blob: 438d567e87cf3e745a2024f9060366d0c5527ec0 [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
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110072static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
73 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110074 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
75// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110076static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110077 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
78 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
79 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
80
jiabin06e4bab2019-07-29 10:13:34 -070081template <typename T>
82bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
83{
84 if (left.size() != right.size()) {
85 return false;
86 }
87 for (size_t index = 0; index < right.size(); index++) {
88 if (left[index] != right[index]) {
89 return false;
90 }
91 }
92 return true;
93}
94
95template <typename T>
96bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
97{
98 return !(left == right);
99}
100
Eric Laurente552edb2014-03-10 17:42:56 -0700101// ----------------------------------------------------------------------------
102// AudioPolicyInterface implementation
103// ----------------------------------------------------------------------------
104
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100105status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
106 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
107 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
113 audio_policy_dev_state_t state,
114 const char* device_address,
115 const char* device_name,
116 audio_format_t encodedFormat) {
117 media::AudioPort aidlPort;
118 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
119 status == OK) {
120 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
121 } else {
122 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
123 return status;
124 }
125}
126
François Gaffie11d30102018-11-02 16:09:09 +0100127void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
128 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200129{
jiabince9f20e2019-09-12 16:29:15 -0700130 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200131 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700132 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100133 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200134 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
135}
136
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100137status_t AudioPolicyManager::setDeviceConnectionStateInt(
138 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
139 audio_format_t encodedFormat) {
140 // TODO: b/211601178 Forward 'port' to Audio HAL via mHwModules. For now, only device_type,
141 // device_address and device_name are forwarded.
142 if (port.ext.getTag() != AudioPortExt::device) {
143 return BAD_VALUE;
144 }
145 audio_devices_t device_type;
146 std::string device_address;
147 if (status_t status = aidl2legacy_AudioDevice_audio_device(
148 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
149 status != OK) {
150 return status;
151 };
152 const char* device_name = port.name.c_str();
153 // connect/disconnect only 1 device at a time
154 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
155 return BAD_VALUE;
156
157 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
158 device_type, device_address.c_str(), device_name, encodedFormat,
159 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
160 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
161}
162
François Gaffie11d30102018-11-02 16:09:09 +0100163status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800164 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100165 const char* device_address,
166 const char* device_name,
167 audio_format_t encodedFormat) {
168 media::AudioPort aidlPort;
169 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
170 status == OK) {
171 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
172 } else {
173 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
174 return status;
175 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176}
Paul McLeane743a472015-01-28 11:07:31 -0800177
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700178status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
179 audio_policy_dev_state_t state)
180{
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700183 SortedVector <audio_io_handle_t> outputs;
184
François Gaffie11d30102018-11-02 16:09:09 +0100185 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700186
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // save a copy of the opened output descriptors before any output is opened or closed
188 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
189 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700190 switch (state)
191 {
192 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800193 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100195 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700196 return INVALID_OPERATION;
197 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800198 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700199 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200202 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700204 }
205
François Gaffie44481e72016-04-20 07:49:57 +0200206 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
207 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100208 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200209
François Gaffie11d30102018-11-02 16:09:09 +0100210 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
211 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200212
Francois Gaffie716e1432019-01-14 16:58:59 +0100213 mHwModules.cleanUpForDevice(device);
214
François Gaffie11d30102018-11-02 16:09:09 +0100215 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700216 return INVALID_OPERATION;
217 }
François Gaffie2110e042015-03-24 08:41:51 +0100218
jiabin1c4794b2020-05-05 10:08:05 -0700219 // Populate encapsulation information when a output device is connected.
220 device->setEncapsulationInfoFromHal(mpClientInterface);
221
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 // outputs should never be empty here
223 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
224 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100225 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700232 return INVALID_OPERATION;
233 }
234
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700236
Paul McLeane743a472015-01-28 11:07:31 -0800237 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100238 broadcastDeviceConnectionState(device, state);
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
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800247 // Reset active device codec
248 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
249
Kriti Dangef6be8f2020-11-05 11:58:19 +0100250 // remove device from mReportedFormatsMap cache
251 mReportedFormatsMap.erase(device);
252
Eric Laurente552edb2014-03-10 17:42:56 -0700253 } break;
254
255 default:
François Gaffie11d30102018-11-02 16:09:09 +0100256 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700257 return BAD_VALUE;
258 }
259
Eric Laurent736a1022019-03-27 18:28:46 -0700260 // Propagate device availability to Engine
261 setEngineDeviceConnectionState(device, state);
262
Eric Laurentae970022019-01-29 14:25:04 -0800263 // No need to evaluate playback routing when connecting a remote submix
264 // output device used by a dynamic policy of type recorder as no
265 // playback use case is affected.
266 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700267 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800268 for (audio_io_handle_t output : outputs) {
269 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800270 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
271 if (policyMix != nullptr
272 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700273 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800274 doCheckForDeviceAndOutputChanges = false;
275 break;
276 }
277 }
278 }
279
280 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700281 // outputs must be closed after checkOutputForAllStrategies() is executed
282 if (!outputs.isEmpty()) {
283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100285 // close unused outputs after device disconnection or direct outputs that have
286 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200287 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
288 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200289 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200290 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700291 closeOutput(output);
292 }
Eric Laurente552edb2014-03-10 17:42:56 -0700293 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
295 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800298 };
299
300 if (doCheckForDeviceAndOutputChanges) {
301 checkForDeviceAndOutputChanges(checkCloseOutputs);
302 } else {
303 checkCloseOutputs();
304 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100305 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700306 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100307 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700308 const DeviceVector activeMediaDevices =
309 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700310 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700311 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530312 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
313 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100314 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700315 // do not force device change on duplicated output because if device is 0, it will
316 // also force a device 0 for the two outputs it is duplicated to which may override
317 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100318 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100319 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700320 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700321 // always force when disconnecting (a non-duplicated device)
322 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100323 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 }
jiabinbce0c1d2020-10-05 11:20:18 -0700325 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000326 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700327 desc->supportsDevicesForPlayback(activeMediaDevices)) {
328 // Reopen the output to query the dynamic profiles when there is not active
329 // clients or all active clients will be rerouted. Otherwise, set the flag
330 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
331 // can be reopened to query dynamic profiles when all clients are inactive.
332 if (areAllActiveTracksRerouted(desc)) {
333 outputsToReopen.push_back(mOutputs.keyAt(i));
334 } else {
335 desc->mPendingReopenToQueryProfiles = true;
336 }
337 }
338 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
339 // Clear the flag that previously set for re-querying profiles.
340 desc->mPendingReopenToQueryProfiles = false;
341 }
342 }
343 for (const auto& output : outputsToReopen) {
344 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
345 closeOutput(output);
346 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700347 }
348
Eric Laurentd60560a2015-04-10 11:31:20 -0700349 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100350 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700351 }
352
Eric Laurent72aa32f2014-05-30 18:51:48 -0700353 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700354 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700355 } // end if is output device
356
Eric Laurente552edb2014-03-10 17:42:56 -0700357 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700358 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100359 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700360 switch (state)
361 {
362 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700363 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100365 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700366 return INVALID_OPERATION;
367 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700368
369 if (mAvailableInputDevices.add(device) < 0) {
370 return NO_MEMORY;
371 }
372
François Gaffie44481e72016-04-20 07:49:57 +0200373 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
374 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100375 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200376
Eric Laurent0dd51852019-04-19 18:18:58 -0700377 if (checkInputsForDevice(device, state) != NO_ERROR) {
378 mAvailableInputDevices.remove(device);
379
François Gaffie11d30102018-11-02 16:09:09 +0100380 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100381
382 mHwModules.cleanUpForDevice(device);
383
Eric Laurentd4692962014-05-05 18:13:44 -0700384 return INVALID_OPERATION;
385 }
386
Eric Laurentd4692962014-05-05 18:13:44 -0700387 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700388
389 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700390 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700391 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100392 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700393 return INVALID_OPERATION;
394 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700395
François Gaffie11d30102018-11-02 16:09:09 +0100396 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700397
398 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100399 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
François Gaffie11d30102018-11-02 16:09:09 +0100401 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700402
403 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100404
405 // remove device from mReportedFormatsMap cache
406 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700407 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700408
409 default:
François Gaffie11d30102018-11-02 16:09:09 +0100410 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700411 return BAD_VALUE;
412 }
413
Eric Laurent736a1022019-03-27 18:28:46 -0700414 // Propagate device availability to Engine
415 setEngineDeviceConnectionState(device, state);
416
Eric Laurent0dd51852019-04-19 18:18:58 -0700417 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700418 // As the input device list can impact the output device selection, update
419 // getDeviceForStrategy() cache
420 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700421
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100422 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200423 // Reconnect Audio Source
424 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
425 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
426 checkAudioSourceForAttributes(attributes);
427 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700428 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100429 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700430 }
431
Eric Laurentb52c1522014-05-20 11:27:36 -0700432 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700433 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700434 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700435
François Gaffie11d30102018-11-02 16:09:09 +0100436 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700437 return BAD_VALUE;
438}
439
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100440status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
441 const char* device_name,
442 media::AudioPort* aidlPort) {
443 DeviceDescriptorBase devDescr(device, device_address);
444 devDescr.setName(device_name);
445 return devDescr.writeToParcelable(aidlPort);
446}
447
Eric Laurent736a1022019-03-27 18:28:46 -0700448void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
449 audio_policy_dev_state_t state) {
450
451 // the Engine does not have to know about remote submix devices used by dynamic audio policies
452 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
453 return;
454 }
455 mEngine->setDeviceConnectionState(device, state);
456}
457
458
Eric Laurente0720872014-03-11 09:30:41 -0700459audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100460 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700461{
Eric Laurent634b7142016-04-20 13:48:02 -0700462 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800463 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
464 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700465 (strlen(device_address) != 0)/*matchAddress*/);
466
467 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100468 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700469 device, device_address);
470 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
471 }
François Gaffie53615e22015-03-19 09:24:12 +0100472
Eric Laurent3a4311c2014-03-17 12:00:47 -0700473 DeviceVector *deviceVector;
474
Eric Laurente552edb2014-03-10 17:42:56 -0700475 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700476 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700477 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700478 deviceVector = &mAvailableInputDevices;
479 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100480 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700482 }
Eric Laurent634b7142016-04-20 13:48:02 -0700483
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800484 return (deviceVector->getDevice(
485 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700486 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800487}
488
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800489status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
490 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800491 const char *device_name,
492 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800493{
494 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700495 String8 reply;
496 AudioParameter param;
497 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800498
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
500 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800502 // connect/disconnect only 1 device at a time
503 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
504
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800505 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700506 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800507 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Nothing to do: device is not connected
509 return NO_ERROR;
510 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700513 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 // configure codecs.
515 // Handle two specific cases by sending a set parameter to
516 // configure A2DP codecs. No need to toggle device state.
517 // Case 1: A2DP active device switches from primary to primary
518 // module
519 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200520 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700521 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
523 if (availablePrimaryOutputDevices().contains(devDesc) &&
524 (module != 0 && module->getHandle() == primaryHandle)) {
525 reply = mpClientInterface->getParameters(
526 AUDIO_IO_HANDLE_NONE,
527 String8(AudioParameter::keyReconfigA2dpSupported));
528 AudioParameter repliedParameters(reply);
529 repliedParameters.getInt(
530 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
531 if (isReconfigA2dpSupported) {
532 const String8 key(AudioParameter::keyReconfigA2dp);
533 param.add(key, String8("true"));
534 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
535 devDesc->setEncodedFormat(encodedFormat);
536 return NO_ERROR;
537 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700538 }
539 }
cnx421bd2dcc42020-07-11 14:58:44 +0800540 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
541 for (size_t i = 0; i < mOutputs.size(); i++) {
542 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
543 // mute media strategies and delay device switch by the largest
544 // This avoid sending the music tail into the earpiece or headset.
545 setStrategyMute(musicStrategy, true, desc);
546 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
547 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
548 nullptr, true /*fromCache*/).types());
549 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800550 // Toggle the device state: UNAVAILABLE -> AVAILABLE
551 // This will force reading again the device configuration
552 status = setDeviceConnectionState(device,
553 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800554 device_address, device_name,
555 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800556 if (status != NO_ERROR) {
557 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
558 status);
559 return status;
560 }
561
562 status = setDeviceConnectionState(device,
563 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800564 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800565 if (status != NO_ERROR) {
566 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
567 status);
568 return status;
569 }
570
571 return NO_ERROR;
572}
573
Pattydd807582021-11-04 21:01:03 +0800574status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
575 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800576{
Pattydd807582021-11-04 21:01:03 +0800577 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800578 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800579 std::unordered_set<audio_format_t> formatSet;
580 sp<HwModule> primaryModule =
581 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700582 if (primaryModule == nullptr) {
583 ALOGE("%s() unable to get primary module", __func__);
584 return NO_INIT;
585 }
Pattydd807582021-11-04 21:01:03 +0800586
587 DeviceTypeSet audioDeviceSet;
588
589 switch(device) {
590 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
591 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
592 break;
593 case AUDIO_DEVICE_OUT_BLE_HEADSET:
594 audioDeviceSet = getAudioDeviceOutAllBleSet();
595 break;
596 default:
597 ALOGE("%s() device type 0x%08x not supported", __func__, device);
598 return BAD_VALUE;
599 }
600
jiabin9a3361e2019-10-01 09:38:30 -0700601 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800602 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800603 for (const auto& device : declaredDevices) {
604 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800605 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800606 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800607 return status;
608}
609
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100610DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
611{
612 DeviceVector rxSinkdevices{};
613 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
614 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
615 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
616 auto rxSinkDevice = rxSinkdevices.itemAt(0);
617 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
618 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
619 // retrieve Rx Source device descriptor
620 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
621 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
622
623 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
624 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
625 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
626 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
627 return DeviceVector(rxSinkDevice);
628 }
629 }
630 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
631 // the device returned is not necessarily reachable via this output
632 // (filter later by setOutputDevices())
633 return getNewOutputDevices(mPrimaryOutput, fromCache);
634}
635
636status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
637{
638 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
639 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
640 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
641 }
642 return INVALID_OPERATION;
643}
644
645status_t AudioPolicyManager::updateCallRoutingInternal(
646 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700647{
648 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100649 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700650 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700651 if(!hasPrimaryOutput() ||
652 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100653 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700654 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100655 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100656
Francois Gaffie716e1432019-01-14 16:58:59 +0100657 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100658 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100659 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100660
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100661 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100662 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700663
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200664 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 // release TX patch if any
666 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100667 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 mCallTxPatch.clear();
669 }
670
François Gaffie9eb18552018-11-05 10:33:26 +0100671 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700672 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100673 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700674 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100675 // retrieve Rx Source and Tx Sink device descriptors
676 sp<DeviceDescriptor> rxSourceDevice =
677 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
678 String8(),
679 AUDIO_FORMAT_DEFAULT);
680 sp<DeviceDescriptor> txSinkDevice =
681 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
682 String8(),
683 AUDIO_FORMAT_DEFAULT);
684
685 // RX and TX Telephony device are declared by Primary Audio HAL
686 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
687 (telephonyRxModule->getHalVersionMajor() >= 3)) {
688 if (rxSourceDevice == 0 || txSinkDevice == 0) {
689 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100690 ALOGE("%s() no telephony Tx and/or RX device", __func__);
691 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100692 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100693 // createAudioPatchInternal now supports both HW / SW bridging
694 createRxPatch = true;
695 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100696 } else {
697 // If the RX device is on the primary HW module, then use legacy routing method for
698 // voice calls via setOutputDevice() on primary output.
699 // Otherwise, create two audio patches for TX and RX path.
700 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
701 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700702 // If the TX device is also on the primary HW module, setOutputDevice() will take care
703 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100704 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
705 (txSinkDevice != 0);
706 }
707 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
708 // Otherwise, create two audio patches for TX and RX path.
709 if (!createRxPatch) {
710 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700711 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200712 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800713 // If the TX device is on the primary HW module but RX device is
714 // on other HW module, SinkMetaData of telephony input should handle it
715 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700716 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700717 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100718 // terminate active capture if on the same HW module as the call TX source device
719 // FIXME: would be better to refine to only inputs whose profile connects to the
720 // call TX device but this information is not in the audio patch and logic here must be
721 // symmetric to the one in startInput()
722 for (const auto& activeDesc : mInputs.getActiveInputs()) {
723 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
724 closeActiveClients(activeDesc);
725 }
726 }
François Gaffie9eb18552018-11-05 10:33:26 +0100727 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800728 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100729 if (waitMs != nullptr) {
730 *waitMs = muteWaitMs;
731 }
732 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800733}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700734
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800735sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100736 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700737 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738
François Gaffie11d30102018-11-02 16:09:09 +0100739 if (device == nullptr) {
740 return nullptr;
741 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100742
743 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800744 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100745 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800746 addSource(mAvailableInputDevices.getDevice(
747 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800748 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100749 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800750 addSink(mAvailableOutputDevices.getDevice(
751 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800752 }
753
François Gaffieafd4cea2019-11-18 15:50:22 +0100754 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
755 status_t status =
756 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
757 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
758 if (status != NO_ERROR || index < 0) {
759 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
760 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800761 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100762 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763}
764
Mikhail Naganov100f0122018-11-29 11:22:16 -0800765bool AudioPolicyManager::isDeviceOfModule(
766 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
767 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
768 if (module != 0) {
769 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND
771 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
772 .indexOf(devDesc) != NAME_NOT_FOUND;
773 }
774 return false;
775}
776
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200777void AudioPolicyManager::connectTelephonyRxAudioSource()
778{
779 disconnectTelephonyRxAudioSource();
780 const struct audio_port_config source = {
781 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
782 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
783 };
784 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
785 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
786 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
787}
788
789void AudioPolicyManager::disconnectTelephonyRxAudioSource()
790{
791 stopAudioSource(mCallRxSourceClientPort);
792 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
793}
794
Eric Laurente0720872014-03-11 09:30:41 -0700795void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700796{
797 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100798 // store previous phone state for management of sonification strategy below
799 int oldState = mEngine->getPhoneState();
800
801 if (mEngine->setPhoneState(state) != NO_ERROR) {
802 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700803 return;
804 }
François Gaffie2110e042015-03-24 08:41:51 +0100805 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700806 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700807 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700808 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800809 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700810 }
811
François Gaffie2110e042015-03-24 08:41:51 +0100812 /**
813 * Switching to or from incall state or switching between telephony and VoIP lead to force
814 * routing command.
815 */
Eric Laurent74b71512019-11-06 17:21:57 -0800816 bool force = ((isStateInCall(oldState) != isStateInCall(state))
817 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700818
819 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700820 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700821
Eric Laurente552edb2014-03-10 17:42:56 -0700822 int delayMs = 0;
823 if (isStateInCall(state)) {
824 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100825 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
826 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700827 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700828 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700829 // mute media and sonification strategies and delay device switch by the largest
830 // latency of any output where either strategy is active.
831 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100832 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
833 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
834 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700835 (delayMs < (int)desc->latency()*2)) {
836 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700837 }
François Gaffiec005e562018-11-06 15:04:49 +0100838 setStrategyMute(musicStrategy, true, desc);
839 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
840 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
841 nullptr, true /*fromCache*/).types());
842 setStrategyMute(sonificationStrategy, true, desc);
843 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
844 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
845 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700846 }
847 }
848
Eric Laurent87ffa392015-05-22 10:32:38 -0700849 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700850 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100851 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700852 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100853 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
854 // force routing command to audio hardware when ending call
855 // even if no device change is needed
856 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
857 rxDevices = mPrimaryOutput->devices();
858 }
859 if (oldState == AUDIO_MODE_IN_CALL) {
860 disconnectTelephonyRxAudioSource();
861 if (mCallTxPatch != 0) {
862 releaseAudioPatchInternal(mCallTxPatch->getHandle());
863 mCallTxPatch.clear();
864 }
865 }
François Gaffie11d30102018-11-02 16:09:09 +0100866 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700867 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700868 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700869
870 // reevaluate routing on all outputs in case tracks have been started during the call
871 for (size_t i = 0; i < mOutputs.size(); i++) {
872 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100873 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700874 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100875 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700876 }
877 }
878
Eric Laurente552edb2014-03-10 17:42:56 -0700879 if (isStateInCall(state)) {
880 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700881 // force reevaluating accessibility routing when call starts
882 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700883 }
884
885 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100886 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
887 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700888}
889
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700890audio_mode_t AudioPolicyManager::getPhoneState() {
891 return mEngine->getPhoneState();
892}
893
Eric Laurente0720872014-03-11 09:30:41 -0700894void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100895 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700896{
François Gaffie2110e042015-03-24 08:41:51 +0100897 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700898 if (config == mEngine->getForceUse(usage)) {
899 return;
900 }
Eric Laurente552edb2014-03-10 17:42:56 -0700901
François Gaffie2110e042015-03-24 08:41:51 +0100902 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
903 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
904 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700905 }
François Gaffie2110e042015-03-24 08:41:51 +0100906 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
907 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
908 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700909
910 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700911 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800912
Eric Laurent22fcda22019-05-17 16:28:47 -0700913 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
914 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
915 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
916 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
917 }
918
Eric Laurentdc462862016-07-19 12:29:53 -0700919 //FIXME: workaround for truncated touch sounds
920 // to be removed when the problem is handled by system UI
921 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700922 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
923 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
924 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700925
926 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100927 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700928}
929
Eric Laurente0720872014-03-11 09:30:41 -0700930void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700931{
932 ALOGV("setSystemProperty() property %s, value %s", property, value);
933}
934
Michael Chana94fbb22018-04-24 14:31:19 +1000935// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
936// search to profiles for direct outputs.
937sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100938 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000939 uint32_t samplingRate,
940 audio_format_t format,
941 audio_channel_mask_t channelMask,
942 audio_output_flags_t flags,
943 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700944{
Michael Chana94fbb22018-04-24 14:31:19 +1000945 if (directOnly) {
946 // only retain flags that will drive the direct output profile selection
947 // if explicitly requested
948 static const uint32_t kRelevantFlags =
949 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700950 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000951 flags =
952 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
953 }
Eric Laurent861a6282015-05-18 15:40:16 -0700954
955 sp<IOProfile> profile;
956
Mikhail Naganovd4120142017-12-06 15:49:22 -0800957 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800958 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100959 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700960 samplingRate, NULL /*updatedSamplingRate*/,
961 format, NULL /*updatedFormat*/,
962 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700963 flags)) {
964 continue;
965 }
966 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100967 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700968 continue;
969 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800970 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700971 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800972 continue;
973 }
Michael Chana94fbb22018-04-24 14:31:19 +1000974 if (!directOnly) return curProfile;
975 // when searching for direct outputs, if several profiles are compatible, give priority
976 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100977 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700978 continue;
979 }
980 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100981 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700982 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700983 }
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
985 }
Eric Laurent861a6282015-05-18 15:40:16 -0700986 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700987}
988
Eric Laurentfa0f6742021-08-17 18:39:44 +0200989sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200990 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200991{
992 for (const auto& hwModule : mHwModules) {
993 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200994 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200995 continue;
996 }
997 // reject profiles not corresponding to a device currently available
998 DeviceVector supportedDevices = curProfile->getSupportedDevices();
999 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1000 continue;
1001 }
1002 if (!devices.empty()) {
1003 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1004 != devices.size()) {
1005 continue;
1006 }
1007 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001008 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1009 return curProfile;
1010 }
1011 }
1012 return nullptr;
1013}
1014
Eric Laurentf4e63452017-11-06 19:31:46 +00001015audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001016{
François Gaffiec005e562018-11-06 15:04:49 +01001017 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001018
1019 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1020 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1021 // format, flags, etc. This may result in some discrepancy for functions that utilize
1022 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1023 // and AudioSystem::getOutputSamplingRate().
1024
François Gaffie11d30102018-11-02 16:09:09 +01001025 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001026 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001027
François Gaffie11d30102018-11-02 16:09:09 +01001028 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1029 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001030 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001031}
1032
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001033status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1034 const audio_attributes_t *srcAttr,
1035 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001036{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001037 if (srcAttr != NULL) {
1038 if (!isValidAttributes(srcAttr)) {
1039 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1040 __func__,
1041 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1042 srcAttr->tags);
1043 return BAD_VALUE;
1044 }
1045 *dstAttr = *srcAttr;
1046 } else {
1047 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1048 ALOGE("%s: invalid stream type", __func__);
1049 return BAD_VALUE;
1050 }
François Gaffiec005e562018-11-06 15:04:49 +01001051 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001052 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001053
1054 // Only honor audibility enforced when required. The client will be
1055 // forced to reconnect if the forced usage changes.
1056 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001057 dstAttr->flags = static_cast<audio_flags_mask_t>(
1058 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001059 }
1060
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001061 return NO_ERROR;
1062}
1063
Kevin Rocard153f92d2018-12-18 18:33:28 -08001064status_t AudioPolicyManager::getOutputForAttrInt(
1065 audio_attributes_t *resultAttr,
1066 audio_io_handle_t *output,
1067 audio_session_t session,
1068 const audio_attributes_t *attr,
1069 audio_stream_type_t *stream,
1070 uid_t uid,
1071 const audio_config_t *config,
1072 audio_output_flags_t *flags,
1073 audio_port_handle_t *selectedDeviceId,
1074 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001075 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001076 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001077{
François Gaffiec005e562018-11-06 15:04:49 +01001078 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001079 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001080 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001081 const sp<DeviceDescriptor> requestedDevice =
1082 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1083
Eric Laurent8a1095a2019-11-08 14:44:16 -08001084 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001085 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1086 if (status != NO_ERROR) {
1087 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001088 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001089 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001090 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001091 }
François Gaffiec005e562018-11-06 15:04:49 +01001092 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001093
François Gaffiec005e562018-11-06 15:04:49 +01001094 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1095 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001096
Kevin Rocard153f92d2018-12-18 18:33:28 -08001097 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1098 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1099 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001100 sp<AudioPolicyMix> primaryMix;
1101 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001102 if (status != OK) {
1103 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001104 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001105
Kevin Rocard153f92d2018-12-18 18:33:28 -08001106 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001107 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001108
1109 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001110 if ((usePrimaryOutputFromPolicyMixes
1111 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001112 && !audio_is_linear_pcm(config->format)) {
1113 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001114 return BAD_VALUE;
1115 }
1116 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001117 sp<DeviceDescriptor> deviceDesc =
1118 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1119 primaryMix->mDeviceAddress,
1120 AUDIO_FORMAT_DEFAULT);
1121 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001122 if (deviceDesc != nullptr
1123 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001124 audio_io_handle_t newOutput;
1125 status = openDirectOutput(
1126 *stream, session, config,
1127 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1128 DeviceVector(deviceDesc), &newOutput);
1129 if (status != NO_ERROR) {
1130 policyDesc = nullptr;
1131 } else {
1132 policyDesc = mOutputs.valueFor(newOutput);
1133 primaryMix->setOutput(policyDesc);
1134 }
1135 }
1136 if (policyDesc != nullptr) {
1137 policyDesc->mPolicyMix = primaryMix;
1138 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001139 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001140
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001141 ALOGV("getOutputForAttr() returns output %d", *output);
1142 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1143 *outputType = API_OUT_MIX_PLAYBACK;
1144 } else {
1145 *outputType = API_OUTPUT_LEGACY;
1146 }
1147 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001148 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001149 }
François Gaffiec005e562018-11-06 15:04:49 +01001150 // Virtual sources must always be dynamicaly or explicitly routed
1151 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1152 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1153 return BAD_VALUE;
1154 }
1155 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1156 // in order to let the choice of the order to future vendor engine
1157 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001158
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001159 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001160 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001161 }
1162
Nadav Barb2f18162018-07-18 13:01:53 +03001163 // Set incall music only if device was explicitly set, and fallback to the device which is
1164 // chosen by the engine if not.
1165 // FIXME: provide a more generic approach which is not device specific and move this back
1166 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001167 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001168 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001169 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001170 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001171 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001172 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001173 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001174 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001175 }
1176 }
1177
François Gaffiec005e562018-11-06 15:04:49 +01001178 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1179 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1180 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001181
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001182 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001183 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001184 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001185 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001186 ALOGV("%s() Using MSD devices %s instead of devices %s",
1187 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001188 } else {
1189 *output = AUDIO_IO_HANDLE_NONE;
1190 }
1191 }
1192 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001193 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001194 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001195 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001196 if (*output == AUDIO_IO_HANDLE_NONE) {
1197 return INVALID_OPERATION;
1198 }
Paul McLeanaa981192015-03-21 09:55:15 -07001199
François Gaffiec005e562018-11-06 15:04:49 +01001200 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001201 for (auto &outputDevice : outputDevices) {
1202 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1203 *selectedDeviceId = outputDevice->getId();
1204 break;
1205 }
1206 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001207
Eric Laurent8a1095a2019-11-08 14:44:16 -08001208 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1209 *outputType = API_OUTPUT_TELEPHONY_TX;
1210 } else {
1211 *outputType = API_OUTPUT_LEGACY;
1212 }
1213
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001214 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1215
1216 return NO_ERROR;
1217}
1218
1219status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1220 audio_io_handle_t *output,
1221 audio_session_t session,
1222 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001223 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001224 const audio_config_t *config,
1225 audio_output_flags_t *flags,
1226 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001227 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001228 std::vector<audio_io_handle_t> *secondaryOutputs,
1229 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001230{
1231 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1232 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1233 return INVALID_OPERATION;
1234 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001235 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001236 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001237 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001238 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001239 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001240 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001241 const sp<DeviceDescriptor> requestedDevice =
1242 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1243
1244 // Prevent from storing invalid requested device id in clients
1245 const audio_port_handle_t sanitizedRequestedPortId =
1246 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1247 *selectedDeviceId = sanitizedRequestedPortId;
1248
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001249 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001250 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001251 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001252 if (status != NO_ERROR) {
1253 return status;
1254 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001255 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001256 if (secondaryOutputs != nullptr) {
1257 for (auto &secondaryMix : secondaryMixes) {
1258 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1259 if (outputDesc != nullptr &&
1260 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1261 secondaryOutputs->push_back(outputDesc->mIoHandle);
1262 weakSecondaryOutputDescs.push_back(outputDesc);
1263 }
1264 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001265 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001266
Eric Laurent8fc147b2018-07-22 19:13:55 -07001267 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001268 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001269 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001270 };
jiabin4ef93452019-09-10 14:29:54 -07001271 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001272
Eric Laurentc209fe42020-06-05 18:11:23 -07001273 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001274 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001275 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001276 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001277 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001278 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001279 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001280 std::move(weakSecondaryOutputDescs),
1281 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001282 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001283
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001284 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1285 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001286
Eric Laurente83b55d2014-11-14 10:06:21 -08001287 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001288}
1289
Eric Laurentc529cf62020-04-17 18:19:10 -07001290status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1291 audio_session_t session,
1292 const audio_config_t *config,
1293 audio_output_flags_t flags,
1294 const DeviceVector &devices,
1295 audio_io_handle_t *output) {
1296
1297 *output = AUDIO_IO_HANDLE_NONE;
1298
1299 // skip direct output selection if the request can obviously be attached to a mixed output
1300 // and not explicitly requested
1301 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1302 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1303 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1304 return NAME_NOT_FOUND;
1305 }
1306
1307 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1308 // This prevents creating an offloaded track and tearing it down immediately after start
1309 // when audioflinger detects there is an active non offloadable effect.
1310 // FIXME: We should check the audio session here but we do not have it in this context.
1311 // This may prevent offloading in rare situations where effects are left active by apps
1312 // in the background.
1313 sp<IOProfile> profile;
1314 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1315 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1316 profile = getProfileForOutput(
1317 devices, config->sample_rate, config->format, config->channel_mask,
1318 flags, true /* directOnly */);
1319 }
1320
1321 if (profile == nullptr) {
1322 return NAME_NOT_FOUND;
1323 }
1324
1325 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1326 for (size_t i = 0; i < mOutputs.size(); i++) {
1327 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1328 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1329 // reuse direct output if currently open by the same client
1330 // and configured with same parameters
1331 if ((config->sample_rate == desc->getSamplingRate()) &&
1332 (config->format == desc->getFormat()) &&
1333 (config->channel_mask == desc->getChannelMask()) &&
1334 (session == desc->mDirectClientSession)) {
1335 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001336 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001337 mOutputs.keyAt(i), session);
1338 *output = mOutputs.keyAt(i);
1339 return NO_ERROR;
1340 }
1341 }
1342 }
1343
1344 if (!profile->canOpenNewIo()) {
1345 return NAME_NOT_FOUND;
1346 }
1347
1348 sp<SwAudioOutputDescriptor> outputDesc =
1349 new SwAudioOutputDescriptor(profile, mpClientInterface);
1350
Michael Chan6fb34492020-12-08 15:44:49 +11001351 // An MSD patch may be using the only output stream that can service this request. Release
1352 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001353 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001354
Eric Laurentf1f22e72021-07-13 14:04:14 +02001355 status_t status =
1356 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001357
1358 // only accept an output with the requested parameters
1359 if (status != NO_ERROR ||
1360 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1361 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1362 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1363 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1364 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1365 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1366 config->channel_mask, outputDesc->getChannelMask());
1367 if (*output != AUDIO_IO_HANDLE_NONE) {
1368 outputDesc->close();
1369 }
1370 // fall back to mixer output if possible when the direct output could not be open
1371 if (audio_is_linear_pcm(config->format) &&
1372 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1373 return NAME_NOT_FOUND;
1374 }
1375 *output = AUDIO_IO_HANDLE_NONE;
1376 return BAD_VALUE;
1377 }
1378 outputDesc->mDirectOpenCount = 1;
1379 outputDesc->mDirectClientSession = session;
1380
1381 addOutput(*output, outputDesc);
1382 mPreviousOutputs = mOutputs;
1383 ALOGV("%s returns new direct output %d", __func__, *output);
1384 mpClientInterface->onAudioPortListUpdate();
1385 return NO_ERROR;
1386}
1387
François Gaffie11d30102018-11-02 16:09:09 +01001388audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1389 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001390 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001391 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001392 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001393 audio_output_flags_t *flags,
1394 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001395{
Andy Hungc88b0642018-04-27 15:42:35 -07001396 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001397
jiabine375d412019-02-26 12:54:53 -08001398 // Discard haptic channel mask when forcing muting haptic channels.
1399 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001400 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1401 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001402
Eric Laurente552edb2014-03-10 17:42:56 -07001403 // open a direct output if required by specified parameters
1404 //force direct flag if offload flag is set: offloading implies a direct output stream
1405 // and all common behaviors are driven by checking only the direct flag
1406 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001407 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1408 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001409 }
Nadav Bar766fb022018-01-07 12:18:03 +02001410 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1411 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001412 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001413
1414 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1415
Eric Laurente83b55d2014-11-14 10:06:21 -08001416 // only allow deep buffering for music stream type
1417 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001418 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001419 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001420 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001421 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1422 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001423 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001424 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001425 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001426 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001427 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001428 audio_is_linear_pcm(config->format) &&
1429 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001430 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001431 AUDIO_OUTPUT_FLAG_DIRECT);
1432 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001433 }
Eric Laurente552edb2014-03-10 17:42:56 -07001434
Carter Hsua3abb402021-10-26 11:11:20 +08001435 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1436 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1437 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1438 }
1439
Eric Laurentfa0f6742021-08-17 18:39:44 +02001440 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001441 && canBeSpatializedInt(attr, config,
1442 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001443 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001444 }
1445
Eric Laurentc529cf62020-04-17 18:19:10 -07001446 audio_config_t directConfig = *config;
1447 directConfig.channel_mask = channelMask;
1448 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1449 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001450 return output;
1451 }
1452
Eric Laurent14cbfca2016-03-17 09:42:16 -07001453 // A request for HW A/V sync cannot fallback to a mixed output because time
1454 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001455 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001456 return AUDIO_IO_HANDLE_NONE;
1457 }
1458
Eric Laurente552edb2014-03-10 17:42:56 -07001459 // ignoring channel mask due to downmix capability in mixer
1460
1461 // open a non direct output
1462
1463 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001464 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001465 // get which output is suitable for the specified stream. The actual
1466 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001467 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001468
Eric Laurent8838a382014-09-08 16:44:28 -07001469 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001470 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001471 output = selectOutput(
1472 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001473 }
François Gaffie11d30102018-11-02 16:09:09 +01001474 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001475 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001476 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001477
Eric Laurente552edb2014-03-10 17:42:56 -07001478 return output;
1479}
1480
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001481sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001482 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1483 mAvailableInputDevices);
1484 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1485}
1486
1487DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1488 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1489 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001490}
1491
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001492const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001493 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001494 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1495 if (msdModule != 0) {
1496 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1497 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1498 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1499 const struct audio_port_config *source = &patch->mPatch.sources[j];
1500 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1501 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001502 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001503 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001504 }
1505 }
1506 }
1507 return msdPatches;
1508}
1509
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001510status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1511 const InputProfileCollection &inputProfiles,
1512 const OutputProfileCollection &outputProfiles,
1513 const sp<DeviceDescriptor> &sourceDevice,
1514 const sp<DeviceDescriptor> &sinkDevice,
1515 AudioProfileVector& sourceProfiles,
1516 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001517 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001518 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001519 return NO_INIT;
1520 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001521 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001522 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001523 return NO_INIT;
1524 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001525 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001526 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1527 inProfile->supportsDevice(sourceDevice)) {
1528 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001529 }
1530 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001531 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001532 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001533 outProfile->supportsDevice(sinkDevice)) {
1534 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001535 }
1536 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001537 return NO_ERROR;
1538}
1539
1540status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1541 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1542 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1543{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001544 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001545 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1546 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1547 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001548 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001549 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1550 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001551 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001552 }
1553 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1554 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1555 sinkConfig->format = bestSinkConfig.format;
1556 // For encoded streams force direct flag to prevent downstream mixing.
1557 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1558 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001559 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1560 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001561 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001562 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1563 // raw and IEC61937 framed streams.
1564 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1565 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1566 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001567 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1568 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1569 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1570 sourceConfig->format = bestSinkConfig.format;
1571 // Copy input stream directly without any processing (e.g. resampling).
1572 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1573 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1574 if (hwAvSync) {
1575 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1576 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1577 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1578 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1579 }
1580 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1581 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1582 sinkConfig->config_mask |= config_mask;
1583 sourceConfig->config_mask |= config_mask;
1584 return NO_ERROR;
1585}
1586
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001587PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1588 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001589{
1590 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001591 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1592 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1593 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1594 if (deviceModule == nullptr) {
1595 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1596 return patchBuilder;
1597 }
1598 const InputProfileCollection inputProfiles = msdIsSource ?
1599 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1600 const OutputProfileCollection outputProfiles = msdIsSource ?
1601 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1602
1603 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1604 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1605 device : getMsdAudioOutDevices().itemAt(0);
1606 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1607
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001608 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1609 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610 AudioProfileVector sourceProfiles;
1611 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001612 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1613 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001614 for (auto hwAvSync : { true, false }) {
1615 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1616 sourceProfiles, sinkProfiles) != NO_ERROR) {
1617 continue;
1618 }
1619 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1620 &sinkConfig) == NO_ERROR) {
1621 // Found a matching config. Re-create PatchBuilder with this config.
1622 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1623 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001625 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001626 " supporting PCM format conversion.", __func__);
1627 return patchBuilder;
1628}
1629
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001631 DeviceVector devices;
1632 if (outputDevices != nullptr && outputDevices->size() > 0) {
1633 devices.add(*outputDevices);
1634 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001635 // Use media strategy for unspecified output device. This should only
1636 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1637 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001638 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001639 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001640 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001641 }
Michael Chan6fb34492020-12-08 15:44:49 +11001642 std::vector<PatchBuilder> patchesToCreate;
1643 for (auto i = 0u; i < devices.size(); ++i) {
1644 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001645 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001646 }
1647 // Retain only the MSD patches associated with outputDevices request.
1648 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001649 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001650 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1651 auto retainedPatch = false;
1652 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1653 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1654 patchesToRemove.removeItemsAt(i);
1655 retainedPatch = true;
1656 break;
1657 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001658 }
Michael Chan6fb34492020-12-08 15:44:49 +11001659 if (retainedPatch) {
1660 it = patchesToCreate.erase(it);
1661 continue;
1662 }
1663 ++it;
1664 }
1665 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1666 return NO_ERROR;
1667 }
1668 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1669 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001670 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001671 }
Michael Chan6fb34492020-12-08 15:44:49 +11001672 status_t status = NO_ERROR;
1673 for (const auto &p : patchesToCreate) {
1674 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1675 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1676 char message[256];
1677 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1678 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1679 currStatus == NO_ERROR ? "Success" : "Error",
1680 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1681 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1682 if (currStatus == NO_ERROR) {
1683 ALOGD("%s", message);
1684 } else {
1685 ALOGE("%s", message);
1686 if (status == NO_ERROR) {
1687 status = currStatus;
1688 }
1689 }
1690 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001691 return status;
1692}
1693
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001694void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1695 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001696 for (size_t i = 0; i < msdPatches.size(); i++) {
1697 const auto& patch = msdPatches[i];
1698 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1699 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1700 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1701 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1702 releaseAudioPatch(patch->getHandle(), mUidCached);
1703 break;
1704 }
1705 }
1706 }
1707}
1708
Eric Laurente0720872014-03-11 09:30:41 -07001709audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001710 audio_output_flags_t flags,
1711 audio_format_t format,
1712 audio_channel_mask_t channelMask,
1713 uint32_t samplingRate,
1714 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001715{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001716 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1717 "%s called with format %#x", __func__, format);
1718
jiabinebb6af42020-06-09 17:31:17 -07001719 // Return the output that haptic-generating attached to when 1) session id is specified,
1720 // 2) haptic-generating effect exists for given session id and 3) the output that
1721 // haptic-generating effect attached to is in given outputs.
1722 if (sessionId != AUDIO_SESSION_NONE) {
1723 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1724 sessionId, FX_IID_HAPTICGENERATOR);
1725 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1726 return hapticGeneratingOutput;
1727 }
1728 }
1729
Eric Laurent16c66dd2019-05-01 17:54:10 -07001730 // Flags disqualifying an output: the match must happen before calling selectOutput()
1731 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1732 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1733
1734 // Flags expressing a functional request: must be honored in priority over
1735 // other criteria
1736 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1737 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001738 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1739 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001740 // Flags expressing a performance request: have lower priority than serving
1741 // requested sampling rate or channel mask
1742 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1743 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1744 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1745
1746 const audio_output_flags_t functionalFlags =
1747 (audio_output_flags_t)(flags & kFunctionalFlags);
1748 const audio_output_flags_t performanceFlags =
1749 (audio_output_flags_t)(flags & kPerformanceFlags);
1750
1751 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1752
Eric Laurente552edb2014-03-10 17:42:56 -07001753 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001754 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001755 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001756 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001757 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001758 // with tiebreak preferring the minimum number of extra functional flags
1759 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001760 // 3: the output supporting the exact channel mask
1761 // 4: the output with a higher channel count than requested
1762 // 5: the output with a higher sampling rate than requested
1763 // 6: the output with the highest number of requested performance flags
1764 // 7: the output with the bit depth the closest to the requested one
1765 // 8: the primary output
1766 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001767
Eric Laurent16c66dd2019-05-01 17:54:10 -07001768 // matching criteria values in priority order for best matching output so far
1769 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001770
Eric Laurent16c66dd2019-05-01 17:54:10 -07001771 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1772 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1773 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001774
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001775 for (audio_io_handle_t output : outputs) {
1776 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001777 // matching criteria values in priority order for current output
1778 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001779
Eric Laurent16c66dd2019-05-01 17:54:10 -07001780 if (outputDesc->isDuplicated()) {
1781 continue;
1782 }
1783 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1784 continue;
1785 }
Eric Laurent8838a382014-09-08 16:44:28 -07001786
Eric Laurent16c66dd2019-05-01 17:54:10 -07001787 // If haptic channel is specified, use the haptic output if present.
1788 // When using haptic output, same audio format and sample rate are required.
1789 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001790 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001791 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1792 continue;
1793 }
1794 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001795 && format == outputDesc->getFormat()
1796 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001797 currentMatchCriteria[0] = outputHapticChannelCount;
1798 }
1799
1800 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001801 const int matchingFunctionalFlags =
1802 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1803 const int totalFunctionalFlags =
1804 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1805 // Prefer matching functional flags, but subtract unnecessary functional flags.
1806 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001807
1808 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001809 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1810 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001811 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1812 channelCount <= outputChannelCount) {
1813 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001814 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1815 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001816 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001817 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001818 currentMatchCriteria[3] = outputChannelCount;
1819 }
1820
1821 // sampling rate match
1822 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001823 samplingRate <= outputDesc->getSamplingRate()) {
1824 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001825 }
1826
1827 // performance flags match
1828 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1829
1830 // format match
1831 if (format != AUDIO_FORMAT_INVALID) {
1832 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001833 PolicyAudioPort::kFormatDistanceMax -
1834 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001835 }
1836
1837 // primary output match
1838 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1839
1840 // compare match criteria by priority then value
1841 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1842 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1843 bestMatchCriteria = currentMatchCriteria;
1844 bestOutput = output;
1845
1846 std::stringstream result;
1847 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1848 std::ostream_iterator<int>(result, " "));
1849 ALOGV("%s new bestOutput %d criteria %s",
1850 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001851 }
1852 }
1853
Eric Laurent16c66dd2019-05-01 17:54:10 -07001854 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001855}
1856
Eric Laurent8fc147b2018-07-22 19:13:55 -07001857status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001858{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001859 ALOGV("%s portId %d", __FUNCTION__, portId);
1860
1861 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1862 if (outputDesc == 0) {
1863 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001864 return BAD_VALUE;
1865 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001866 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001867
Eric Laurent8fc147b2018-07-22 19:13:55 -07001868 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001869 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001870
Eric Laurent733ce942017-12-07 12:18:25 -08001871 status_t status = outputDesc->start();
1872 if (status != NO_ERROR) {
1873 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001874 }
1875
Eric Laurent97ac8712018-07-27 18:59:02 -07001876 uint32_t delayMs;
1877 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001878
1879 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001880 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001881 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001882 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001883 if (delayMs != 0) {
1884 usleep(delayMs * 1000);
1885 }
1886
1887 return status;
1888}
1889
Eric Laurent97ac8712018-07-27 18:59:02 -07001890status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1891 const sp<TrackClientDescriptor>& client,
1892 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001893{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001894 // cannot start playback of STREAM_TTS if any other output is being used
1895 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001896
1897 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001898 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001899 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001900 auto clientStrategy = client->strategy();
1901 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001902 if (stream == AUDIO_STREAM_TTS) {
1903 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001904 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001905 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001906 return INVALID_OPERATION;
1907 } else {
1908 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1909 }
1910 } else {
1911 // some playback other than beacon starts
1912 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1913 }
1914
Eric Laurent77305a62016-07-25 16:39:22 -07001915 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001916 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001917 bool force = !outputDesc->isActive() &&
1918 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001919
François Gaffie11d30102018-11-02 16:09:09 +01001920 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001921 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001922 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001923 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001924 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001925 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001926 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001927 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001928 } else {
1929 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001930 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001931 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1932 AUDIO_FORMAT_DEFAULT);
1933 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1934 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001935 }
1936
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001937 // requiresMuteCheck is false when we can bypass mute strategy.
1938 // It covers a common case when there is no materially active audio
1939 // and muting would result in unnecessary delay and dropped audio.
1940 const uint32_t outputLatencyMs = outputDesc->latency();
1941 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1942
Eric Laurente552edb2014-03-10 17:42:56 -07001943 // increment usage count for this stream on the requested output:
1944 // NOTE that the usage count is the same for duplicated output and hardware output which is
1945 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001946 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001947
1948 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001949 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1950 client->isPreferredDeviceForExclusiveUse()) {
1951 // Preferred device may be exclusive, use only if no other active clients on this output
1952 devices = DeviceVector(
1953 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1954 } else {
1955 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1956 }
François Gaffie11d30102018-11-02 16:09:09 +01001957 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001958 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001959 }
1960 }
Eric Laurente552edb2014-03-10 17:42:56 -07001961
François Gaffiec005e562018-11-06 15:04:49 +01001962 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001963 selectOutputForMusicEffects();
1964 }
1965
François Gaffie1c878552018-11-22 16:53:21 +01001966 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001967 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001968 if (devices.isEmpty()) {
1969 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001970 }
François Gaffiec005e562018-11-06 15:04:49 +01001971 bool shouldWait =
1972 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1973 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1974 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001975 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001976 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001978 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001979 // An output has a shared device if
1980 // - managed by the same hw module
1981 // - supports the currently selected device
1982 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001983 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001984
Eric Laurent77305a62016-07-25 16:39:22 -07001985 // force a device change if any other output is:
1986 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001987 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001988 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001989 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001990 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001991 // change the device currently selected by the other output.
1992 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001993 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001994 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001995 force = true;
1996 }
1997 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001998 // a notification so that audio focus effect can propagate, or that a mute/unmute
1999 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002000 const uint32_t latencyMs = desc->latency();
2001 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2002
2003 if (shouldWait && isActive && (waitMs < latencyMs)) {
2004 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002005 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002006
2007 // Require mute check if another output is on a shared device
2008 // and currently active to have proper drain and avoid pops.
2009 // Note restoring AudioTracks onto this output needs to invoke
2010 // a volume ramp if there is no mute.
2011 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002012 }
2013 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002014
2015 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002016 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002017
Eric Laurente552edb2014-03-10 17:42:56 -07002018 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002019 auto &curves = getVolumeCurves(client->attributes());
2020 checkAndSetVolume(curves, client->volumeSource(),
2021 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002022 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002023 outputDesc->devices().types(), 0 /*delay*/,
2024 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002025
2026 // update the outputs if starting an output with a stream that can affect notification
2027 // routing
2028 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002029
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002030 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002031 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002032 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2033 }
Eric Laurentdc462862016-07-19 12:29:53 -07002034
2035 if (waitMs > muteWaitMs) {
2036 *delayMs = waitMs - muteWaitMs;
2037 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002038
2039 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2040 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2041 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2042 // change occurs after the MixerThread starts and causes a stream volume
2043 // glitch.
2044 //
2045 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002046 }
Eric Laurentdc462862016-07-19 12:29:53 -07002047
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002048 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002049 mEngine->getForceUse(
2050 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002051 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002052 }
2053
Eric Laurent97ac8712018-07-27 18:59:02 -07002054 // Automatically enable the remote submix input when output is started on a re routing mix
2055 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002056 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2057 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002058 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2059 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2060 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002061 "remote-submix",
2062 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002063 }
2064
Eric Laurente552edb2014-03-10 17:42:56 -07002065 return NO_ERROR;
2066}
2067
Eric Laurent8fc147b2018-07-22 19:13:55 -07002068status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002069{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002070 ALOGV("%s portId %d", __FUNCTION__, portId);
2071
2072 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2073 if (outputDesc == 0) {
2074 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002075 return BAD_VALUE;
2076 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002077 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002078
Eric Laurent97ac8712018-07-27 18:59:02 -07002079 ALOGV("stopOutput() output %d, stream %d, session %d",
2080 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002081
Eric Laurent97ac8712018-07-27 18:59:02 -07002082 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002083
Eric Laurent733ce942017-12-07 12:18:25 -08002084 if (status == NO_ERROR ) {
2085 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002086 }
2087 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002088}
2089
Eric Laurent97ac8712018-07-27 18:59:02 -07002090status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2091 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002092{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002093 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002094 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002095 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002096
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002097 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2098
François Gaffie1c878552018-11-22 16:53:21 +01002099 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2100 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002101 // Automatically disable the remote submix input when output is stopped on a
2102 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002103 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002104 if (isSingleDeviceType(
2105 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002106 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002107 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002108 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2109 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002110 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002111 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002112 }
2113 }
2114 bool forceDeviceUpdate = false;
2115 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002116 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002117 forceDeviceUpdate = true;
2118 }
2119
Eric Laurente552edb2014-03-10 17:42:56 -07002120 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002121 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002122
Eric Laurente552edb2014-03-10 17:42:56 -07002123 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002124 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002125 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002126 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002127 // delay the device switch by twice the latency because stopOutput() is executed when
2128 // the track stop() command is received and at that time the audio track buffer can
2129 // still contain data that needs to be drained. The latency only covers the audio HAL
2130 // and kernel buffers. Also the latency does not always include additional delay in the
2131 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002132 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002133
2134 // force restoring the device selection on other active outputs if it differs from the
2135 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002136 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002137 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002138 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002139 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002140 desc->isActive() &&
2141 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002142 (newDevices != desc->devices())) {
2143 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2144 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002145
François Gaffie11d30102018-11-02 16:09:09 +01002146 setOutputDevices(desc, newDevices2, force, delayMs);
2147
Eric Laurent57de36c2016-09-28 16:59:11 -07002148 // re-apply device specific volume if not done by setOutputDevice()
2149 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002150 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002151 }
Eric Laurente552edb2014-03-10 17:42:56 -07002152 }
2153 }
2154 // update the outputs if stopping one with a stream that can affect notification routing
2155 handleNotificationRoutingForStream(stream);
2156 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002157
2158 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2159 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002160 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002161 }
2162
François Gaffiec005e562018-11-06 15:04:49 +01002163 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002164 selectOutputForMusicEffects();
2165 }
Eric Laurente552edb2014-03-10 17:42:56 -07002166 return NO_ERROR;
2167 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002168 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002169 return INVALID_OPERATION;
2170 }
2171}
2172
jiabinbce0c1d2020-10-05 11:20:18 -07002173bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002174{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002175 ALOGV("%s portId %d", __FUNCTION__, portId);
2176
2177 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2178 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002179 // If an output descriptor is closed due to a device routing change,
2180 // then there are race conditions with releaseOutput from tracks
2181 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2182 // destroyed shortly thereafter.
2183 //
2184 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002185 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002186 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002187 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002188
2189 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002190
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302191 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2192 if (outputDesc->isClientActive(client)) {
2193 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2194 stopOutput(portId);
2195 }
2196
Eric Laurent8fc147b2018-07-22 19:13:55 -07002197 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2198 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002199 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002201 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002202 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002203 if (--outputDesc->mDirectOpenCount == 0) {
2204 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002205 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002206 }
2207 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302208
Andy Hung39efb7a2018-09-26 15:39:28 -07002209 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002210 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2211 // The output is pending reopened to query dynamic profiles and
2212 // there is no active clients
2213 closeOutput(outputDesc->mIoHandle);
2214 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2215 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2216 if (newOutputDesc == nullptr) {
2217 ALOGE("%s failed to open output", __func__);
2218 }
2219 return true;
2220 }
2221 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002222}
2223
Eric Laurentcaf7f482014-11-25 17:50:47 -08002224status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2225 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002226 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002227 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002228 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002229 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002230 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002231 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002232 input_type_t *inputType,
2233 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002234{
François Gaffiec005e562018-11-06 15:04:49 +01002235 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002236 "flags %#x attributes=%s requested device ID %d",
2237 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2238 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002239
Eric Laurentad2e7b92017-09-14 20:06:42 -07002240 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002241 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002242 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002243 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002244 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002245 sp<AudioInputDescriptor> inputDesc;
2246 sp<RecordClientDescriptor> clientDesc;
2247 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002248 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002249 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002250
2251 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2252 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2253 return INVALID_OPERATION;
2254 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002255
Francois Gaffie716e1432019-01-14 16:58:59 +01002256 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2257 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002258 }
2259
Paul McLean466dc8e2015-04-17 13:15:36 -06002260 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002261 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002262 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002263
Eric Laurentad2e7b92017-09-14 20:06:42 -07002264 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2265 // possible
2266 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2267 *input != AUDIO_IO_HANDLE_NONE) {
2268 ssize_t index = mInputs.indexOfKey(*input);
2269 if (index < 0) {
2270 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2271 status = BAD_VALUE;
2272 goto error;
2273 }
2274 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002275 RecordClientVector clients = inputDesc->getClientsForSession(session);
2276 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002277 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2278 status = BAD_VALUE;
2279 goto error;
2280 }
2281 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2282 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002283 // corresponds to a new client and is only permitted from the same UID.
2284 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002285 if (clients.size() > 1) {
2286 for (const auto& client : clients) {
2287 // The client map is ordered by key values (portId) and portIds are allocated
2288 // incrementaly. So the first client in this list is the one opened by audio flinger
2289 // when the mmap stream is created and should be ignored as it does not correspond
2290 // to an actual client
2291 if (client == *clients.cbegin()) {
2292 continue;
2293 }
2294 if (uid != client->uid() && !client->isSilenced()) {
2295 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2296 uid, client->portId(), client->uid());
2297 status = INVALID_OPERATION;
2298 goto error;
2299 }
Eric Laurent331679c2018-04-16 17:03:16 -07002300 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002301 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002302 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002303 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002304
Eric Laurentfecbceb2021-02-09 14:46:43 +01002305 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002306 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002307 }
2308
2309 *input = AUDIO_IO_HANDLE_NONE;
2310 *inputType = API_INPUT_INVALID;
2311
Francois Gaffie716e1432019-01-14 16:58:59 +01002312 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002313
Francois Gaffie716e1432019-01-14 16:58:59 +01002314 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2315 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2316 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002317 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002318 ALOGW("%s could not find input mix for attr %s",
2319 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002320 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002321 }
jiabinc1de2df2019-05-07 14:26:40 -07002322 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2323 String8(attr->tags + strlen("addr=")),
2324 AUDIO_FORMAT_DEFAULT);
2325 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002326 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002327 __func__, attributes.source, attributes.tags);
2328 status = BAD_VALUE;
2329 goto error;
2330 }
2331
Kevin Rocard25f9b052019-02-27 15:08:54 -08002332 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2333 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2334 } else {
2335 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2336 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002337 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002338 if (explicitRoutingDevice != nullptr) {
2339 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002340 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002341 // Prevent from storing invalid requested device id in clients
2342 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002343 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002344 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2345 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002346 }
François Gaffie11d30102018-11-02 16:09:09 +01002347 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002348 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002349 status = BAD_VALUE;
2350 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002351 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002352 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2353 *inputType = API_INPUT_MIX_CAPTURE;
2354 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002355 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2356 // there is an external policy, but this input is attached to a mix of recorders,
2357 // meaning it receives audio injected into the framework, so the recorder doesn't
2358 // know about it and is therefore considered "legacy"
2359 *inputType = API_INPUT_LEGACY;
2360 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002361 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002362 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002363 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002364 } else {
2365 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002366 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002367
Eric Laurent599c7582015-12-07 18:05:55 -08002368 }
2369
François Gaffiec005e562018-11-06 15:04:49 +01002370 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002371 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002372 status = INVALID_OPERATION;
2373 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002374 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002375
Eric Laurent8f42ea12018-08-08 09:08:25 -07002376exit:
2377
François Gaffiec005e562018-11-06 15:04:49 +01002378 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2379 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002380
Francois Gaffie716e1432019-01-14 16:58:59 +01002381 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002382 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002383 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002384
Mikhail Naganov2996f672019-04-18 12:29:59 -07002385 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002386 requestedDeviceId, attributes.source, flags,
2387 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002388 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002389 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002390
2391 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2392 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002393
Eric Laurent599c7582015-12-07 18:05:55 -08002394 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002395
2396error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002397 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002398}
2399
2400
François Gaffie11d30102018-11-02 16:09:09 +01002401audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002402 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002403 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002404 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002405 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002406 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002407{
2408 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002409 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002410 bool isSoundTrigger = false;
2411
François Gaffiec005e562018-11-06 15:04:49 +01002412 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002413 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2414 if (index >= 0) {
2415 input = mSoundTriggerSessions.valueFor(session);
2416 isSoundTrigger = true;
2417 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2418 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2419 } else {
2420 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002421 }
François Gaffiec005e562018-11-06 15:04:49 +01002422 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002423 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002424 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002425 }
2426
Carter Hsua3abb402021-10-26 11:11:20 +08002427 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2428 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2429 }
2430
Andy Hungf129b032015-04-07 13:45:50 -07002431 // find a compatible input profile (not necessarily identical in parameters)
2432 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002433 // sampling rate and flags may be updated by getInputProfile
2434 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2435 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002436 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002437 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002438 audio_input_flags_t profileFlags = flags;
2439 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002440 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002441 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002442 profileFlags);
2443 if (profile != 0) {
2444 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002445 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2446 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002447 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002448 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2449 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002450 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002451 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002452 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002453 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002454 }
Eric Laurente552edb2014-03-10 17:42:56 -07002455 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002456 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002457 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002458 if (samplingRate == 0) {
2459 samplingRate = profileSamplingRate;
2460 }
Eric Laurente552edb2014-03-10 17:42:56 -07002461
Eric Laurent322b4d22015-04-03 15:57:54 -07002462 if (profile->getModuleHandle() == 0) {
2463 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002464 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002465 }
2466
Eric Laurentec376dc2021-04-08 20:41:22 +02002467 // Reuse an already opened input if a client with the same session ID already exists
2468 // on that input
2469 for (size_t i = 0; i < mInputs.size(); i++) {
2470 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2471 if (desc->mProfile != profile) {
2472 continue;
2473 }
2474 RecordClientVector clients = desc->clientsList();
2475 for (const auto &client : clients) {
2476 if (session == client->session()) {
2477 return desc->mIoHandle;
2478 }
2479 }
2480 }
2481
Eric Laurent3974e3b2017-12-07 17:58:43 -08002482 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002483 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002484 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002485 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002486 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002487 continue;
2488 }
2489 // if sound trigger, reuse input if used by other sound trigger on same session
2490 // else
2491 // reuse input if active client app is not in IDLE state
2492 //
2493 RecordClientVector clients = desc->clientsList();
2494 bool doClose = false;
2495 for (const auto& client : clients) {
2496 if (isSoundTrigger != client->isSoundTrigger()) {
2497 continue;
2498 }
2499 if (client->isSoundTrigger()) {
2500 if (session == client->session()) {
2501 return desc->mIoHandle;
2502 }
2503 continue;
2504 }
2505 if (client->active() && client->appState() != APP_STATE_IDLE) {
2506 return desc->mIoHandle;
2507 }
2508 doClose = true;
2509 }
2510 if (doClose) {
2511 closeInput(desc->mIoHandle);
2512 } else {
2513 i++;
2514 }
2515 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002516 }
2517
Eric Laurentfe231122017-11-17 17:48:06 -08002518 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002519
Eric Laurentfe231122017-11-17 17:48:06 -08002520 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2521 lConfig.sample_rate = profileSamplingRate;
2522 lConfig.channel_mask = profileChannelMask;
2523 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002524
François Gaffie11d30102018-11-02 16:09:09 +01002525 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002526
2527 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002528 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002529 (profileSamplingRate != lConfig.sample_rate) ||
2530 !audio_formats_match(profileFormat, lConfig.format) ||
2531 (profileChannelMask != lConfig.channel_mask)) {
2532 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002533 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002534 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002535 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002536 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002537 }
Eric Laurent599c7582015-12-07 18:05:55 -08002538 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002539 }
2540
Eric Laurentc722f302014-12-10 11:21:49 -08002541 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002542
Eric Laurent599c7582015-12-07 18:05:55 -08002543 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002544 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002545
Eric Laurent599c7582015-12-07 18:05:55 -08002546 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002547}
2548
Eric Laurent4eb58f12018-12-07 16:41:02 -08002549status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002550{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002551 ALOGV("%s portId %d", __FUNCTION__, portId);
2552
2553 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2554 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002555 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002556 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002557 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002558 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002559 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002560 if (client->active()) {
2561 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2562 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002563 }
2564
Eric Laurent8f42ea12018-08-08 09:08:25 -07002565 audio_session_t session = client->session();
2566
Eric Laurent4eb58f12018-12-07 16:41:02 -08002567 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002568
Eric Laurent4eb58f12018-12-07 16:41:02 -08002569 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002570
Eric Laurent4eb58f12018-12-07 16:41:02 -08002571 status_t status = inputDesc->start();
2572 if (status != NO_ERROR) {
2573 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002574 }
Eric Laurente552edb2014-03-10 17:42:56 -07002575
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002576 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002577 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002579
Eric Laurent8f42ea12018-08-08 09:08:25 -07002580 // indicate active capture to sound trigger service if starting capture from a mic on
2581 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002582 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002583 if (device != nullptr) {
2584 status = setInputDevice(input, device, true /* force */);
2585 } else {
2586 ALOGW("%s no new input device can be found for descriptor %d",
2587 __FUNCTION__, inputDesc->getId());
2588 status = BAD_VALUE;
2589 }
Eric Laurente552edb2014-03-10 17:42:56 -07002590
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002591 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002592 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002593 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002594 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002595 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2596 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002597 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002598 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002599
François Gaffie11d30102018-11-02 16:09:09 +01002600 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2601 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002602 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002603 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002604 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002605
Eric Laurent8f42ea12018-08-08 09:08:25 -07002606 // automatically enable the remote submix output when input is started if not
2607 // used by a policy mix of type MIX_TYPE_RECORDERS
2608 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002609 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002610 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002611 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002612 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002613 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2614 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002615 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002616 if (address != "") {
2617 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2618 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002619 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002620 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002621 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002622 } else if (status != NO_ERROR) {
2623 // Restore client activity state.
2624 inputDesc->setClientActive(client, false);
2625 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002626 }
2627
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002628 ALOGV("%s input %d source = %d status = %d exit",
2629 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002630
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002631 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002632}
2633
Eric Laurent8fc147b2018-07-22 19:13:55 -07002634status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002635{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002636 ALOGV("%s portId %d", __FUNCTION__, portId);
2637
2638 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2639 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002640 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002641 return BAD_VALUE;
2642 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002643 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002644 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002645 if (!client->active()) {
2646 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002647 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002648 }
Carter Hsue6139d52021-07-08 10:30:20 +08002649 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002650 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002651
Eric Laurent8f42ea12018-08-08 09:08:25 -07002652 inputDesc->stop();
2653 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002654 auto current_source = inputDesc->source();
2655 setInputDevice(input, getNewInputDevice(inputDesc),
2656 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002657 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002658 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002659 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002660 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002661 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2662 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002663 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002664 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002665
2666 // automatically disable the remote submix output when input is stopped if not
2667 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002668 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002669 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002670 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002671 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002672 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2673 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002674 }
2675 if (address != "") {
2676 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2677 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002678 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002679 }
2680 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002681 resetInputDevice(input);
2682
2683 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2684 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002685 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2686 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002687 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002688 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002689 }
2690 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002691 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002692 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002693}
2694
Eric Laurent8fc147b2018-07-22 19:13:55 -07002695void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002696{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002697 ALOGV("%s portId %d", __FUNCTION__, portId);
2698
2699 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2700 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002701 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002702 return;
2703 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002704 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002705 audio_io_handle_t input = inputDesc->mIoHandle;
2706
Eric Laurent8f42ea12018-08-08 09:08:25 -07002707 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002708
Andy Hung39efb7a2018-09-26 15:39:28 -07002709 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002710
Andy Hung39efb7a2018-09-26 15:39:28 -07002711 if (inputDesc->getClientCount() > 0) {
2712 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002713 return;
2714 }
2715
Eric Laurent05b90f82014-08-27 15:32:29 -07002716 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002717 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002718 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002719}
2720
Eric Laurent8f42ea12018-08-08 09:08:25 -07002721void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002722{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002723 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002724
2725 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002726 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002727 }
2728}
2729
Eric Laurent8f42ea12018-08-08 09:08:25 -07002730void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2731{
2732 stopInput(portId);
2733 releaseInput(portId);
2734}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002735
Eric Laurent0dd51852019-04-19 18:18:58 -07002736void AudioPolicyManager::checkCloseInputs() {
2737 // After connecting or disconnecting an input device, close input if:
2738 // - it has no client (was just opened to check profile) OR
2739 // - none of its supported devices are connected anymore OR
2740 // - one of its clients cannot be routed to one of its supported
2741 // devices anymore. Otherwise update device selection
2742 std::vector<audio_io_handle_t> inputsToClose;
2743 for (size_t i = 0; i < mInputs.size(); i++) {
2744 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2745 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002746 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002747 inputsToClose.push_back(mInputs.keyAt(i));
2748 } else {
2749 bool close = false;
2750 for (const auto& client : input->clientsList()) {
2751 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002752 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002753 if (!input->supportedDevices().contains(device)) {
2754 close = true;
2755 break;
2756 }
2757 }
2758 if (close) {
2759 inputsToClose.push_back(mInputs.keyAt(i));
2760 } else {
2761 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2762 }
2763 }
2764 }
2765
2766 for (const audio_io_handle_t handle : inputsToClose) {
2767 ALOGV("%s closing input %d", __func__, handle);
2768 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002769 }
Eric Laurentd4692962014-05-05 18:13:44 -07002770}
2771
François Gaffie251c7f02018-11-07 10:41:08 +01002772void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002773{
2774 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002775 if (indexMin < 0 || indexMax < 0) {
2776 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2777 return;
2778 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002779 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002780
2781 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002782 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2783 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002784 continue;
2785 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002786 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002787 }
Eric Laurente552edb2014-03-10 17:42:56 -07002788}
2789
Eric Laurente0720872014-03-11 09:30:41 -07002790status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002791 int index,
2792 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002793{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002794 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002795 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2796 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2797 return NO_ERROR;
2798 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002799 ALOGV("%s: stream %s attributes=%s", __func__,
2800 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002801 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002802}
2803
Eric Laurente0720872014-03-11 09:30:41 -07002804status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002805 int *index,
2806 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002807{
François Gaffiec005e562018-11-06 15:04:49 +01002808 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2809 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002810 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002811 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002812 deviceTypes = mEngine->getOutputDevicesForStream(
2813 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002814 }
jiabin9a3361e2019-10-01 09:38:30 -07002815 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002816}
2817
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002818status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002819 int index,
2820 audio_devices_t device)
2821{
2822 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002823 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2824 if (group == VOLUME_GROUP_NONE) {
2825 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002826 return BAD_VALUE;
2827 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002828 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002829 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002830 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002831 VolumeSource vs = toVolumeSource(group);
2832 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2833
2834 status = setVolumeCurveIndex(index, device, curves);
2835 if (status != NO_ERROR) {
2836 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2837 return status;
2838 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002839
jiabin9a3361e2019-10-01 09:38:30 -07002840 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002841 auto curCurvAttrs = curves.getAttributes();
2842 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2843 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002844 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002845 } else if (!curves.getStreamTypes().empty()) {
2846 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002847 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002848 } else {
2849 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2850 return BAD_VALUE;
2851 }
jiabin9a3361e2019-10-01 09:38:30 -07002852 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2853 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002854
François Gaffiecfe17322018-11-07 13:41:29 +01002855 // update volume on all outputs and streams matching the following:
2856 // - The requested stream (or a stream matching for volume control) is active on the output
2857 // - The device (or devices) selected by the engine for this stream includes
2858 // the requested device
2859 // - For non default requested device, currently selected device on the output is either the
2860 // requested device or one of the devices selected by the engine for this stream
2861 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2862 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002863 for (size_t i = 0; i < mOutputs.size(); i++) {
2864 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002865 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002866
jiabin9a3361e2019-10-01 09:38:30 -07002867 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2868 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002869 }
François Gaffieed91f582020-01-31 10:35:37 +01002870 if (!(desc->isActive(vs) || isInCall())) {
2871 continue;
2872 }
2873 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2874 curDevices.find(device) == curDevices.end()) {
2875 continue;
2876 }
2877 bool applyVolume = false;
2878 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2879 curSrcDevices.insert(device);
2880 applyVolume = (curSrcDevices.find(
2881 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2882 } else {
2883 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2884 }
2885 if (!applyVolume) {
2886 continue; // next output
2887 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002888 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2889 // If a higher priority strategy is active, and the output is routed to a device with a
2890 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002891 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002892 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002893 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2894 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2895 false /*preferredDevice*/);
2896 if (activeClients.empty()) {
2897 continue;
2898 }
2899 bool isPreempted = false;
2900 bool isHigherPriority = productStrategy < strategy;
2901 for (const auto &client : activeClients) {
2902 if (isHigherPriority && (client->volumeSource() != vs)) {
2903 ALOGV("%s: Strategy=%d (\nrequester:\n"
2904 " group %d, volumeGroup=%d attributes=%s)\n"
2905 " higher priority source active:\n"
2906 " volumeGroup=%d attributes=%s) \n"
2907 " on output %zu, bailing out", __func__, productStrategy,
2908 group, group, toString(attributes).c_str(),
2909 client->volumeSource(), toString(client->attributes()).c_str(), i);
2910 applyVolume = false;
2911 isPreempted = true;
2912 break;
2913 }
2914 // However, continue for loop to ensure no higher prio clients running on output
2915 if (client->volumeSource() == vs) {
2916 applyVolume = true;
2917 }
2918 }
2919 if (isPreempted || applyVolume) {
2920 break;
2921 }
2922 }
2923 if (!applyVolume) {
2924 continue; // next output
2925 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002926 }
François Gaffieed91f582020-01-31 10:35:37 +01002927 //FIXME: workaround for truncated touch sounds
2928 // delayed volume change for system stream to be removed when the problem is
2929 // handled by system UI
2930 status_t volStatus = checkAndSetVolume(
2931 curves, vs, index, desc, curDevices,
2932 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2933 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2934 if (volStatus != NO_ERROR) {
2935 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002936 }
2937 }
François Gaffiecfe17322018-11-07 13:41:29 +01002938 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2939 return status;
2940}
2941
François Gaffieaaac0fd2018-11-22 17:56:39 +01002942status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002943 audio_devices_t device,
2944 IVolumeCurves &volumeCurves)
2945{
2946 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2947 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002948 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2949 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002950 (index > volumeCurves.getVolumeIndexMax())) {
2951 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2952 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2953 return BAD_VALUE;
2954 }
2955 if (!audio_is_output_device(device)) {
2956 return BAD_VALUE;
2957 }
2958
2959 // Force max volume if stream cannot be muted
2960 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2961
François Gaffieaaac0fd2018-11-22 17:56:39 +01002962 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002963 volumeCurves.addCurrentVolumeIndex(device, index);
2964 return NO_ERROR;
2965}
2966
2967status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2968 int &index,
2969 audio_devices_t device)
2970{
2971 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2972 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002973 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002974 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002975 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2976 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002977 }
jiabin9a3361e2019-10-01 09:38:30 -07002978 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002979}
2980
2981status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2982 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002983 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002984{
jiabin9a3361e2019-10-01 09:38:30 -07002985 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002986 return BAD_VALUE;
2987 }
jiabin9a3361e2019-10-01 09:38:30 -07002988 index = curves.getVolumeIndex(deviceTypes);
2989 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002990 return NO_ERROR;
2991}
2992
2993status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2994 int &index)
2995{
2996 index = getVolumeCurves(attr).getVolumeIndexMin();
2997 return NO_ERROR;
2998}
2999
3000status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3001 int &index)
3002{
3003 index = getVolumeCurves(attr).getVolumeIndexMax();
3004 return NO_ERROR;
3005}
3006
Eric Laurent36829f92017-04-07 19:04:42 -07003007audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003008{
3009 // select one output among several suitable for global effects.
3010 // The priority is as follows:
3011 // 1: An offloaded output. If the effect ends up not being offloadable,
3012 // AudioFlinger will invalidate the track and the offloaded output
3013 // will be closed causing the effect to be moved to a PCM output.
3014 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003015 // 3: The primary output
3016 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003017
François Gaffiec005e562018-11-06 15:04:49 +01003018 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3019 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003020 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003021
Eric Laurent36829f92017-04-07 19:04:42 -07003022 if (outputs.size() == 0) {
3023 return AUDIO_IO_HANDLE_NONE;
3024 }
Eric Laurente552edb2014-03-10 17:42:56 -07003025
Eric Laurent36829f92017-04-07 19:04:42 -07003026 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3027 bool activeOnly = true;
3028
3029 while (output == AUDIO_IO_HANDLE_NONE) {
3030 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3031 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3032 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3033
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003034 for (audio_io_handle_t output : outputs) {
3035 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003036 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003037 continue;
3038 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003039 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3040 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003041 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003042 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003043 }
3044 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003045 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003046 }
3047 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003048 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003049 }
3050 }
3051 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3052 output = outputOffloaded;
3053 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3054 output = outputDeepBuffer;
3055 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3056 output = outputPrimary;
3057 } else {
3058 output = outputs[0];
3059 }
3060 activeOnly = false;
3061 }
3062
3063 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003064 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003065 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3066 mMusicEffectOutput = output;
3067 }
3068
3069 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003070 return output;
3071}
3072
Eric Laurent36829f92017-04-07 19:04:42 -07003073audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3074{
3075 return selectOutputForMusicEffects();
3076}
3077
Eric Laurente0720872014-03-11 09:30:41 -07003078status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003079 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003080 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003081 int session,
3082 int id)
3083{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003084 if (session != AUDIO_SESSION_DEVICE) {
3085 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003086 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003087 index = mInputs.indexOfKey(io);
3088 if (index < 0) {
3089 ALOGW("registerEffect() unknown io %d", io);
3090 return INVALID_OPERATION;
3091 }
Eric Laurente552edb2014-03-10 17:42:56 -07003092 }
3093 }
François Gaffiec005e562018-11-06 15:04:49 +01003094 return mEffects.registerEffect(desc, io, session, id,
3095 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3096 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003097}
3098
Eric Laurentc241b0d2018-11-28 09:08:49 -08003099status_t AudioPolicyManager::unregisterEffect(int id)
3100{
3101 if (mEffects.getEffect(id) == nullptr) {
3102 return INVALID_OPERATION;
3103 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003104 if (mEffects.isEffectEnabled(id)) {
3105 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3106 setEffectEnabled(id, false);
3107 }
3108 return mEffects.unregisterEffect(id);
3109}
3110
3111status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3112{
3113 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3114 if (effect == nullptr) {
3115 return INVALID_OPERATION;
3116 }
3117
3118 status_t status = mEffects.setEffectEnabled(id, enabled);
3119 if (status == NO_ERROR) {
3120 mInputs.trackEffectEnabled(effect, enabled);
3121 }
3122 return status;
3123}
3124
Eric Laurent6c796322019-04-09 14:13:17 -07003125
3126status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3127{
3128 mEffects.moveEffects(ids, io);
3129 return NO_ERROR;
3130}
3131
Eric Laurentc75307b2015-03-17 15:29:32 -07003132bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3133{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003134 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003135}
3136
3137bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3138{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003139 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003140}
3141
Eric Laurente0720872014-03-11 09:30:41 -07003142bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003143{
3144 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003145 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003146 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003147 return true;
3148 }
3149 }
3150 return false;
3151}
3152
Eric Laurent275e8e92014-11-30 15:14:47 -08003153// Register a list of custom mixes with their attributes and format.
3154// When a mix is registered, corresponding input and output profiles are
3155// added to the remote submix hw module. The profile contains only the
3156// parameters (sampling rate, format...) specified by the mix.
3157// The corresponding input remote submix device is also connected.
3158//
3159// When a remote submix device is connected, the address is checked to select the
3160// appropriate profile and the corresponding input or output stream is opened.
3161//
3162// When capture starts, getInputForAttr() will:
3163// - 1 look for a mix matching the address passed in attribtutes tags if any
3164// - 2 if none found, getDeviceForInputSource() will:
3165// - 2.1 look for a mix matching the attributes source
3166// - 2.2 if none found, default to device selection by policy rules
3167// At this time, the corresponding output remote submix device is also connected
3168// and active playback use cases can be transferred to this mix if needed when reconnecting
3169// after AudioTracks are invalidated
3170//
3171// When playback starts, getOutputForAttr() will:
3172// - 1 look for a mix matching the address passed in attribtutes tags if any
3173// - 2 if none found, look for a mix matching the attributes usage
3174// - 3 if none found, default to device and output selection by policy rules.
3175
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003176status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003177{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003178 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3179 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003180 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003181 sp<HwModule> rSubmixModule;
3182 // examine each mix's route type
3183 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003184 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003185 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3186 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3187 ALOGE("Unsupported Policy Mix %zu of %zu: "
3188 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3189 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003190 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003191 break;
3192 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003193 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3194 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003195 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003196 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3197 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003198 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003199 rSubmixModule = mHwModules.getModuleFromName(
3200 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3201 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003202 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003203 i);
3204 res = INVALID_OPERATION;
3205 break;
3206 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003207 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003208
Eric Laurent97ac8712018-07-27 18:59:02 -07003209 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003210 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003211 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003212 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003213 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3214 } else {
3215 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3216 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003217 }
François Gaffie036e1e92015-03-19 10:16:24 +01003218
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003219 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003220 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003221 res = INVALID_OPERATION;
3222 break;
3223 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003224 audio_config_t outputConfig = mix.mFormat;
3225 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003226 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3227 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003228 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3229 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003230 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003231 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003232 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003233 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003234
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003235 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003236 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3237 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3238 ALOGE("Failed to set remote submix device available, type %u, address %s",
3239 mix.mDeviceType, address.string());
3240 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003241 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003242 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3243 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003244 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003245 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003246 i, mixes.size(), type, address.string());
3247
3248 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3249 mix.mDeviceType, mix.mDeviceAddress,
3250 String8(), AUDIO_FORMAT_DEFAULT);
3251 if (device == nullptr) {
3252 res = INVALID_OPERATION;
3253 break;
3254 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003255
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003256 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003257 // First try to find an already opened output supporting the device
3258 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003259 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003260
Eric Laurentc529cf62020-04-17 18:19:10 -07003261 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003262 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003263 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3264 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003265 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003266 } else {
3267 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003268 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003269 }
3270 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003271 // If no output found, try to find a direct output profile supporting the device
3272 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3273 sp<HwModule> module = mHwModules[i];
3274 for (size_t j = 0;
3275 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3276 j++) {
3277 sp<IOProfile> profile = module->getOutputProfiles()[j];
3278 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3279 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3280 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3281 address.string());
3282 res = INVALID_OPERATION;
3283 } else {
3284 foundOutput = true;
3285 }
3286 }
3287 }
3288 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003289 if (res != NO_ERROR) {
3290 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003291 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003292 res = INVALID_OPERATION;
3293 break;
3294 } else if (!foundOutput) {
3295 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003296 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003297 res = INVALID_OPERATION;
3298 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003299 } else {
3300 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003301 }
Eric Laurentc722f302014-12-10 11:21:49 -08003302 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003303 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003304 if (res != NO_ERROR) {
3305 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003306 } else if (checkOutputs) {
3307 checkForDeviceAndOutputChanges();
3308 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003309 }
3310 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003311}
3312
3313status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3314{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003315 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003316 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003317 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003318 sp<HwModule> rSubmixModule;
3319 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003320 for (const auto& mix : mixes) {
3321 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003322
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003323 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003324 rSubmixModule = mHwModules.getModuleFromName(
3325 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3326 if (rSubmixModule == 0) {
3327 res = INVALID_OPERATION;
3328 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003329 }
3330 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003331
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003332 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003333
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003334 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003335 res = INVALID_OPERATION;
3336 continue;
3337 }
3338
Kevin Rocard04ed0462019-05-02 17:53:24 -07003339 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3340 if (getDeviceConnectionState(device, address.string()) ==
3341 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3342 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3343 address.string(), "remote-submix",
3344 AUDIO_FORMAT_DEFAULT);
3345 if (res != OK) {
3346 ALOGE("Error making RemoteSubmix device unavailable for mix "
3347 "with type %d, address %s", device, address.string());
3348 }
3349 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003350 }
jiabin5740f082019-08-19 15:08:30 -07003351 rSubmixModule->removeOutputProfile(address.c_str());
3352 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003353
Kevin Rocard153f92d2018-12-18 18:33:28 -08003354 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003355 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003356 res = INVALID_OPERATION;
3357 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003358 } else {
3359 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003360 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003361 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003362 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003363 if (res == NO_ERROR && checkOutputs) {
3364 checkForDeviceAndOutputChanges();
3365 updateCallAndOutputRouting();
3366 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003367 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003368}
3369
Mikhail Naganov100f0122018-11-29 11:22:16 -08003370void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3371{
3372 size_t i = 0;
3373 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3374 for (const auto& fmt : mManualSurroundFormats) {
3375 if (i++ != 0) dst->append(", ");
3376 std::string sfmt;
3377 FormatConverter::toString(fmt, sfmt);
3378 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3379 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3380 }
3381}
3382
Eric Laurentc529cf62020-04-17 18:19:10 -07003383// Returns true if all devices types match the predicate and are supported by one HW module
3384bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003385 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003386 std::function<bool(audio_devices_t)> predicate,
3387 const char *context) {
3388 for (size_t i = 0; i < devices.size(); i++) {
3389 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003390 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003391 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003392 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003393 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003394 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003395 return false;
3396 }
3397 }
3398 return true;
3399}
3400
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003401status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003402 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003403 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003404 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3405 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003406 }
3407 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003408 if (res != NO_ERROR) {
3409 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3410 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003411 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003412
3413 checkForDeviceAndOutputChanges();
3414 updateCallAndOutputRouting();
3415
3416 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003417}
3418
3419status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3420 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003421 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3422 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003423 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003424 __FUNCTION__, uid);
3425 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003426 }
3427
Eric Laurentc529cf62020-04-17 18:19:10 -07003428 checkForDeviceAndOutputChanges();
3429 updateCallAndOutputRouting();
3430
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003431 return res;
3432}
3433
Eric Laurent2517af32020-11-25 15:31:27 +01003434
jiabin0a488932020-08-07 17:32:40 -07003435status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3436 device_role_t role,
3437 const AudioDeviceTypeAddrVector &devices) {
3438 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3439 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003440
Eric Laurentc529cf62020-04-17 18:19:10 -07003441 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003442 return BAD_VALUE;
3443 }
jiabin0a488932020-08-07 17:32:40 -07003444 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003445 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003446 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3447 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003448 return status;
3449 }
3450
3451 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003452
3453 bool forceVolumeReeval = false;
3454 // FIXME: workaround for truncated touch sounds
3455 // to be removed when the problem is handled by system UI
3456 uint32_t delayMs = 0;
3457 if (strategy == mCommunnicationStrategy) {
3458 forceVolumeReeval = true;
3459 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3460 updateInputRouting();
3461 }
3462 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003463
3464 return NO_ERROR;
3465}
3466
3467void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3468{
3469 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003470 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003471 // Only apply special touch sound delay once
3472 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003473 }
3474 for (size_t i = 0; i < mOutputs.size(); i++) {
3475 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3476 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3477 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3478 // As done in setDeviceConnectionState, we could also fix default device issue by
3479 // preventing the force re-routing in case of default dev that distinguishes on address.
3480 // Let's give back to engine full device choice decision however.
3481 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003482 // Only apply special touch sound delay once
3483 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003484 }
3485 if (forceVolumeReeval && !newDevices.isEmpty()) {
3486 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3487 }
3488 }
3489}
3490
Eric Laurent2517af32020-11-25 15:31:27 +01003491void AudioPolicyManager::updateInputRouting() {
3492 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303493 // Skip for hotword recording as the input device switch
3494 // is handled within sound trigger HAL
3495 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3496 continue;
3497 }
Eric Laurent2517af32020-11-25 15:31:27 +01003498 auto newDevice = getNewInputDevice(activeDesc);
3499 // Force new input selection if the new device can not be reached via current input
3500 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3501 setInputDevice(activeDesc->mIoHandle, newDevice);
3502 } else {
3503 closeInput(activeDesc->mIoHandle);
3504 }
3505 }
3506}
3507
jiabin0a488932020-08-07 17:32:40 -07003508status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3509 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003510{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003511 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003512
jiabin0a488932020-08-07 17:32:40 -07003513 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003514 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003515 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3516 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003517 return status;
3518 }
3519
3520 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003521
3522 bool forceVolumeReeval = false;
3523 // FIXME: workaround for truncated touch sounds
3524 // to be removed when the problem is handled by system UI
3525 uint32_t delayMs = 0;
3526 if (strategy == mCommunnicationStrategy) {
3527 forceVolumeReeval = true;
3528 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3529 updateInputRouting();
3530 }
3531 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003532
3533 return NO_ERROR;
3534}
3535
jiabin0a488932020-08-07 17:32:40 -07003536status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3537 device_role_t role,
3538 AudioDeviceTypeAddrVector &devices) {
3539 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003540}
3541
Jiabin Huang3b98d322020-09-03 17:54:16 +00003542status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3543 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3544 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3545 dumpAudioDeviceTypeAddrVector(devices).c_str());
3546
Mikhail Naganov55773032020-10-01 15:08:13 -07003547 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003548 return BAD_VALUE;
3549 }
3550 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3551 ALOGW_IF(status != NO_ERROR,
3552 "Engine could not set preferred devices %s for audio source %d role %d",
3553 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3554
3555 return status;
3556}
3557
3558status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3559 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3560 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3561 dumpAudioDeviceTypeAddrVector(devices).c_str());
3562
Mikhail Naganov55773032020-10-01 15:08:13 -07003563 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003564 return BAD_VALUE;
3565 }
3566 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3567 ALOGW_IF(status != NO_ERROR,
3568 "Engine could not add preferred devices %s for audio source %d role %d",
3569 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3570
Eric Laurent2517af32020-11-25 15:31:27 +01003571 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003572 return status;
3573}
3574
3575status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3576 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3577{
3578 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3579 dumpAudioDeviceTypeAddrVector(devices).c_str());
3580
Mikhail Naganov55773032020-10-01 15:08:13 -07003581 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003582 return BAD_VALUE;
3583 }
3584
3585 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3586 audioSource, role, devices);
3587 ALOGW_IF(status != NO_ERROR,
3588 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3589
Eric Laurent2517af32020-11-25 15:31:27 +01003590 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003591 return status;
3592}
3593
3594status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3595 device_role_t role) {
3596 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3597
3598 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3599 ALOGW_IF(status != NO_ERROR,
3600 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3601
Eric Laurent2517af32020-11-25 15:31:27 +01003602 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003603 return status;
3604}
3605
3606status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3607 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3608 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3609}
3610
Oscar Azucena90e77632019-11-27 17:12:28 -08003611status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003612 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003613 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003614 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3615 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003616 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003617 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3618 if (status != NO_ERROR) {
3619 ALOGE("%s() could not set device affinity for userId %d",
3620 __FUNCTION__, userId);
3621 return status;
3622 }
3623
3624 // reevaluate outputs for all devices
3625 checkForDeviceAndOutputChanges();
3626 updateCallAndOutputRouting();
3627
3628 return NO_ERROR;
3629}
3630
3631status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003632 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003633 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3634 if (status != NO_ERROR) {
3635 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3636 __FUNCTION__, userId);
3637 return status;
3638 }
3639
3640 // reevaluate outputs for all devices
3641 checkForDeviceAndOutputChanges();
3642 updateCallAndOutputRouting();
3643
3644 return NO_ERROR;
3645}
3646
Andy Hungc29d82b2018-10-05 12:23:17 -07003647void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003648{
Andy Hungc29d82b2018-10-05 12:23:17 -07003649 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003650 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003651 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003652 std::string stateLiteral;
3653 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003654 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003655 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3656 "communications", "media", "record", "dock", "system",
3657 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3658 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3659 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003660 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3661 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3662 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3663 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3664 dst->append(" (MANUAL: ");
3665 dumpManualSurroundFormats(dst);
3666 dst->append(")");
3667 }
3668 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003669 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003670 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3671 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003672 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003673 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003674
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003675 dst->append("\n");
3676 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3677 dst->append("\n");
3678 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003679 mHwModulesAll.dump(dst);
3680 mOutputs.dump(dst);
3681 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003682 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003683 mAudioPatches.dump(dst);
3684 mPolicyMixes.dump(dst);
3685 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003686
Kevin Rocardb99cc752019-03-21 20:52:24 -07003687 dst->appendFormat(" AllowedCapturePolicies:\n");
3688 for (auto& policy : mAllowedCapturePolicies) {
3689 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3690 }
3691
François Gaffiec005e562018-11-06 15:04:49 +01003692 dst->appendFormat("\nPolicy Engine dump:\n");
3693 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003694}
3695
3696status_t AudioPolicyManager::dump(int fd)
3697{
3698 String8 result;
3699 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003700 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003701 return NO_ERROR;
3702}
3703
Kevin Rocardb99cc752019-03-21 20:52:24 -07003704status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3705{
3706 mAllowedCapturePolicies[uid] = capturePolicy;
3707 return NO_ERROR;
3708}
3709
Eric Laurente552edb2014-03-10 17:42:56 -07003710// This function checks for the parameters which can be offloaded.
3711// This can be enhanced depending on the capability of the DSP and policy
3712// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003713audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003714{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003715 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003716 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003717 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003718 offloadInfo.format,
3719 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3720 offloadInfo.has_video);
3721
jiabin2b9d5a12021-12-10 01:06:29 +00003722 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003723 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003724 }
3725
3726 // See if there is a profile to support this.
3727 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003728 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003729 offloadInfo.sample_rate,
3730 offloadInfo.format,
3731 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003732 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3733 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003734 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3735 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3736 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003737 if (profile == nullptr) {
3738 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3739 }
3740 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3741 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3742 }
3743 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003744}
3745
Michael Chana94fbb22018-04-24 14:31:19 +10003746bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3747 const audio_attributes_t& attributes) {
3748 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003749 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003750 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3751 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003752 config.sample_rate,
3753 config.format,
3754 config.channel_mask,
3755 output_flags,
3756 true /* directOnly */);
3757 ALOGV("%s() profile %sfound with name: %s, "
3758 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3759 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003760 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003761 config.sample_rate, config.format, config.channel_mask, output_flags);
3762 return (profile != 0);
3763}
3764
jiabin2b9d5a12021-12-10 01:06:29 +00003765bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3766 bool durationIgnored) {
3767 if (mMasterMono) {
3768 return false; // no offloading if mono is set.
3769 }
3770
3771 // Check if offload has been disabled
3772 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3773 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3774 return false;
3775 }
3776
3777 // Check if stream type is music, then only allow offload as of now.
3778 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3779 {
3780 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3781 return false;
3782 }
3783
3784 //TODO: enable audio offloading with video when ready
3785 const bool allowOffloadWithVideo =
3786 property_get_bool("audio.offload.video", false /* default_value */);
3787 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3788 ALOGV("%s: has_video == true, returning false", __func__);
3789 return false;
3790 }
3791
3792 //If duration is less than minimum value defined in property, return false
3793 const int min_duration_secs = property_get_int32(
3794 "audio.offload.min.duration.secs", -1 /* default_value */);
3795 if (!durationIgnored) {
3796 if (min_duration_secs >= 0) {
3797 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3798 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3799 __func__, min_duration_secs);
3800 return false;
3801 }
3802 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3803 ALOGV("%s: Offload denied by duration < default min(=%u)",
3804 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3805 return false;
3806 }
3807 }
3808
3809 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3810 // creating an offloaded track and tearing it down immediately after start when audioflinger
3811 // detects there is an active non offloadable effect.
3812 // FIXME: We should check the audio session here but we do not have it in this context.
3813 // This may prevent offloading in rare situations where effects are left active by apps
3814 // in the background.
3815 if (mEffects.isNonOffloadableEffectEnabled()) {
3816 return false;
3817 }
3818
3819 return true;
3820}
3821
3822audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3823 const audio_config_t *config) {
3824 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3825 offloadInfo.format = config->format;
3826 offloadInfo.sample_rate = config->sample_rate;
3827 offloadInfo.channel_mask = config->channel_mask;
3828 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3829 offloadInfo.has_video = false;
3830 offloadInfo.is_streaming = false;
3831 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3832
3833 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3834 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3835 audio_flags_to_audio_output_flags(attr->flags, &flags);
3836 // only retain flags that will drive compressed offload or passthrough
3837 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3838 if (offloadPossible) {
3839 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3840 }
3841 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3842
jiabinc8f7dfc2022-01-06 18:42:08 +00003843 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003844 for (const auto& hwModule : mHwModules) {
3845 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003846 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003847 config->sample_rate, nullptr /*updatedSamplingRate*/,
3848 config->format, nullptr /*updatedFormat*/,
3849 config->channel_mask, nullptr /*updatedChannelMask*/,
3850 flags)) {
3851 continue;
3852 }
3853 // reject profiles not corresponding to a device currently available
3854 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3855 continue;
3856 }
3857 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3858 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003859 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003860 != AUDIO_DIRECT_NOT_SUPPORTED) {
3861 // Already reports offload gapless supported. No need to report offload support.
3862 continue;
3863 }
3864 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3865 != AUDIO_OUTPUT_FLAG_NONE) {
3866 // If offload gapless is reported, no need to report offload support.
3867 directMode = (audio_direct_mode_t) ((directMode &
3868 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
3869 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
3870 } else {
3871 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
3872 }
3873 } else {
3874 directMode = (audio_direct_mode_t) (directMode |
3875 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
3876 }
3877 }
3878 }
3879 return directMode;
3880}
3881
Dorin Drimusf2196d82022-01-03 12:11:18 +01003882status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
3883 AudioProfileVector& audioProfilesVector) {
3884 AudioDeviceTypeAddrVector devices;
3885 status_t status = getDevicesForAttributes(*attr, &devices);
3886 if (status != OK) {
3887 return status;
3888 }
3889 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
3890 if (devices.empty()) {
3891 return OK; // no output devices for the attributes
3892 }
3893
3894 for (const auto& hwModule : mHwModules) {
3895 for (const auto& curProfile : hwModule->getOutputProfiles()) {
3896 if (!curProfile->asAudioPort()->isDirectOutput()) {
3897 continue;
3898 }
3899 // Allow only profiles that support all the available and routed devices
3900 DeviceVector supportedDevices = curProfile->getSupportedDevices();
3901 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
3902 != devices.size()) {
3903 continue;
3904 }
3905
3906 const auto audioProfiles = curProfile->asAudioPort()->getAudioProfiles();
3907 ALOGV("%s: found direct profile (%s) with %zu audio profiles.",
3908 __func__, curProfile->getTagName().c_str(), audioProfiles.size());
3909 for (const auto& audioProfile : audioProfiles) {
3910 if (audioProfile->isValid() && !audioProfilesVector.contains(audioProfile)
3911 // TODO - why do we have same PCM format with both dynamic and non dynamic format
3912 && audioProfile->isDynamicFormat()) {
3913 ALOGV("%s: adding audio profile with encoding (%d).",
3914 __func__, audioProfile->getFormat());
3915 audioProfilesVector.add(audioProfile);
3916 }
3917 }
3918 }
3919 }
3920 return NO_ERROR;
3921}
3922
Eric Laurent6a94d692014-05-20 11:18:06 -07003923status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3924 audio_port_type_t type,
3925 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003926 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003927 unsigned int *generation)
3928{
jiabin19cdba52020-11-24 11:28:58 -08003929 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3930 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003931 return BAD_VALUE;
3932 }
3933 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003934 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003935 *num_ports = 0;
3936 }
3937
3938 size_t portsWritten = 0;
3939 size_t portsMax = *num_ports;
3940 *num_ports = 0;
3941 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003942 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3943 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003944 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003945 for (const auto& dev : mAvailableOutputDevices) {
3946 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003947 continue;
3948 }
3949 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003950 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003951 }
3952 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003954 }
3955 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003956 for (const auto& dev : mAvailableInputDevices) {
3957 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003958 continue;
3959 }
3960 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003961 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003962 }
3963 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003964 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003965 }
3966 }
3967 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3968 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3969 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3970 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3971 }
3972 *num_ports += mInputs.size();
3973 }
3974 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003975 size_t numOutputs = 0;
3976 for (size_t i = 0; i < mOutputs.size(); i++) {
3977 if (!mOutputs[i]->isDuplicated()) {
3978 numOutputs++;
3979 if (portsWritten < portsMax) {
3980 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3981 }
3982 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003983 }
Eric Laurent84c70242014-06-23 08:46:27 -07003984 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 }
3986 }
3987 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003988 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 return NO_ERROR;
3990}
3991
jiabin19cdba52020-11-24 11:28:58 -08003992status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003993{
Eric Laurent99fcae42018-05-17 16:59:18 -07003994 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3995 return BAD_VALUE;
3996 }
3997 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3998 if (dev != 0) {
3999 dev->toAudioPort(port);
4000 return NO_ERROR;
4001 }
4002 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4003 if (dev != 0) {
4004 dev->toAudioPort(port);
4005 return NO_ERROR;
4006 }
4007 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4008 if (out != 0) {
4009 out->toAudioPort(port);
4010 return NO_ERROR;
4011 }
4012 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4013 if (in != 0) {
4014 in->toAudioPort(port);
4015 return NO_ERROR;
4016 }
4017 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004018}
4019
François Gaffieafd4cea2019-11-18 15:50:22 +01004020status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4021 audio_patch_handle_t *handle,
4022 uid_t uid, uint32_t delayMs,
4023 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07004024{
François Gaffieafd4cea2019-11-18 15:50:22 +01004025 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004026 if (handle == NULL || patch == NULL) {
4027 return BAD_VALUE;
4028 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004029 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004030
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004031 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004032 return BAD_VALUE;
4033 }
4034 // only one source per audio patch supported for now
4035 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 return INVALID_OPERATION;
4037 }
Eric Laurent874c42872014-08-08 15:13:39 -07004038
4039 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 return INVALID_OPERATION;
4041 }
Eric Laurent874c42872014-08-08 15:13:39 -07004042 for (size_t i = 0; i < patch->num_sinks; i++) {
4043 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4044 return INVALID_OPERATION;
4045 }
4046 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004047
4048 sp<AudioPatch> patchDesc;
4049 ssize_t index = mAudioPatches.indexOfKey(*handle);
4050
François Gaffieafd4cea2019-11-18 15:50:22 +01004051 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4052 patch->sources[0].role,
4053 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004054#if LOG_NDEBUG == 0
4055 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004056 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4057 patch->sinks[i].role,
4058 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004059 }
4060#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004061
4062 if (index >= 0) {
4063 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004064 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4065 __func__, mUidCached, patchDesc->getUid(), uid);
4066 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004067 return INVALID_OPERATION;
4068 }
4069 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004070 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004071 }
4072
4073 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004074 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004075 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004076 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004077 return BAD_VALUE;
4078 }
Eric Laurent84c70242014-06-23 08:46:27 -07004079 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4080 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004081 if (patchDesc != 0) {
4082 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004083 ALOGV("%s source id differs for patch current id %d new id %d",
4084 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004085 return BAD_VALUE;
4086 }
4087 }
Eric Laurent874c42872014-08-08 15:13:39 -07004088 DeviceVector devices;
4089 for (size_t i = 0; i < patch->num_sinks; i++) {
4090 // Only support mix to devices connection
4091 // TODO add support for mix to mix connection
4092 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004093 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004094 return INVALID_OPERATION;
4095 }
4096 sp<DeviceDescriptor> devDesc =
4097 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4098 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004099 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004100 return BAD_VALUE;
4101 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004102
François Gaffie11d30102018-11-02 16:09:09 +01004103 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004104 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004105 NULL, // updatedSamplingRate
4106 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004107 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004108 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004109 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004110 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004111 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004112 return INVALID_OPERATION;
4113 }
4114 devices.add(devDesc);
4115 }
4116 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004117 return INVALID_OPERATION;
4118 }
Eric Laurent874c42872014-08-08 15:13:39 -07004119
Eric Laurent6a94d692014-05-20 11:18:06 -07004120 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004121 ALOGV("%s setting device %s on output %d",
4122 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004123 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004124 index = mAudioPatches.indexOfKey(*handle);
4125 if (index >= 0) {
4126 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004127 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004128 }
4129 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004130 patchDesc->setUid(uid);
4131 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004132 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004133 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004134 return INVALID_OPERATION;
4135 }
4136 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4137 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4138 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004139 // only one sink supported when connecting an input device to a mix
4140 if (patch->num_sinks > 1) {
4141 return INVALID_OPERATION;
4142 }
François Gaffie53615e22015-03-19 09:24:12 +01004143 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004144 if (inputDesc == NULL) {
4145 return BAD_VALUE;
4146 }
4147 if (patchDesc != 0) {
4148 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4149 return BAD_VALUE;
4150 }
4151 }
François Gaffie11d30102018-11-02 16:09:09 +01004152 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004153 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004154 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 return BAD_VALUE;
4156 }
4157
François Gaffie11d30102018-11-02 16:09:09 +01004158 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004159 patch->sinks[0].sample_rate,
4160 NULL, /*updatedSampleRate*/
4161 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004162 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004163 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004164 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004165 // FIXME for the parameter type,
4166 // and the NONE
4167 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004168 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004169 return INVALID_OPERATION;
4170 }
4171 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004172 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004173 device->toString().c_str(), inputDesc->mIoHandle);
4174 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 index = mAudioPatches.indexOfKey(*handle);
4176 if (index >= 0) {
4177 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004178 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 }
4180 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004181 patchDesc->setUid(uid);
4182 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004183 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004184 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004185 return INVALID_OPERATION;
4186 }
4187 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4188 // device to device connection
4189 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004190 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004191 return BAD_VALUE;
4192 }
4193 }
François Gaffie11d30102018-11-02 16:09:09 +01004194 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004195 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004196 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004197 return BAD_VALUE;
4198 }
Eric Laurent874c42872014-08-08 15:13:39 -07004199
Eric Laurent6a94d692014-05-20 11:18:06 -07004200 //update source and sink with our own data as the data passed in the patch may
4201 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004202 PatchBuilder patchBuilder;
4203 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004204
4205 // if first sink is to MSD, establish single MSD patch
4206 if (getMsdAudioOutDevices().contains(
4207 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4208 ALOGV("%s patching to MSD", __FUNCTION__);
4209 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4210 goto installPatch;
4211 }
4212
François Gaffieafd4cea2019-11-18 15:50:22 +01004213 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4214 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004215
Eric Laurent874c42872014-08-08 15:13:39 -07004216 for (size_t i = 0; i < patch->num_sinks; i++) {
4217 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004218 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004219 return INVALID_OPERATION;
4220 }
François Gaffie11d30102018-11-02 16:09:09 +01004221 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004222 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004223 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004224 return BAD_VALUE;
4225 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004226 audio_port_config sinkPortConfig = {};
4227 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4228 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004229
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004230 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4231 // volume management purpose (tracking activity)
4232 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4233 // in config XML to reach the sink so that is can be declared as available.
4234 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4235 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4236 if (sourceDesc != nullptr) {
4237 // take care of dynamic routing for SwOutput selection,
4238 audio_attributes_t attributes = sourceDesc->attributes();
4239 audio_stream_type_t stream = sourceDesc->stream();
4240 audio_attributes_t resultAttr;
4241 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4242 config.sample_rate = sourceDesc->config().sample_rate;
4243 config.channel_mask = sourceDesc->config().channel_mask;
4244 config.format = sourceDesc->config().format;
4245 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4246 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4247 bool isRequestedDeviceForExclusiveUse = false;
4248 output_type_t outputType;
4249 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4250 &stream, sourceDesc->uid(), &config, &flags,
4251 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4252 nullptr, &outputType);
4253 if (output == AUDIO_IO_HANDLE_NONE) {
4254 ALOGV("%s no output for device %s",
4255 __FUNCTION__, sinkDevice->toString().c_str());
4256 return INVALID_OPERATION;
4257 }
4258 outputDesc = mOutputs.valueFor(output);
4259 if (outputDesc->isDuplicated()) {
4260 ALOGE("%s output is duplicated", __func__);
4261 return INVALID_OPERATION;
4262 }
4263 sourceDesc->setSwOutput(outputDesc);
4264 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004265 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004266 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004267 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004268 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004269 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4270 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004271 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4272 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004273 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4274 (sourceDesc != nullptr &&
4275 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004276 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004277 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004278 return INVALID_OPERATION;
4279 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004280 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004281 SortedVector<audio_io_handle_t> outputs =
4282 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4283 // if the sink device is reachable via an opened output stream, request to
4284 // go via this output stream by adding a second source to the patch
4285 // description
4286 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004287 if (output != AUDIO_IO_HANDLE_NONE) {
4288 outputDesc = mOutputs.valueFor(output);
4289 if (outputDesc->isDuplicated()) {
4290 ALOGV("%s output for device %s is duplicated",
4291 __FUNCTION__, sinkDevice->toString().c_str());
4292 return INVALID_OPERATION;
4293 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004294 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004295 }
4296 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004297 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004298 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004299 // for volume control, we may need a valid stream
4300 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4301 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4302 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004303 }
Eric Laurent83b88082014-06-20 18:31:16 -07004304 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004305 }
4306 // TODO: check from routing capabilities in config file and other conflicting patches
4307
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004308installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004309 status_t status = installPatch(
4310 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004311 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004312 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004313 return INVALID_OPERATION;
4314 }
4315 } else {
4316 return BAD_VALUE;
4317 }
4318 } else {
4319 return BAD_VALUE;
4320 }
4321 return NO_ERROR;
4322}
4323
4324status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4325 uid_t uid)
4326{
4327 ALOGV("releaseAudioPatch() patch %d", handle);
4328
4329 ssize_t index = mAudioPatches.indexOfKey(handle);
4330
4331 if (index < 0) {
4332 return BAD_VALUE;
4333 }
4334 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004335 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4336 __func__, mUidCached, patchDesc->getUid(), uid);
4337 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004338 return INVALID_OPERATION;
4339 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004340 return releaseAudioPatchInternal(handle);
4341}
Eric Laurent6a94d692014-05-20 11:18:06 -07004342
François Gaffieafd4cea2019-11-18 15:50:22 +01004343status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4344 uint32_t delayMs)
4345{
4346 ALOGV("%s patch %d", __func__, handle);
4347 if (mAudioPatches.indexOfKey(handle) < 0) {
4348 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4349 return BAD_VALUE;
4350 }
4351 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004352 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004353 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004354 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004355 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004356 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004357 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004358 return BAD_VALUE;
4359 }
4360
François Gaffie11d30102018-11-02 16:09:09 +01004361 setOutputDevices(outputDesc,
4362 getNewOutputDevices(outputDesc, true /*fromCache*/),
4363 true,
4364 0,
4365 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004366 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4367 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004368 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004369 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004370 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004371 return BAD_VALUE;
4372 }
4373 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004374 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004375 true,
4376 NULL);
4377 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004378 status_t status =
4379 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4380 ALOGV("%s patch panel returned %d patchHandle %d",
4381 __func__, status, patchDesc->getAfHandle());
4382 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004383 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004384 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004385 // SW Bridge
4386 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4387 sp<SwAudioOutputDescriptor> outputDesc =
4388 mOutputs.getOutputFromId(patch->sources[1].id);
4389 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004390 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4391 // releaseOutput has already called closeOuput in case of direct output
4392 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004393 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004394 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4395 // force SwOutput patch removal as AF counter part patch has already gone.
4396 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4397 removeAudioPatch(outputDesc->getPatchHandle());
4398 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004399 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4400 setOutputDevices(outputDesc,
4401 getNewOutputDevices(outputDesc, true /*fromCache*/),
4402 true, /*force*/
4403 0,
4404 NULL);
4405 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004406 } else {
4407 return BAD_VALUE;
4408 }
4409 } else {
4410 return BAD_VALUE;
4411 }
4412 return NO_ERROR;
4413}
4414
4415status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4416 struct audio_patch *patches,
4417 unsigned int *generation)
4418{
François Gaffie53615e22015-03-19 09:24:12 +01004419 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004420 return BAD_VALUE;
4421 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004423 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004424}
4425
Eric Laurente1715a42014-05-20 11:30:42 -07004426status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004427{
Eric Laurente1715a42014-05-20 11:30:42 -07004428 ALOGV("setAudioPortConfig()");
4429
4430 if (config == NULL) {
4431 return BAD_VALUE;
4432 }
4433 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4434 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004435 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4436 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004437 }
4438
Eric Laurenta121f902014-06-03 13:32:54 -07004439 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004440 if (config->type == AUDIO_PORT_TYPE_MIX) {
4441 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004442 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004443 if (outputDesc == NULL) {
4444 return BAD_VALUE;
4445 }
Eric Laurent84c70242014-06-23 08:46:27 -07004446 ALOG_ASSERT(!outputDesc->isDuplicated(),
4447 "setAudioPortConfig() called on duplicated output %d",
4448 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004449 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004450 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004451 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004452 if (inputDesc == NULL) {
4453 return BAD_VALUE;
4454 }
Eric Laurenta121f902014-06-03 13:32:54 -07004455 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004456 } else {
4457 return BAD_VALUE;
4458 }
4459 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4460 sp<DeviceDescriptor> deviceDesc;
4461 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4462 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4463 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4464 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4465 } else {
4466 return BAD_VALUE;
4467 }
4468 if (deviceDesc == NULL) {
4469 return BAD_VALUE;
4470 }
Eric Laurenta121f902014-06-03 13:32:54 -07004471 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004472 } else {
4473 return BAD_VALUE;
4474 }
4475
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004476 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004477 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4478 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004479 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004480 audioPortConfig->toAudioPortConfig(&newConfig, config);
4481 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004482 }
Eric Laurenta121f902014-06-03 13:32:54 -07004483 if (status != NO_ERROR) {
4484 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004485 }
Eric Laurente1715a42014-05-20 11:30:42 -07004486
4487 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004488}
4489
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004490void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4491{
Eric Laurentd60560a2015-04-10 11:31:20 -07004492 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004493 clearAudioPatches(uid);
4494 clearSessionRoutes(uid);
4495}
4496
Eric Laurent6a94d692014-05-20 11:18:06 -07004497void AudioPolicyManager::clearAudioPatches(uid_t uid)
4498{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004499 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004500 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004501 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004502 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 }
4504 }
4505}
4506
François Gaffiec005e562018-11-06 15:04:49 +01004507void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004508{
François Gaffiec005e562018-11-06 15:04:49 +01004509 // Take the first attributes following the product strategy as it is used to retrieve the routed
4510 // device. All attributes wihin a strategy follows the same "routing strategy"
4511 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4512 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004513 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004514 for (size_t j = 0; j < mOutputs.size(); j++) {
4515 if (mOutputs.keyAt(j) == ouptutToSkip) {
4516 continue;
4517 }
4518 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004519 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004520 continue;
4521 }
4522 // If the default device for this strategy is on another output mix,
4523 // invalidate all tracks in this strategy to force re connection.
4524 // Otherwise select new device on the output mix.
4525 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004526 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4527 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004528 }
4529 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004530 setOutputDevices(
4531 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004532 }
4533 }
4534}
4535
4536void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4537{
4538 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004539 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004540 for (size_t i = 0; i < mOutputs.size(); i++) {
4541 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004542 for (const auto& client : outputDesc->getClientIterable()) {
4543 if (client->hasPreferredDevice() && client->uid() == uid) {
4544 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004545 auto clientStrategy = client->strategy();
4546 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4547 end(affectedStrategies)) {
4548 continue;
4549 }
4550 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004551 }
4552 }
4553 }
4554 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004555 for (const auto& strategy : affectedStrategies) {
4556 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004557 }
4558
4559 // remove input routes associated with this uid
4560 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004561 for (size_t i = 0; i < mInputs.size(); i++) {
4562 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004563 for (const auto& client : inputDesc->getClientIterable()) {
4564 if (client->hasPreferredDevice() && client->uid() == uid) {
4565 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4566 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004567 }
4568 }
4569 }
4570 // reroute inputs if necessary
4571 SortedVector<audio_io_handle_t> inputsToClose;
4572 for (size_t i = 0; i < mInputs.size(); i++) {
4573 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004574 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004575 inputsToClose.add(inputDesc->mIoHandle);
4576 }
4577 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004578 for (const auto& input : inputsToClose) {
4579 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004580 }
4581}
4582
Eric Laurentd60560a2015-04-10 11:31:20 -07004583void AudioPolicyManager::clearAudioSources(uid_t uid)
4584{
4585 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004586 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4587 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004588 stopAudioSource(mAudioSources.keyAt(i));
4589 }
4590 }
4591}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004592
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004593status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4594 audio_io_handle_t *ioHandle,
4595 audio_devices_t *device)
4596{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004597 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4598 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004599 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004600 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004601
François Gaffiedf372692015-03-19 10:43:27 +01004602 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004603}
4604
Eric Laurentd60560a2015-04-10 11:31:20 -07004605status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004606 const audio_attributes_t *attributes,
4607 audio_port_handle_t *portId,
4608 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004609{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004610 ALOGV("%s", __FUNCTION__);
4611 *portId = AUDIO_PORT_HANDLE_NONE;
4612
4613 if (source == NULL || attributes == NULL || portId == NULL) {
4614 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4615 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004616 return BAD_VALUE;
4617 }
4618
Eric Laurentd60560a2015-04-10 11:31:20 -07004619 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4620 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004621 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4622 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004623 return INVALID_OPERATION;
4624 }
4625
François Gaffie11d30102018-11-02 16:09:09 +01004626 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004627 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004628 String8(source->ext.device.address),
4629 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004630 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004631 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004632 return BAD_VALUE;
4633 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004634
jiabin4ef93452019-09-10 14:29:54 -07004635 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004636
François Gaffieaaac0fd2018-11-22 17:56:39 +01004637 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004638 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004639 mEngine->getStreamTypeForAttributes(*attributes),
4640 mEngine->getProductStrategyForAttributes(*attributes),
4641 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004642
4643 status_t status = connectAudioSource(sourceDesc);
4644 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004645 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004646 }
4647 return status;
4648}
4649
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004650status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004651{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004652 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004653
4654 // make sure we only have one patch per source.
4655 disconnectAudioSource(sourceDesc);
4656
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004657 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004658 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4659 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4660 sourceDesc->srcDevice()->type(),
4661 String8(sourceDesc->srcDevice()->address().c_str()),
4662 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004663 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004664 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004665 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004666 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004667 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4668 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4669 return INVALID_OPERATION;
4670 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004671 PatchBuilder patchBuilder;
4672 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4673 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4674 status_t status =
4675 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4676 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4677 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4678 return INVALID_OPERATION;
4679 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004680 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004681 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4682 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4683 if (swOutput != 0) {
4684 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004685 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004686 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004687 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004688 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004689 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004690 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004691 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004692 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004693 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004694 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004695 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004696 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4697 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004698 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004699 if (delayMs != 0) {
4700 usleep(delayMs * 1000);
4701 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004702 } else {
4703 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4704 if (hwOutputDesc != 0) {
4705 // create Hwoutput and add to mHwOutputs
4706 } else {
4707 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4708 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004709 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004710 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004711
4712FailureSourceActive:
4713 swOutput->stop();
4714 releaseOutput(sourceDesc->portId());
4715FailureSourceAdded:
4716 sourceDesc->setSwOutput(nullptr);
4717FailureReleasePatch:
4718 releaseAudioPatchInternal(handle);
4719 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004720}
4721
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004722status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004723{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004724 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4725 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004726 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004727 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004728 return BAD_VALUE;
4729 }
4730 status_t status = disconnectAudioSource(sourceDesc);
4731
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004732 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004733 return status;
4734}
4735
Andy Hung2ddee192015-12-18 17:34:44 -08004736status_t AudioPolicyManager::setMasterMono(bool mono)
4737{
4738 if (mMasterMono == mono) {
4739 return NO_ERROR;
4740 }
4741 mMasterMono = mono;
4742 // if enabling mono we close all offloaded devices, which will invalidate the
4743 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4744 // for recreating the new AudioTrack as non-offloaded PCM.
4745 //
4746 // If disabling mono, we leave all tracks as is: we don't know which clients
4747 // and tracks are able to be recreated as offloaded. The next "song" should
4748 // play back offloaded.
4749 if (mMasterMono) {
4750 Vector<audio_io_handle_t> offloaded;
4751 for (size_t i = 0; i < mOutputs.size(); ++i) {
4752 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4753 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4754 offloaded.push(desc->mIoHandle);
4755 }
4756 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004757 for (const auto& handle : offloaded) {
4758 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004759 }
4760 }
4761 // update master mono for all remaining outputs
4762 for (size_t i = 0; i < mOutputs.size(); ++i) {
4763 updateMono(mOutputs.keyAt(i));
4764 }
4765 return NO_ERROR;
4766}
4767
4768status_t AudioPolicyManager::getMasterMono(bool *mono)
4769{
4770 *mono = mMasterMono;
4771 return NO_ERROR;
4772}
4773
Eric Laurentac9cef52017-06-09 15:46:26 -07004774float AudioPolicyManager::getStreamVolumeDB(
4775 audio_stream_type_t stream, int index, audio_devices_t device)
4776{
jiabin9a3361e2019-10-01 09:38:30 -07004777 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004778}
4779
jiabin81772902018-04-02 17:52:27 -07004780status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4781 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004782 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004783{
Kriti Dang6537def2021-03-02 13:46:59 +01004784 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4785 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004786 return BAD_VALUE;
4787 }
Kriti Dang6537def2021-03-02 13:46:59 +01004788 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4789 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004790
4791 size_t formatsWritten = 0;
4792 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004793
Kriti Dang6537def2021-03-02 13:46:59 +01004794 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004795 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4796 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004797 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004798 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004799 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004800 bool formatEnabled = true;
4801 switch (forceUse) {
4802 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004803 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004804 break;
4805 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4806 formatEnabled = false;
4807 break;
4808 default: // AUTO or ALWAYS => true
4809 break;
jiabin81772902018-04-02 17:52:27 -07004810 }
4811 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4812 }
jiabin81772902018-04-02 17:52:27 -07004813 }
4814 return NO_ERROR;
4815}
4816
Kriti Dang6537def2021-03-02 13:46:59 +01004817status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4818 audio_format_t *surroundFormats) {
4819 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4820 return BAD_VALUE;
4821 }
4822 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4823 __func__, *numSurroundFormats, surroundFormats);
4824
4825 size_t formatsWritten = 0;
4826 size_t formatsMax = *numSurroundFormats;
4827 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4828
4829 // Return formats from all device profiles that have already been resolved by
4830 // checkOutputsForDevice().
4831 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4832 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4833 audio_devices_t deviceType = device->type();
4834 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4835 // returns formats reported by HDMI devices.
4836 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4837 continue;
4838 }
4839 // Formats reported by sink devices
4840 std::unordered_set<audio_format_t> formatset;
4841 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4842 formatset.insert(it->second.begin(), it->second.end());
4843 }
4844
4845 // Formats hard-coded in the in policy configuration file (if any).
4846 FormatVector encodedFormats = device->encodedFormats();
4847 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4848 // Filter the formats which are supported by the vendor hardware.
4849 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4850 if (mConfig.getSurroundFormats().count(*it) != 0) {
4851 formats.insert(*it);
4852 } else {
4853 for (const auto& pair : mConfig.getSurroundFormats()) {
4854 if (pair.second.count(*it) != 0) {
4855 formats.insert(pair.first);
4856 break;
4857 }
4858 }
4859 }
4860 }
4861 }
4862 *numSurroundFormats = formats.size();
4863 for (const auto& format: formats) {
4864 if (formatsWritten < formatsMax) {
4865 surroundFormats[formatsWritten++] = format;
4866 }
4867 }
4868 return NO_ERROR;
4869}
4870
jiabin81772902018-04-02 17:52:27 -07004871status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4872{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004873 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004874 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4875 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004876 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004877 return BAD_VALUE;
4878 }
4879
Mikhail Naganov100f0122018-11-29 11:22:16 -08004880 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4881 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004882 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004883 return INVALID_OPERATION;
4884 }
4885
Mikhail Naganov100f0122018-11-29 11:22:16 -08004886 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004887 return NO_ERROR;
4888 }
4889
Mikhail Naganov100f0122018-11-29 11:22:16 -08004890 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004891 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004892 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004893 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004894 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004895 }
4896 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004897 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004898 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004899 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004900 }
4901 }
4902
4903 sp<SwAudioOutputDescriptor> outputDesc;
4904 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004905 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4906 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004907 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4908 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004909 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004910 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004911 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4912 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4913 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004914 name.c_str(),
4915 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004916 if (status != NO_ERROR) {
4917 continue;
4918 }
4919 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4920 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4921 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004922 name.c_str(),
4923 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004924 profileUpdated |= (status == NO_ERROR);
4925 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004926 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004927 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004928 AUDIO_DEVICE_IN_HDMI);
4929 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4930 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004931 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004932 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004933 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4934 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4935 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004936 name.c_str(),
4937 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004938 if (status != NO_ERROR) {
4939 continue;
4940 }
4941 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4942 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4943 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004944 name.c_str(),
4945 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004946 profileUpdated |= (status == NO_ERROR);
4947 }
4948
jiabin81772902018-04-02 17:52:27 -07004949 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004950 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004951 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004952 }
4953
4954 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4955}
4956
Eric Laurent5ada82e2019-08-29 17:53:54 -07004957void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004958{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004959 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004960 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004961 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004962 }
4963}
4964
jiabin6012f912018-11-02 17:06:30 -07004965bool AudioPolicyManager::isHapticPlaybackSupported()
4966{
4967 for (const auto& hwModule : mHwModules) {
4968 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4969 for (const auto &outProfile : outputProfiles) {
4970 struct audio_port audioPort;
4971 outProfile->toAudioPort(&audioPort);
4972 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4973 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4974 return true;
4975 }
4976 }
4977 }
4978 }
4979 return false;
4980}
4981
Carter Hsu325a8eb2022-01-19 19:56:51 +08004982bool AudioPolicyManager::isUltrasoundSupported()
4983{
4984 bool hasUltrasoundOutput = false;
4985 bool hasUltrasoundInput = false;
4986 for (const auto& hwModule : mHwModules) {
4987 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4988 if (!hasUltrasoundOutput) {
4989 for (const auto &outProfile : outputProfiles) {
4990 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
4991 hasUltrasoundOutput = true;
4992 break;
4993 }
4994 }
4995 }
4996
4997 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
4998 if (!hasUltrasoundInput) {
4999 for (const auto &inputProfile : inputProfiles) {
5000 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5001 hasUltrasoundInput = true;
5002 break;
5003 }
5004 }
5005 }
5006
5007 if (hasUltrasoundOutput && hasUltrasoundInput)
5008 return true;
5009 }
5010 return false;
5011}
5012
Eric Laurent8340e672019-11-06 11:01:08 -08005013bool AudioPolicyManager::isCallScreenModeSupported()
5014{
5015 return getConfig().isCallScreenModeSupported();
5016}
5017
5018
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005019status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005020{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005021 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005022 if (!sourceDesc->isConnected()) {
5023 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5024 return NO_ERROR;
5025 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005026 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5027 if (swOutput != 0) {
5028 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005029 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005030 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005031 }
jiabinbce0c1d2020-10-05 11:20:18 -07005032 if (releaseOutput(sourceDesc->portId())) {
5033 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5034 // no need to release audio patch here but just return NO_ERROR.
5035 return NO_ERROR;
5036 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005037 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005038 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005039 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005040 // close Hwoutput and remove from mHwOutputs
5041 } else {
5042 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5043 }
5044 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005045 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
5046 sourceDesc->disconnect();
5047 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005048}
5049
François Gaffiec005e562018-11-06 15:04:49 +01005050sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5051 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005052{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005053 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005054 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005055 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005056 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005057 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5058 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005059 source = sourceDesc;
5060 break;
5061 }
5062 }
5063 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005064}
5065
Eric Laurent39095982021-08-24 18:29:27 +02005066/* static */
5067bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5068 switch (channels) {
5069 case AUDIO_CHANNEL_OUT_5POINT1:
5070 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5071 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5072 case AUDIO_CHANNEL_OUT_7POINT1:
5073 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5074 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5075 return true;
5076 default:
5077 return false;
5078 }
5079}
5080
Eric Laurentb4f42a92022-01-17 17:37:31 +01005081bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005082 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005083 const AudioDeviceTypeAddrVector &devices,
5084 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005085{
5086 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5087 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005088 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005089 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005090 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5091 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5092 return false;
5093 }
5094 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5095 return false;
5096 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005097 }
5098
5099 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005100 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5101 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005102 // to the specified devices must exist.
5103 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005104 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005105 if (profile == nullptr) {
5106 return false;
5107 }
5108
5109 // The caller can have the audio config criteria ignored by either passing a null ptr or
5110 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005111 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005112 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005113 // If the spatializer output is already opened, only channel masks included in the
5114 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005115
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005116 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005117 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005118 return false;
5119 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005120 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5121 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005122 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005123 != config->channel_mask) {
5124 return false;
5125 }
5126 }
5127 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005128 return true;
5129}
5130
5131void AudioPolicyManager::checkVirtualizerClientRoutes() {
5132 std::set<audio_stream_type_t> streamsToInvalidate;
5133 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005134 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5135 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005136 audio_attributes_t attr = client->attributes();
5137 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5138 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5139 audio_config_base_t clientConfig = client->config();
5140 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005141 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005142 && canBeSpatializedInt(&attr, &config,
5143 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005144 streamsToInvalidate.insert(client->stream());
5145 }
5146 }
5147 }
5148
5149 for (audio_stream_type_t stream : streamsToInvalidate) {
5150 mpClientInterface->invalidateStream(stream);
5151 }
5152}
5153
Eric Laurentfa0f6742021-08-17 18:39:44 +02005154status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005155 const audio_attributes_t *attr,
5156 audio_io_handle_t *output) {
5157 *output = AUDIO_IO_HANDLE_NONE;
5158
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005159 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5160 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5161 audio_config_t *configPtr = nullptr;
5162 audio_config_t config;
5163 if (mixerConfig != nullptr) {
5164 config = audio_config_initializer(mixerConfig);
5165 configPtr = &config;
5166 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005167 if (!canBeSpatializedInt(
5168 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005169 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005170 return BAD_VALUE;
5171 }
5172
5173 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005174 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005175 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005176 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005177 return BAD_VALUE;
5178 }
5179
Eric Laurent39095982021-08-24 18:29:27 +02005180 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5181 && configPtr != nullptr
5182 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5183 *output = mSpatializerOutput->mIoHandle;
5184 ALOGV("%s returns current spatializer output %d", __func__, *output);
5185 return NO_ERROR;
5186 }
5187 mSpatializerOutput.clear();
5188 for (size_t i = 0; i < mOutputs.size(); i++) {
5189 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5190 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005191 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005192 mSpatializerOutput = desc;
5193 break;
5194 }
5195 }
5196 if (mSpatializerOutput == nullptr) {
5197 ALOGW("%s no opened spatializer output for profile %s",
5198 __func__, profile->getName().c_str());
5199 return BAD_VALUE;
5200 }
5201
5202 if (configPtr != nullptr
5203 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5204 audio_config_base_t savedMixerConfig = {
5205 .sample_rate = mSpatializerOutput->getSamplingRate(),
5206 .format = mSpatializerOutput->getFormat(),
5207 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5208 };
5209 DeviceVector savedDevices = mSpatializerOutput->devices();
5210
Eric Laurentb4f42a92022-01-17 17:37:31 +01005211 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5212 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005213
Eric Laurentb4f42a92022-01-17 17:37:31 +01005214 closeOutput(mSpatializerOutput->mIoHandle);
5215 //from now on mSpatializerOutput is null
5216
5217 sp<SwAudioOutputDescriptor> desc =
5218 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5219 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005220 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005221 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5222 if (desc == nullptr) {
5223 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005224 } else {
5225 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005226 }
5227 mPreviousOutputs = mOutputs;
5228 mpClientInterface->onAudioPortListUpdate();
5229 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005230 ALOGW("%s could not open spatializer output with requested config", __func__);
5231 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005232 }
Eric Laurent39095982021-08-24 18:29:27 +02005233 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005234 mPreviousOutputs = mOutputs;
5235 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005236 }
5237
5238 checkVirtualizerClientRoutes();
5239
Eric Laurent39095982021-08-24 18:29:27 +02005240 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005241 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005242 return NO_ERROR;
5243}
5244
Eric Laurentfa0f6742021-08-17 18:39:44 +02005245status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5246 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005247 return INVALID_OPERATION;
5248 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005249 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005250 return BAD_VALUE;
5251 }
Eric Laurent39095982021-08-24 18:29:27 +02005252
Eric Laurentfa0f6742021-08-17 18:39:44 +02005253 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005254
5255 checkVirtualizerClientRoutes();
5256
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005257 return NO_ERROR;
5258}
5259
Eric Laurente552edb2014-03-10 17:42:56 -07005260// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005261// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005262// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005263uint32_t AudioPolicyManager::nextAudioPortGeneration()
5264{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005265 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005266}
5267
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005268static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005269 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5270 !audioPolicyXmlConfigFile.empty()) {
5271 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5272 if (ret == NO_ERROR) {
5273 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005274 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005275 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005276 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005277 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005278}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005279
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005280AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5281 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005282 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005283 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005284 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005285 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005286 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005287 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005288 mAudioPortGeneration(1),
5289 mBeaconMuteRefCount(0),
5290 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005291 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005292 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005293 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005294 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005295{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005296}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005297
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005298AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5299 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5300{
5301 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005302}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005303
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005304void AudioPolicyManager::loadConfig() {
5305 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005306 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005307 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005308 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005309}
5310
5311status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005312 {
5313 auto engLib = EngineLibrary::load(
5314 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5315 if (!engLib) {
5316 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5317 return NO_INIT;
5318 }
5319 mEngine = engLib->createEngine();
5320 if (mEngine == nullptr) {
5321 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5322 return NO_INIT;
5323 }
François Gaffie2110e042015-03-24 08:41:51 +01005324 }
5325 mEngine->setObserver(this);
5326 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005327 if (status != NO_ERROR) {
5328 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5329 return status;
5330 }
François Gaffie2110e042015-03-24 08:41:51 +01005331
Eric Laurent1d69c872021-01-11 18:53:01 +01005332 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5333 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5334
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005335 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005336 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005337 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005338
Eric Laurent3a4311c2014-03-17 12:00:47 -07005339 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005340 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5341 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5342 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005343 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005344 }
jiabin9ff780e2018-03-19 18:19:52 -07005345 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005346 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005347 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005348 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005349 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005350 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005351 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005352 }
5353 }
5354 }
Eric Laurente552edb2014-03-10 17:42:56 -07005355
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005356 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005357
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005358 // Silence ALOGV statements
5359 property_set("log.tag." LOG_TAG, "D");
5360
Eric Laurente552edb2014-03-10 17:42:56 -07005361 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005362 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005363}
5364
Eric Laurente0720872014-03-11 09:30:41 -07005365AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005366{
Eric Laurente552edb2014-03-10 17:42:56 -07005367 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005368 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005369 }
5370 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005371 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005372 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005373 mAvailableOutputDevices.clear();
5374 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005375 mOutputs.clear();
5376 mInputs.clear();
5377 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005378 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005379 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005380}
5381
Eric Laurente0720872014-03-11 09:30:41 -07005382status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005383{
Eric Laurent87ffa392015-05-22 10:32:38 -07005384 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005385}
5386
Eric Laurente552edb2014-03-10 17:42:56 -07005387// ---
5388
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005389void AudioPolicyManager::onNewAudioModulesAvailable()
5390{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005391 DeviceVector newDevices;
5392 onNewAudioModulesAvailableInt(&newDevices);
5393 if (!newDevices.empty()) {
5394 nextAudioPortGeneration();
5395 mpClientInterface->onAudioPortListUpdate();
5396 }
5397}
5398
5399void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5400{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005401 for (const auto& hwModule : mHwModulesAll) {
5402 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5403 continue;
5404 }
5405 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5406 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5407 ALOGW("could not open HW module %s", hwModule->getName());
5408 continue;
5409 }
5410 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005411 // open all output streams needed to access attached devices.
5412 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005413 // This also validates mAvailableOutputDevices list
5414 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5415 if (!outProfile->canOpenNewIo()) {
5416 ALOGE("Invalid Output profile max open count %u for profile %s",
5417 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5418 continue;
5419 }
5420 if (!outProfile->hasSupportedDevices()) {
5421 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5422 continue;
5423 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005424 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5425 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005426 mTtsOutputAvailable = true;
5427 }
5428
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005429 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5430 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5431 sp<DeviceDescriptor> supportedDevice = 0;
5432 if (supportedDevices.contains(mDefaultOutputDevice)) {
5433 supportedDevice = mDefaultOutputDevice;
5434 } else {
5435 // choose first device present in profile's SupportedDevices also part of
5436 // mAvailableOutputDevices.
5437 if (availProfileDevices.isEmpty()) {
5438 continue;
5439 }
5440 supportedDevice = availProfileDevices.itemAt(0);
5441 }
5442 if (!mOutputDevicesAll.contains(supportedDevice)) {
5443 continue;
5444 }
5445 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5446 mpClientInterface);
5447 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005448 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5449 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005450 AUDIO_STREAM_DEFAULT,
5451 AUDIO_OUTPUT_FLAG_NONE, &output);
5452 if (status != NO_ERROR) {
5453 ALOGW("Cannot open output stream for devices %s on hw module %s",
5454 supportedDevice->toString().c_str(), hwModule->getName());
5455 continue;
5456 }
5457 for (const auto &device : availProfileDevices) {
5458 // give a valid ID to an attached device once confirmed it is reachable
5459 if (!device->isAttached()) {
5460 device->attach(hwModule);
5461 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005462 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005463 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005464 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5465 }
5466 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005467 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005468 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5469 mPrimaryOutput = outputDesc;
5470 }
Eric Laurent39095982021-08-24 18:29:27 +02005471 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005472 outputDesc->close();
5473 } else {
5474 addOutput(output, outputDesc);
5475 setOutputDevices(outputDesc,
5476 DeviceVector(supportedDevice),
5477 true,
5478 0,
5479 NULL);
5480 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005481 }
5482 // open input streams needed to access attached devices to validate
5483 // mAvailableInputDevices list
5484 for (const auto& inProfile : hwModule->getInputProfiles()) {
5485 if (!inProfile->canOpenNewIo()) {
5486 ALOGE("Invalid Input profile max open count %u for profile %s",
5487 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5488 continue;
5489 }
5490 if (!inProfile->hasSupportedDevices()) {
5491 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5492 continue;
5493 }
5494 // chose first device present in profile's SupportedDevices also part of
5495 // available input devices
5496 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5497 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5498 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005499 ALOGV("%s: Input device list is empty! for profile %s",
5500 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005501 continue;
5502 }
5503 sp<AudioInputDescriptor> inputDesc =
5504 new AudioInputDescriptor(inProfile, mpClientInterface);
5505
5506 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5507 status_t status = inputDesc->open(nullptr,
5508 availProfileDevices.itemAt(0),
5509 AUDIO_SOURCE_MIC,
5510 AUDIO_INPUT_FLAG_NONE,
5511 &input);
5512 if (status != NO_ERROR) {
5513 ALOGW("Cannot open input stream for device %s on hw module %s",
5514 availProfileDevices.toString().c_str(),
5515 hwModule->getName());
5516 continue;
5517 }
5518 for (const auto &device : availProfileDevices) {
5519 // give a valid ID to an attached device once confirmed it is reachable
5520 if (!device->isAttached()) {
5521 device->attach(hwModule);
5522 device->importAudioPortAndPickAudioProfile(inProfile, true);
5523 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005524 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005525 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5526 }
5527 }
5528 inputDesc->close();
5529 }
5530 }
5531}
5532
Eric Laurent98e38192018-02-15 18:31:53 -08005533void AudioPolicyManager::addOutput(audio_io_handle_t output,
5534 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005535{
Eric Laurent1c333e22014-05-20 10:48:17 -07005536 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005537 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005538 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005539 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005541}
5542
François Gaffie53615e22015-03-19 09:24:12 +01005543void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5544{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005545 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5546 ALOGV("%s: removing primary output", __func__);
5547 mPrimaryOutput = nullptr;
5548 }
François Gaffie53615e22015-03-19 09:24:12 +01005549 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005550 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005551}
5552
Eric Laurent98e38192018-02-15 18:31:53 -08005553void AudioPolicyManager::addInput(audio_io_handle_t input,
5554 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005555{
Eric Laurent1c333e22014-05-20 10:48:17 -07005556 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005558}
Eric Laurente552edb2014-03-10 17:42:56 -07005559
François Gaffie11d30102018-11-02 16:09:09 +01005560status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005561 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005562 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005563{
François Gaffie11d30102018-11-02 16:09:09 +01005564 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005565 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005566 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005567
François Gaffie11d30102018-11-02 16:09:09 +01005568 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005569 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005570 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005571 }
Eric Laurente552edb2014-03-10 17:42:56 -07005572
Eric Laurent3b73df72014-03-11 09:06:29 -07005573 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005574 // first call getAudioPort to get the supported attributes from the HAL
5575 struct audio_port_v7 port = {};
5576 device->toAudioPort(&port);
5577 status_t status = mpClientInterface->getAudioPort(&port);
5578 if (status == NO_ERROR) {
5579 device->importAudioPort(port);
5580 }
5581
5582 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005583 for (size_t i = 0; i < mOutputs.size(); i++) {
5584 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005585 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005586 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005587 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5588 mOutputs.keyAt(i), device->toString().c_str());
5589 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005590 }
5591 }
5592 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005593 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005594 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005595 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5596 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005597 if (profile->supportsDevice(device)) {
5598 profiles.add(profile);
5599 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5600 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005601 }
5602 }
5603 }
5604
Eric Laurent7b279bb2015-12-14 10:18:23 -08005605 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005606
Eric Laurente552edb2014-03-10 17:42:56 -07005607 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005608 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005609 return BAD_VALUE;
5610 }
5611
5612 // open outputs for matching profiles if needed. Direct outputs are also opened to
5613 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5614 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005615 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005616
5617 // nothing to do if one output is already opened for this profile
5618 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005619 for (j = 0; j < outputs.size(); j++) {
5620 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005621 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005622 // matching profile: save the sample rates, format and channel masks supported
5623 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005624 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005625 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005626 }
Eric Laurente552edb2014-03-10 17:42:56 -07005627 break;
5628 }
5629 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005630 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005631 continue;
5632 }
5633
Eric Laurent3974e3b2017-12-07 17:58:43 -08005634 if (!profile->canOpenNewIo()) {
5635 ALOGW("Max Output number %u already opened for this profile %s",
5636 profile->maxOpenCount, profile->getTagName().c_str());
5637 continue;
5638 }
5639
Eric Laurent83efe1c2017-07-09 16:51:08 -07005640 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005641 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005642 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5643 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005644 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005645 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005646 profiles.removeAt(profile_index);
5647 profile_index--;
5648 } else {
5649 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005650 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005651 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005652 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5653 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005654 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005655 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005656
François Gaffie11d30102018-11-02 16:09:09 +01005657 if (device_distinguishes_on_address(deviceType)) {
5658 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5659 device->toString().c_str());
5660 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5661 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005662 }
Eric Laurente552edb2014-03-10 17:42:56 -07005663 ALOGV("checkOutputsForDevice(): adding output %d", output);
5664 }
5665 }
5666
5667 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005668 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005669 return BAD_VALUE;
5670 }
Eric Laurentd4692962014-05-05 18:13:44 -07005671 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005672 // check if one opened output is not needed any more after disconnecting one device
5673 for (size_t i = 0; i < mOutputs.size(); i++) {
5674 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005675 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005676 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005677 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005678 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005679 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005680 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005681 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5682 mOutputs.keyAt(i));
5683 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005684 }
Eric Laurente552edb2014-03-10 17:42:56 -07005685 }
5686 }
Eric Laurentd4692962014-05-05 18:13:44 -07005687 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005688 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005689 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5690 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005691 if (!profile->supportsDevice(device)) {
5692 continue;
5693 }
5694 ALOGV("checkOutputsForDevice(): "
5695 "clearing direct output profile %zu on module %s",
5696 j, hwModule->getName());
5697 profile->clearAudioProfiles();
5698 if (!profile->hasDynamicAudioProfile()) {
5699 continue;
5700 }
5701 // When a device is disconnected, if there is an IOProfile that contains dynamic
5702 // profiles and supports the disconnected device, call getAudioPort to repopulate
5703 // the capabilities of the devices that is supported by the IOProfile.
5704 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5705 if (supportedDevice == device ||
5706 !mAvailableOutputDevices.contains(supportedDevice)) {
5707 continue;
5708 }
5709 struct audio_port_v7 port;
5710 supportedDevice->toAudioPort(&port);
5711 status_t status = mpClientInterface->getAudioPort(&port);
5712 if (status == NO_ERROR) {
5713 supportedDevice->importAudioPort(port);
5714 }
Eric Laurente552edb2014-03-10 17:42:56 -07005715 }
5716 }
5717 }
5718 }
5719 return NO_ERROR;
5720}
5721
François Gaffie11d30102018-11-02 16:09:09 +01005722status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005723 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005724{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005725 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005726
François Gaffie11d30102018-11-02 16:09:09 +01005727 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005728 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005729 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005730 }
5731
Eric Laurentd4692962014-05-05 18:13:44 -07005732 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005733 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005734 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005735 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005736 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005737 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005738 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005739 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005740
François Gaffie11d30102018-11-02 16:09:09 +01005741 if (profile->supportsDevice(device)) {
5742 profiles.add(profile);
5743 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5744 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005745 }
5746 }
5747 }
5748
Eric Laurent0dd51852019-04-19 18:18:58 -07005749 if (profiles.isEmpty()) {
5750 ALOGW("%s: No input profile available for device %s",
5751 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005752 return BAD_VALUE;
5753 }
5754
5755 // open inputs for matching profiles if needed. Direct inputs are also opened to
5756 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5757 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5758
Eric Laurent1c333e22014-05-20 10:48:17 -07005759 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005760
Eric Laurentd4692962014-05-05 18:13:44 -07005761 // nothing to do if one input is already opened for this profile
5762 size_t input_index;
5763 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5764 desc = mInputs.valueAt(input_index);
5765 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005766 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005767 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005768 }
Eric Laurentd4692962014-05-05 18:13:44 -07005769 break;
5770 }
5771 }
5772 if (input_index != mInputs.size()) {
5773 continue;
5774 }
5775
Eric Laurent3974e3b2017-12-07 17:58:43 -08005776 if (!profile->canOpenNewIo()) {
5777 ALOGW("Max Input number %u already opened for this profile %s",
5778 profile->maxOpenCount, profile->getTagName().c_str());
5779 continue;
5780 }
5781
Eric Laurentfe231122017-11-17 17:48:06 -08005782 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005783 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005784 status_t status = desc->open(nullptr,
5785 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005786 AUDIO_SOURCE_MIC,
5787 AUDIO_INPUT_FLAG_NONE,
5788 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005789
Eric Laurentcf2c0212014-07-25 16:20:43 -07005790 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005791 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005792 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005793 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005794 mpClientInterface->setParameters(input, String8(param));
5795 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005796 }
François Gaffie11d30102018-11-02 16:09:09 +01005797 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005798 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005799 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005800 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005801 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005802 }
5803
Eric Laurent0dd51852019-04-19 18:18:58 -07005804 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005805 addInput(input, desc);
5806 }
5807 } // endif input != 0
5808
Eric Laurentcf2c0212014-07-25 16:20:43 -07005809 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005810 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005811 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005812 profiles.removeAt(profile_index);
5813 profile_index--;
5814 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005815 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005816 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005817 }
Eric Laurentd4692962014-05-05 18:13:44 -07005818 ALOGV("checkInputsForDevice(): adding input %d", input);
5819 }
5820 } // end scan profiles
5821
5822 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005823 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005824 return BAD_VALUE;
5825 }
5826 } else {
5827 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005828 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005829 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005830 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005831 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005832 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005833 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005834 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005835 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5836 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005837 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005838 }
5839 }
5840 }
5841 } // end disconnect
5842
5843 return NO_ERROR;
5844}
5845
5846
Eric Laurente0720872014-03-11 09:30:41 -07005847void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005848{
5849 ALOGV("closeOutput(%d)", output);
5850
François Gaffie1c878552018-11-22 16:53:21 +01005851 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5852 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005853 ALOGW("closeOutput() unknown output %d", output);
5854 return;
5855 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005856 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005857 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005858
Eric Laurente552edb2014-03-10 17:42:56 -07005859 // look for duplicated outputs connected to the output being removed.
5860 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005861 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5862 if (dupOutput->isDuplicated() &&
5863 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5864 sp<SwAudioOutputDescriptor> remainingOutput =
5865 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005866 // As all active tracks on duplicated output will be deleted,
5867 // and as they were also referenced on the other output, the reference
5868 // count for their stream type must be adjusted accordingly on
5869 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005870 const bool wasActive = remainingOutput->isActive();
5871 // Note: no-op on the closing output where all clients has already been set inactive
5872 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005873 // stop() will be a no op if the output is still active but is needed in case all
5874 // active streams refcounts where cleared above
5875 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005876 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005877 }
Eric Laurente552edb2014-03-10 17:42:56 -07005878 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5879 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5880
5881 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005882 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005883 }
5884 }
5885
Eric Laurent05b90f82014-08-27 15:32:29 -07005886 nextAudioPortGeneration();
5887
François Gaffie1c878552018-11-22 16:53:21 +01005888 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005889 if (index >= 0) {
5890 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005891 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5892 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005893 mAudioPatches.removeItemsAt(index);
5894 mpClientInterface->onAudioPatchListUpdate();
5895 }
5896
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005897 if (closingOutputWasActive) {
5898 closingOutput->stop();
5899 }
François Gaffie1c878552018-11-22 16:53:21 +01005900 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005901
François Gaffie53615e22015-03-19 09:24:12 +01005902 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005903 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005904 if (closingOutput == mSpatializerOutput) {
5905 mSpatializerOutput.clear();
5906 }
Dean Wheatley3023b382018-08-09 07:42:40 +10005907
5908 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5909 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005910 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005911 bool directOutputOpen = false;
5912 for (size_t i = 0; i < mOutputs.size(); i++) {
5913 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5914 directOutputOpen = true;
5915 break;
5916 }
5917 }
5918 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005919 ALOGV("no direct outputs open, reset MSD patches");
5920 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5921 // how output devices for patching are resolved. Avoid by caching and reusing the
5922 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5923 // devices to patch to. This may be complicated by the fact that devices may become
5924 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005925 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005926 }
5927 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005928}
5929
5930void AudioPolicyManager::closeInput(audio_io_handle_t input)
5931{
5932 ALOGV("closeInput(%d)", input);
5933
5934 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5935 if (inputDesc == NULL) {
5936 ALOGW("closeInput() unknown input %d", input);
5937 return;
5938 }
5939
Eric Laurent6a94d692014-05-20 11:18:06 -07005940 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005941
François Gaffie11d30102018-11-02 16:09:09 +01005942 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005943 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005944 if (index >= 0) {
5945 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005946 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5947 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005948 mAudioPatches.removeItemsAt(index);
5949 mpClientInterface->onAudioPatchListUpdate();
5950 }
5951
Eric Laurentfe231122017-11-17 17:48:06 -08005952 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005953 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005954
François Gaffie11d30102018-11-02 16:09:09 +01005955 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5956 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005957 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005958 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005959 }
Eric Laurente552edb2014-03-10 17:42:56 -07005960}
5961
François Gaffie11d30102018-11-02 16:09:09 +01005962SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5963 const DeviceVector &devices,
5964 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005965{
5966 SortedVector<audio_io_handle_t> outputs;
5967
François Gaffie11d30102018-11-02 16:09:09 +01005968 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005969 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005970 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005971 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005972 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005973 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005974 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005975 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005976 outputs.add(openOutputs.keyAt(i));
5977 }
5978 }
5979 return outputs;
5980}
5981
Mikhail Naganov37977152018-07-11 15:54:44 -07005982void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5983{
5984 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5985 // output is suspended before any tracks are moved to it
5986 checkA2dpSuspend();
5987 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005988 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005989 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005990 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005991 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005992 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5993 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5994 // configuration changes will ultimately be rerouted correctly. We can still avoid
5995 // unnecessary rerouting by caching and reusing the arguments to
5996 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5997 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005998 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005999 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006000 // an event that changed routing likely occurred, inform upper layers
6001 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006002}
6003
François Gaffiec005e562018-11-06 15:04:49 +01006004bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6005 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006006{
François Gaffiec005e562018-11-06 15:04:49 +01006007 return mEngine->getProductStrategyForAttributes(lAttr) ==
6008 mEngine->getProductStrategyForAttributes(rAttr);
6009}
6010
Francois Gaffieff1eb522020-05-06 18:37:04 +02006011void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6012{
6013 for (size_t i = 0; i < mAudioSources.size(); i++) {
6014 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6015 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006016 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
6017 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006018 connectAudioSource(sourceDesc);
6019 }
6020 }
6021}
6022
6023void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6024{
6025 for (size_t i = 0; i < mAudioSources.size(); i++) {
6026 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6027 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6028 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6029 disconnectAudioSource(sourceDesc);
6030 }
6031 }
6032}
6033
François Gaffiec005e562018-11-06 15:04:49 +01006034void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6035{
6036 auto psId = mEngine->getProductStrategyForAttributes(attr);
6037
6038 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6039 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006040
François Gaffie11d30102018-11-02 16:09:09 +01006041 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6042 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006043
Eric Laurentc209fe42020-06-05 18:11:23 -07006044 uint32_t maxLatency = 0;
6045 bool invalidate = false;
6046 // take into account dynamic audio policies related changes: if a client is now associated
6047 // to a different policy mix than at creation time, invalidate corresponding stream
6048 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6049 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6050 if (desc->isDuplicated()) {
6051 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006052 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006053 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6054 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6055 continue;
6056 }
6057 sp<AudioPolicyMix> primaryMix;
6058 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6059 client->flags(), primaryMix, nullptr);
6060 if (status != OK) {
6061 continue;
6062 }
yucliuf4de36d2020-09-14 14:57:56 -07006063 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006064 invalidate = true;
6065 if (desc->isStrategyActive(psId)) {
6066 maxLatency = desc->latency();
6067 }
6068 break;
6069 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006070 }
6071 }
6072
Eric Laurentc209fe42020-06-05 18:11:23 -07006073 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006074 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6075 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006076 for (audio_io_handle_t srcOut : srcOutputs) {
6077 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006078 if (desc == nullptr) continue;
6079
6080 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006081 maxLatency = desc->latency();
6082 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006083
6084 if (invalidate) continue;
6085
6086 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006087 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006088 // a client on a non direct outputs has necessarily a linear PCM format
6089 // so we can call selectOutput() safely
6090 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6091 client->flags(),
6092 client->config().format,
6093 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006094 client->config().sample_rate,
6095 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006096 if (newOutput != srcOut) {
6097 invalidate = true;
6098 break;
6099 }
6100 } else {
6101 sp<IOProfile> profile = getProfileForOutput(newDevices,
6102 client->config().sample_rate,
6103 client->config().format,
6104 client->config().channel_mask,
6105 client->flags(),
6106 true /* directOnly */);
6107 if (profile != desc->mProfile) {
6108 invalidate = true;
6109 break;
6110 }
6111 }
6112 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006113 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006114
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006115 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006116 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006117 std::to_string(srcOutputs[0]).c_str(),
6118 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006119 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006120 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006121 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006122 if (desc == nullptr) continue;
6123
6124 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006125 setStrategyMute(psId, true, desc);
6126 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006127 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006128 }
François Gaffiec005e562018-11-06 15:04:49 +01006129 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006130 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006131 connectAudioSource(source);
6132 }
Eric Laurente552edb2014-03-10 17:42:56 -07006133 }
6134
François Gaffiec005e562018-11-06 15:04:49 +01006135 // Move effects associated to this stream from previous output to new output
6136 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006137 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006138 }
François Gaffiec005e562018-11-06 15:04:49 +01006139 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006140 if (invalidate) {
6141 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6142 mpClientInterface->invalidateStream(stream);
6143 }
Eric Laurente552edb2014-03-10 17:42:56 -07006144 }
6145 }
6146}
6147
Eric Laurente0720872014-03-11 09:30:41 -07006148void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006149{
François Gaffiec005e562018-11-06 15:04:49 +01006150 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6151 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6152 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006153 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006154 }
Eric Laurente552edb2014-03-10 17:42:56 -07006155}
6156
Kevin Rocard153f92d2018-12-18 18:33:28 -08006157void AudioPolicyManager::checkSecondaryOutputs() {
6158 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006159 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006160 for (size_t i = 0; i < mOutputs.size(); i++) {
6161 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6162 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006163 sp<AudioPolicyMix> primaryMix;
6164 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006165 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006166 client->flags(), primaryMix, &secondaryMixes);
6167 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6168 for (auto &secondaryMix : secondaryMixes) {
6169 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6170 if (outputDesc != nullptr &&
6171 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6172 secondaryDescs.push_back(outputDesc);
6173 }
6174 }
6175
jiabin10a03f12021-05-07 23:46:28 +00006176 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006177 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006178 } else if (!std::equal(
6179 client->getSecondaryOutputs().begin(),
6180 client->getSecondaryOutputs().end(),
6181 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006182 if (!audio_is_linear_pcm(client->config().format)) {
6183 // If the format is not PCM, the tracks should be invalidated to get correct
6184 // behavior when the secondary output is changed.
6185 streamsToInvalidate.insert(client->stream());
6186 } else {
6187 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6188 std::vector<audio_io_handle_t> secondaryOutputIds;
6189 for (const auto &secondaryDesc: secondaryDescs) {
6190 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6191 weakSecondaryDescs.push_back(secondaryDesc);
6192 }
6193 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6194 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006195 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006196 }
6197 }
6198 }
jiabin10a03f12021-05-07 23:46:28 +00006199 if (!trackSecondaryOutputs.empty()) {
6200 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6201 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006202 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006203 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006204 mpClientInterface->invalidateStream(stream);
6205 }
6206}
6207
Eric Laurent2517af32020-11-25 15:31:27 +01006208bool AudioPolicyManager::isScoRequestedForComm() const {
6209 AudioDeviceTypeAddrVector devices;
6210 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6211 for (const auto &device : devices) {
6212 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6213 return true;
6214 }
6215 }
6216 return false;
6217}
6218
Eric Laurente0720872014-03-11 09:30:41 -07006219void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006220{
François Gaffie53615e22015-03-19 09:24:12 +01006221 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006222 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006223 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006224 return;
6225 }
6226
Eric Laurent3a4311c2014-03-17 12:00:47 -07006227 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006228 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6229 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006230 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006231
6232 // if suspended, restore A2DP output if:
6233 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006234 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006235 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006236 //
Eric Laurentf732e072016-08-03 19:30:28 -07006237 // if not suspended, suspend A2DP output if:
6238 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006239 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006240 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006241 //
6242 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006243 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006244 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006245 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006246 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006247
6248 mpClientInterface->restoreOutput(a2dpOutput);
6249 mA2dpSuspended = false;
6250 }
6251 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006252 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006253 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006254 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006255 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006256
6257 mpClientInterface->suspendOutput(a2dpOutput);
6258 mA2dpSuspended = true;
6259 }
6260 }
6261}
6262
François Gaffie11d30102018-11-02 16:09:09 +01006263DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6264 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006265{
François Gaffie11d30102018-11-02 16:09:09 +01006266 DeviceVector devices;
6267
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006268 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006269 if (index >= 0) {
6270 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006271 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006272 ALOGV("%s device %s forced by patch %d", __func__,
6273 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6274 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006275 }
6276 }
6277
Dean Wheatley514b4312020-06-17 21:45:00 +10006278 // Do not retrieve engine device for outputs through MSD
6279 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6280 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6281 return outputDesc->devices();
6282 }
6283
Eric Laurent97ac8712018-07-27 18:59:02 -07006284 // Honor explicit routing requests only if no client using default routing is active on this
6285 // input: a specific app can not force routing for other apps by setting a preferred device.
6286 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006287 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006288 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006289 if (device != nullptr) {
6290 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006291 }
6292
François Gaffiea807ef92018-11-05 10:44:33 +01006293 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6294 // of setForceUse / Default Bus device here
6295 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6296 if (device != nullptr) {
6297 return DeviceVector(device);
6298 }
6299
François Gaffiec005e562018-11-06 15:04:49 +01006300 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6301 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6302 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306303 auto hasStreamActive = [&](auto stream) {
6304 return hasStream(streams, stream) && isStreamActive(stream, 0);
6305 };
Eric Laurent484e9272018-06-07 17:29:23 -07006306
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306307 auto doGetOutputDevicesForVoice = [&]() {
6308 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
6309 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
6310 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006311 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6312 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306313 };
6314
6315 // With low-latency playing on speaker, music on WFD, when the first low-latency
6316 // output is stopped, getNewOutputDevices checks for a product strategy
6317 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006318 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306319 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6320 // stream is associated to the output descriptor.
6321 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6322 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6323 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6324 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006325 // Retrieval of devices for voice DL is done on primary output profile, cannot
6326 // check the route (would force modifying configuration file for this profile)
6327 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6328 break;
6329 }
Eric Laurente552edb2014-03-10 17:42:56 -07006330 }
François Gaffiec005e562018-11-06 15:04:49 +01006331 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006332 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006333}
6334
François Gaffie11d30102018-11-02 16:09:09 +01006335sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6336 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006337{
François Gaffie11d30102018-11-02 16:09:09 +01006338 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006339
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006340 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006341 if (index >= 0) {
6342 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006343 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006344 ALOGV("getNewInputDevice() device %s forced by patch %d",
6345 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6346 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006347 }
6348 }
6349
Eric Laurent97ac8712018-07-27 18:59:02 -07006350 // Honor explicit routing requests only if no client using default routing is active on this
6351 // input: a specific app can not force routing for other apps by setting a preferred device.
6352 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006353 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6354 if (device != nullptr) {
6355 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006356 }
6357
Eric Laurentdc95a252018-04-12 12:46:56 -07006358 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006359 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006360 audio_attributes_t attributes;
6361 uid_t uid;
6362 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6363 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006364 attributes = topClient->attributes();
6365 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006366 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006367 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6368 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006369 }
6370
Francois Gaffie716e1432019-01-14 16:58:59 +01006371 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6372 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006373 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006374 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006375 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006376 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006377
Eric Laurente552edb2014-03-10 17:42:56 -07006378 return device;
6379}
6380
Eric Laurent794fde22016-03-11 09:50:45 -08006381bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6382 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006383 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006384}
6385
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006386DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006387 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006388 // getOutputDevicesForStream's behavior for invalid streams.
6389 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6390 // device for music stream), but we want to return the empty set.
6391 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006392 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006393 }
François Gaffie11d30102018-11-02 16:09:09 +01006394 DeviceVector activeDevices;
6395 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006396 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6397 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006398 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006399 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006400 }
François Gaffiec005e562018-11-06 15:04:49 +01006401 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006402 devices.merge(curDevices);
6403 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006404 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07006405 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01006406 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006407 }
6408 }
Eric Laurente552edb2014-03-10 17:42:56 -07006409 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006410
Eric Laurentb0688d62018-08-14 15:49:18 -07006411 // Favor devices selected on active streams if any to report correct device in case of
6412 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006413 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006414 devices = activeDevices;
6415 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006416 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6417 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006418 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006419 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006420 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006421 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006422 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006423 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006424}
6425
Dorin Drimusf2196d82022-01-03 12:11:18 +01006426// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006427status_t AudioPolicyManager::getDevicesForAttributes(
6428 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6429 if (devices == nullptr) {
6430 return BAD_VALUE;
6431 }
6432 // check dynamic policies but only for primary descriptors (secondary not used for audible
6433 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006434 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006435 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006436 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006437 if (status != OK) {
6438 return status;
6439 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006440 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6441 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6442 devices->push_back(device);
6443 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006444 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006445 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6446 for (const auto& device : curDevices) {
6447 devices->push_back(device->getDeviceTypeAddr());
6448 }
6449 return NO_ERROR;
6450}
6451
Eric Laurente0720872014-03-11 09:30:41 -07006452void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006453 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006454 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006455 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006456 updateDevicesAndOutputs();
6457 break;
6458 default:
6459 break;
6460 }
6461}
6462
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006463uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006464
6465 // skip beacon mute management if a dedicated TTS output is available
6466 if (mTtsOutputAvailable) {
6467 return 0;
6468 }
6469
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006470 switch(event) {
6471 case STARTING_OUTPUT:
6472 mBeaconMuteRefCount++;
6473 break;
6474 case STOPPING_OUTPUT:
6475 if (mBeaconMuteRefCount > 0) {
6476 mBeaconMuteRefCount--;
6477 }
6478 break;
6479 case STARTING_BEACON:
6480 mBeaconPlayingRefCount++;
6481 break;
6482 case STOPPING_BEACON:
6483 if (mBeaconPlayingRefCount > 0) {
6484 mBeaconPlayingRefCount--;
6485 }
6486 break;
6487 }
6488
6489 if (mBeaconMuteRefCount > 0) {
6490 // any playback causes beacon to be muted
6491 return setBeaconMute(true);
6492 } else {
6493 // no other playback: unmute when beacon starts playing, mute when it stops
6494 return setBeaconMute(mBeaconPlayingRefCount == 0);
6495 }
6496}
6497
6498uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6499 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6500 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6501 // keep track of muted state to avoid repeating mute/unmute operations
6502 if (mBeaconMuted != mute) {
6503 // mute/unmute AUDIO_STREAM_TTS on all outputs
6504 ALOGV("\t muting %d", mute);
6505 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006506 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006507 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006508 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006509 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006510 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006511 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006512 maxLatency = latency;
6513 }
6514 }
6515 mBeaconMuted = mute;
6516 return maxLatency;
6517 }
6518 return 0;
6519}
6520
Eric Laurente0720872014-03-11 09:30:41 -07006521void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006522{
François Gaffiec005e562018-11-06 15:04:49 +01006523 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006524 mPreviousOutputs = mOutputs;
6525}
6526
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006527uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006528 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006529 uint32_t delayMs)
6530{
6531 // mute/unmute strategies using an incompatible device combination
6532 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6533 // if unmuting, unmute only after the specified delay
6534 if (outputDesc->isDuplicated()) {
6535 return 0;
6536 }
6537
6538 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006539 DeviceVector devices = outputDesc->devices();
6540 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006541
François Gaffiec005e562018-11-06 15:04:49 +01006542 auto productStrategies = mEngine->getOrderedProductStrategies();
6543 for (const auto &productStrategy : productStrategies) {
6544 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6545 DeviceVector curDevices =
6546 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6547 curDevices = curDevices.filter(outputDesc->supportedDevices());
6548 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006549 bool doMute = false;
6550
François Gaffiec005e562018-11-06 15:04:49 +01006551 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006552 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006553 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6554 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006555 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006556 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006557 }
Eric Laurent99401132014-05-07 19:48:15 -07006558 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006559 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006560 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006561 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006562 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006563 continue;
6564 }
François Gaffiec005e562018-11-06 15:04:49 +01006565 ALOGVV("%s() %s (curDevice %s)", __func__,
6566 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6567 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6568 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006569 if (mute) {
6570 // FIXME: should not need to double latency if volume could be applied
6571 // immediately by the audioflinger mixer. We must account for the delay
6572 // between now and the next time the audioflinger thread for this output
6573 // will process a buffer (which corresponds to one buffer size,
6574 // usually 1/2 or 1/4 of the latency).
6575 if (muteWaitMs < desc->latency() * 2) {
6576 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006577 }
6578 }
6579 }
6580 }
6581 }
6582 }
6583
Eric Laurent99401132014-05-07 19:48:15 -07006584 // temporary mute output if device selection changes to avoid volume bursts due to
6585 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006586 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006587 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006588
Eric Laurentdc462862016-07-19 12:29:53 -07006589 if (muteWaitMs < tempMuteWaitMs) {
6590 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006591 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006592
6593 // If recommended duration is defined, replace temporary mute duration to avoid
6594 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6595 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6596 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6597 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6598 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6599
François Gaffieaaac0fd2018-11-22 17:56:39 +01006600 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6601 // make sure that we do not start the temporary mute period too early in case of
6602 // delayed device change
6603 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6604 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006605 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006606 }
6607 }
6608
Eric Laurente552edb2014-03-10 17:42:56 -07006609 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6610 if (muteWaitMs > delayMs) {
6611 muteWaitMs -= delayMs;
6612 usleep(muteWaitMs * 1000);
6613 return muteWaitMs;
6614 }
6615 return 0;
6616}
6617
François Gaffie11d30102018-11-02 16:09:09 +01006618uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6619 const DeviceVector &devices,
6620 bool force,
6621 int delayMs,
6622 audio_patch_handle_t *patchHandle,
6623 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006624{
François Gaffie11d30102018-11-02 16:09:09 +01006625 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006626 uint32_t muteWaitMs;
6627
6628 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006629 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6630 nullptr /* patchHandle */, requiresMuteCheck);
6631 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6632 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006633 return muteWaitMs;
6634 }
Eric Laurente552edb2014-03-10 17:42:56 -07006635
6636 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006637 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006638 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006639
François Gaffie11d30102018-11-02 16:09:09 +01006640 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6641
6642 if (!filteredDevices.isEmpty()) {
6643 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006644 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006645
6646 // if the outputs are not materially active, there is no need to mute.
6647 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006648 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006649 } else {
6650 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6651 muteWaitMs = 0;
6652 }
Eric Laurente552edb2014-03-10 17:42:56 -07006653
Eric Laurent79ea9582020-06-11 18:49:24 -07006654 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6655 // output profile or if new device is not supported AND previous device(s) is(are) still
6656 // available (otherwise reset device must be done on the output)
6657 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6658 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6659 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6660 // restore previous device after evaluating strategy mute state
6661 outputDesc->setDevices(prevDevices);
6662 return muteWaitMs;
6663 }
6664
Eric Laurente552edb2014-03-10 17:42:56 -07006665 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006666 // the requested device is AUDIO_DEVICE_NONE
6667 // OR the requested device is the same as current device
6668 // AND force is not specified
6669 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006670 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006671 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006672 !force && outputDesc->getPatchHandle() != 0) {
6673 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6674 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006675 return muteWaitMs;
6676 }
6677
François Gaffie11d30102018-11-02 16:09:09 +01006678 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006679
Eric Laurente552edb2014-03-10 17:42:56 -07006680 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006681 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006682 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006683 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006684 PatchBuilder patchBuilder;
6685 patchBuilder.addSource(outputDesc);
6686 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6687 for (const auto &filteredDevice : filteredDevices) {
6688 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006689 }
6690
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006691 // Add half reported latency to delayMs when muteWaitMs is null in order
6692 // to avoid disordered sequence of muting volume and changing devices.
6693 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6694 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006695 }
Eric Laurente552edb2014-03-10 17:42:56 -07006696
6697 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006698 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006699
6700 return muteWaitMs;
6701}
6702
Eric Laurentc75307b2015-03-17 15:29:32 -07006703status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006704 int delayMs,
6705 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006706{
Eric Laurent6a94d692014-05-20 11:18:06 -07006707 ssize_t index;
6708 if (patchHandle) {
6709 index = mAudioPatches.indexOfKey(*patchHandle);
6710 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006711 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006712 }
6713 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006714 return INVALID_OPERATION;
6715 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006716 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006717 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006718 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006719 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006720 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006721 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006722 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006723 return status;
6724}
6725
6726status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006727 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006728 bool force,
6729 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006730{
6731 status_t status = NO_ERROR;
6732
Eric Laurent1f2f2232014-06-02 12:01:23 -07006733 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006734 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6735 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006736
François Gaffie11d30102018-11-02 16:09:09 +01006737 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006738 PatchBuilder patchBuilder;
6739 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006740 // AUDIO_SOURCE_HOTWORD is for internal use only:
6741 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006742 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6743 auto result = usecase;
6744 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6745 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6746 }
6747 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006748 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006749 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006750 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006751 }
6752 }
6753 return status;
6754}
6755
Eric Laurent6a94d692014-05-20 11:18:06 -07006756status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6757 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006758{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006759 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006760 ssize_t index;
6761 if (patchHandle) {
6762 index = mAudioPatches.indexOfKey(*patchHandle);
6763 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006764 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006765 }
6766 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006767 return INVALID_OPERATION;
6768 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006769 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006770 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006771 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006772 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006773 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006774 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006775 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006776 return status;
6777}
6778
François Gaffie11d30102018-11-02 16:09:09 +01006779sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006780 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006781 audio_format_t& format,
6782 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006783 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006784{
6785 // Choose an input profile based on the requested capture parameters: select the first available
6786 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006787 //
6788 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6789 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006790
Glenn Kasten730b9262018-03-29 15:01:26 -07006791 sp<IOProfile> firstInexact;
6792 uint32_t updatedSamplingRate = 0;
6793 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6794 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006795 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006796 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006797 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006798 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006799 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006800 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006801 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006802 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006803 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006804 &channelMask /*updatedChannelMask*/,
6805 // FIXME ugly cast
6806 (audio_output_flags_t) flags,
6807 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006808 return profile;
6809 }
François Gaffie11d30102018-11-02 16:09:09 +01006810 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006811 samplingRate,
6812 &updatedSamplingRate,
6813 format,
6814 &updatedFormat,
6815 channelMask,
6816 &updatedChannelMask,
6817 // FIXME ugly cast
6818 (audio_output_flags_t) flags,
6819 false /*exactMatchRequiredForInputFlags*/)) {
6820 firstInexact = profile;
6821 }
6822
Eric Laurente552edb2014-03-10 17:42:56 -07006823 }
6824 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006825 if (firstInexact != nullptr) {
6826 samplingRate = updatedSamplingRate;
6827 format = updatedFormat;
6828 channelMask = updatedChannelMask;
6829 return firstInexact;
6830 }
Eric Laurente552edb2014-03-10 17:42:56 -07006831 return NULL;
6832}
6833
François Gaffieaaac0fd2018-11-22 17:56:39 +01006834float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6835 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006836 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006837 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006838{
jiabin9a3361e2019-10-01 09:38:30 -07006839 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006840
6841 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6842 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6843 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6844 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006845 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6846 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6847 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6848 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006849 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006850
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006851 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006852 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6853 mOutputs.isActive(ringVolumeSrc, 0)) {
6854 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006855 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006856 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006857 }
6858
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006859 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006860 if ((volumeSource != callVolumeSrc && (isInCall() ||
6861 mOutputs.isActiveLocally(callVolumeSrc))) &&
6862 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6863 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6864 volumeSource == alarmVolumeSrc ||
6865 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6866 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6867 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006868 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006869 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006870 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006871 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006872 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006873 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006874 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6875 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6876 // programmatically muted.
6877 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6878 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6879 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006880 bool exemptFromCapping =
6881 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6882 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006883 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6884 volumeSource, volumeDb);
6885 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006886 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6887 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6888 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006889 }
6890 }
Eric Laurente552edb2014-03-10 17:42:56 -07006891 // if a headset is connected, apply the following rules to ring tones and notifications
6892 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006893 // - always attenuate notifications volume by 6dB
6894 // - attenuate ring tones volume by 6dB unless music is not playing and
6895 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006896 // - if music is playing, always limit the volume to current music volume,
6897 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006898 if (!Intersection(deviceTypes,
6899 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6900 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006901 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6902 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006903 ((volumeSource == alarmVolumeSrc ||
6904 volumeSource == ringVolumeSrc) ||
6905 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6906 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6907 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6908 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6909 curves.canBeMuted()) {
6910
Eric Laurente552edb2014-03-10 17:42:56 -07006911 // when the phone is ringing we must consider that music could have been paused just before
6912 // by the music application and behave as if music was active if the last music track was
6913 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006914 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006915 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006916 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006917 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006918 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6919 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006920 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006921 float musicVolDb = computeVolume(musicCurves,
6922 musicVolumeSrc,
6923 musicCurves.getVolumeIndex(musicDevice),
6924 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006925 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6926 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6927 if (volumeDb > minVolDb) {
6928 volumeDb = minVolDb;
6929 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006930 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006931 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6932 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6933 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006934 // on A2DP, also ensure notification volume is not too low compared to media when
6935 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006936 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006937 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006938 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6939 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006940 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6941 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006942 }
6943 }
jiabin9a3361e2019-10-01 09:38:30 -07006944 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006945 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006946 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006947 }
6948 }
6949
François Gaffie43c73442018-11-08 08:21:55 +01006950 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006951}
6952
Eric Laurent3839bc02018-07-10 18:33:34 -07006953int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006954 VolumeSource fromVolumeSource,
6955 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006956{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006957 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006958 return srcIndex;
6959 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006960 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6961 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006962 float minSrc = (float)srcCurves.getVolumeIndexMin();
6963 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6964 float minDst = (float)dstCurves.getVolumeIndexMin();
6965 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006966
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006967 // preserve mute request or correct range
6968 if (srcIndex < minSrc) {
6969 if (srcIndex == 0) {
6970 return 0;
6971 }
6972 srcIndex = minSrc;
6973 } else if (srcIndex > maxSrc) {
6974 srcIndex = maxSrc;
6975 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006976 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6977}
6978
François Gaffieaaac0fd2018-11-22 17:56:39 +01006979status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6980 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006981 int index,
6982 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006983 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006984 int delayMs,
6985 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006986{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006987 // do not change actual attributes volume if the attributes is muted
6988 if (outputDesc->isMuted(volumeSource)) {
6989 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6990 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006991 return NO_ERROR;
6992 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006993 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6994 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6995 bool isVoiceVolSrc = callVolSrc == volumeSource;
6996 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6997
Eric Laurent2517af32020-11-25 15:31:27 +01006998 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006999 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007000 // if sco and call follow same curves, bypass forceUseForComm
7001 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007002 ((isVoiceVolSrc && isScoRequested) ||
7003 (isBtScoVolSrc && !isScoRequested))) {
7004 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7005 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007006 // Do not return an error here as AudioService will always set both voice call
7007 // and bluetooth SCO volumes due to stream aliasing.
7008 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007009 }
jiabin9a3361e2019-10-01 09:38:30 -07007010 if (deviceTypes.empty()) {
7011 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007012 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007013
jiabin9a3361e2019-10-01 09:38:30 -07007014 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7015 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007016 // Force VoIP volume to max for bluetooth SCO device except if muted
7017 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007018 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007019 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007020 }
jiabin9a3361e2019-10-01 09:38:30 -07007021 outputDesc->setVolume(
7022 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007023
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007024 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007025 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007026 // 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 +01007027 if (isVoiceVolSrc) {
7028 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007029 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007030 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007031 }
Eric Laurent18fba842016-03-31 14:41:26 -07007032 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007033 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7034 mLastVoiceVolume = voiceVolume;
7035 }
7036 }
Eric Laurente552edb2014-03-10 17:42:56 -07007037 return NO_ERROR;
7038}
7039
Eric Laurentc75307b2015-03-17 15:29:32 -07007040void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007041 const DeviceTypeSet& deviceTypes,
7042 int delayMs,
7043 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007044{
jiabincd510522020-01-22 09:40:55 -08007045 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007046 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7047 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7048 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007049 curves.getVolumeIndex(deviceTypes),
7050 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007051 }
7052}
7053
François Gaffiec005e562018-11-06 15:04:49 +01007054void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7055 bool on,
7056 const sp<AudioOutputDescriptor>& outputDesc,
7057 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007058 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007059{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007060 std::vector<VolumeSource> sourcesToMute;
7061 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7062 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7063 toString(attributes).c_str(), on, outputDesc->getId());
7064 VolumeSource source = toVolumeSource(attributes);
7065 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
7066 sourcesToMute.push_back(source);
7067 }
Eric Laurente552edb2014-03-10 17:42:56 -07007068 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007069 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007070 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007071 }
7072
Eric Laurente552edb2014-03-10 17:42:56 -07007073}
7074
François Gaffieaaac0fd2018-11-22 17:56:39 +01007075void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7076 bool on,
7077 const sp<AudioOutputDescriptor>& outputDesc,
7078 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007079 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007080{
jiabin9a3361e2019-10-01 09:38:30 -07007081 if (deviceTypes.empty()) {
7082 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007083 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007084 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007085 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007086 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007087 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007088 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
7089 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7090 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007091 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007092 }
7093 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007094 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7095 // ignored
7096 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007097 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007098 if (!outputDesc->isMuted(volumeSource)) {
7099 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007100 return;
7101 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007102 if (outputDesc->decMuteCount(volumeSource) == 0) {
7103 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007104 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007105 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007106 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007107 delayMs);
7108 }
7109 }
7110}
7111
François Gaffie53615e22015-03-19 09:24:12 +01007112bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7113{
François Gaffiec005e562018-11-06 15:04:49 +01007114 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007115 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7116 return true;
7117 }
7118
7119 // has known usage?
7120 switch (paa->usage) {
7121 case AUDIO_USAGE_UNKNOWN:
7122 case AUDIO_USAGE_MEDIA:
7123 case AUDIO_USAGE_VOICE_COMMUNICATION:
7124 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7125 case AUDIO_USAGE_ALARM:
7126 case AUDIO_USAGE_NOTIFICATION:
7127 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7128 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7129 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7130 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7131 case AUDIO_USAGE_NOTIFICATION_EVENT:
7132 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7133 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7134 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7135 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007136 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007137 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007138 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007139 case AUDIO_USAGE_EMERGENCY:
7140 case AUDIO_USAGE_SAFETY:
7141 case AUDIO_USAGE_VEHICLE_STATUS:
7142 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007143 break;
7144 default:
7145 return false;
7146 }
7147 return true;
7148}
7149
François Gaffie2110e042015-03-24 08:41:51 +01007150audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7151{
7152 return mEngine->getForceUse(usage);
7153}
7154
7155bool AudioPolicyManager::isInCall()
7156{
7157 return isStateInCall(mEngine->getPhoneState());
7158}
7159
7160bool AudioPolicyManager::isStateInCall(int state)
7161{
7162 return is_state_in_call(state);
7163}
7164
Eric Laurent74b71512019-11-06 17:21:57 -08007165bool AudioPolicyManager::isCallAudioAccessible()
7166{
7167 audio_mode_t mode = mEngine->getPhoneState();
7168 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007169 || (mode == AUDIO_MODE_CALL_SCREEN)
7170 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007171}
7172
Eric Laurentd60560a2015-04-10 11:31:20 -07007173void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7174{
7175 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007176 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007177 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007178 sourceDesc->sinkDevice()->equals(deviceDesc))
7179 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007180 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007181 }
7182 }
7183
7184 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7185 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7186 bool release = false;
7187 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7188 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7189 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7190 source->ext.device.type == deviceDesc->type()) {
7191 release = true;
7192 }
7193 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007194 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007195 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7196 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7197 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007198 sink->ext.device.type == deviceDesc->type() &&
7199 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7200 || strncmp(sink->ext.device.address, address,
7201 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007202 release = true;
7203 }
7204 }
7205 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007206 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7207 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007208 }
7209 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007210
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007211 mInputs.clearSessionRoutesForDevice(deviceDesc);
7212
Francois Gaffie716e1432019-01-14 16:58:59 +01007213 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007214}
7215
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007216void AudioPolicyManager::modifySurroundFormats(
7217 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007218 std::unordered_set<audio_format_t> enforcedSurround(
7219 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007220 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7221 for (const auto& pair : mConfig.getSurroundFormats()) {
7222 allSurround.insert(pair.first);
7223 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7224 }
Phil Burk09bc4612016-02-24 15:58:15 -08007225
7226 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7227 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007228 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007229 // This is the resulting set of formats depending on the surround mode:
7230 // 'all surround' = allSurround
7231 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7232 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7233 // 'manual surround' = mManualSurroundFormats
7234 // AUTO: formats v 'enforced surround'
7235 // ALWAYS: formats v 'all surround' v 'enforced surround'
7236 // NEVER: formats ^ 'non-surround'
7237 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007238
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007239 std::unordered_set<audio_format_t> formatSet;
7240 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7241 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007242 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007243 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007244 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007245 formatSet.insert(*formatIter);
7246 }
7247 }
7248 } else {
7249 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7250 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007251 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007252
jiabin81772902018-04-02 17:52:27 -07007253 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007254 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007255 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7256 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7257 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007258 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007259 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7260 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7261 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007262 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007263 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007264 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007265 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007266 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007267 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007268}
7269
jiabin06e4bab2019-07-29 10:13:34 -07007270void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7271 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007272 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7273 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7274
7275 // If NEVER, then remove support for channelMasks > stereo.
7276 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007277 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7278 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007279 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007280 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007281 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007282 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007283 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007284 }
7285 }
jiabin81772902018-04-02 17:52:27 -07007286 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7287 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7288 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007289 bool supports5dot1 = false;
7290 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007291 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007292 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7293 supports5dot1 = true;
7294 break;
7295 }
7296 }
7297 // If not then add 5.1 support.
7298 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007299 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007300 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007301 }
Phil Burk09bc4612016-02-24 15:58:15 -08007302 }
7303}
7304
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007305void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007306 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007307 AudioProfileVector &profiles)
7308{
7309 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007310 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007311
François Gaffie112b0af2015-11-19 16:13:25 +01007312 // Format MUST be checked first to update the list of AudioProfile
7313 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007314 reply = mpClientInterface->getParameters(
7315 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007316 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007317 AudioParameter repliedParameters(reply);
7318 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007319 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007320 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7321 return;
7322 }
Phil Burk09bc4612016-02-24 15:58:15 -08007323 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007324 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007325 if (device == AUDIO_DEVICE_OUT_HDMI
7326 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007327 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007328 }
jiabin3e277cc2019-09-10 14:27:34 -07007329 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007330 }
François Gaffie112b0af2015-11-19 16:13:25 +01007331
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007332 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007333 ChannelMaskSet channelMasks;
7334 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007335 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007336 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007337
7338 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007339 reply = mpClientInterface->getParameters(
7340 ioHandle,
7341 requestedParameters.toString() + ";" +
7342 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007343 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007344 AudioParameter repliedParameters(reply);
7345 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007346 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007347 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007348 }
7349 }
7350 if (profiles.hasDynamicChannelsFor(format)) {
7351 reply = mpClientInterface->getParameters(ioHandle,
7352 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007353 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007354 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007355 AudioParameter repliedParameters(reply);
7356 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007357 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007358 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007359 if (device == AUDIO_DEVICE_OUT_HDMI
7360 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007361 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007362 }
François Gaffie112b0af2015-11-19 16:13:25 +01007363 }
7364 }
jiabin3e277cc2019-09-10 14:27:34 -07007365 addDynamicAudioProfileAndSort(
7366 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007367 }
7368}
Eric Laurentd60560a2015-04-10 11:31:20 -07007369
Mikhail Naganovdc769682018-05-04 15:34:08 -07007370status_t AudioPolicyManager::installPatch(const char *caller,
7371 audio_patch_handle_t *patchHandle,
7372 AudioIODescriptorInterface *ioDescriptor,
7373 const struct audio_patch *patch,
7374 int delayMs)
7375{
7376 ssize_t index = mAudioPatches.indexOfKey(
7377 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7378 *patchHandle : ioDescriptor->getPatchHandle());
7379 sp<AudioPatch> patchDesc;
7380 status_t status = installPatch(
7381 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7382 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007383 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007384 }
7385 return status;
7386}
7387
7388status_t AudioPolicyManager::installPatch(const char *caller,
7389 ssize_t index,
7390 audio_patch_handle_t *patchHandle,
7391 const struct audio_patch *patch,
7392 int delayMs,
7393 uid_t uid,
7394 sp<AudioPatch> *patchDescPtr)
7395{
7396 sp<AudioPatch> patchDesc;
7397 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7398 if (index >= 0) {
7399 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007400 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007401 }
7402
7403 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7404 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7405 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7406 if (status == NO_ERROR) {
7407 if (index < 0) {
7408 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007409 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007410 } else {
7411 patchDesc->mPatch = *patch;
7412 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007413 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007414 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007415 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007416 }
7417 nextAudioPortGeneration();
7418 mpClientInterface->onAudioPatchListUpdate();
7419 }
7420 if (patchDescPtr) *patchDescPtr = patchDesc;
7421 return status;
7422}
7423
jiabinbce0c1d2020-10-05 11:20:18 -07007424bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7425{
7426 const TrackClientVector activeClients = output->getActiveClients();
7427 if (activeClients.empty()) {
7428 return true;
7429 }
7430 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7431 if (index < 0) {
7432 ALOGE("%s, no audio patch found while there are active clients on output %d",
7433 __func__, output->getId());
7434 return false;
7435 }
7436 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7437 DeviceVector routedDevices;
7438 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7439 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7440 patchDesc->mPatch.sinks[i].id);
7441 if (device == nullptr) {
7442 ALOGE("%s, no audio device found with id(%d)",
7443 __func__, patchDesc->mPatch.sinks[i].id);
7444 return false;
7445 }
7446 routedDevices.add(device);
7447 }
7448 for (const auto& client : activeClients) {
7449 // TODO: b/175343099 only travel the valid client
7450 sp<DeviceDescriptor> preferredDevice =
7451 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7452 if (mEngine->getOutputDevicesForAttributes(
7453 client->attributes(), preferredDevice, false) == routedDevices) {
7454 return false;
7455 }
7456 }
7457 return true;
7458}
7459
7460sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007461 const sp<IOProfile>& profile, const DeviceVector& devices,
7462 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007463{
7464 for (const auto& device : devices) {
7465 // TODO: This should be checking if the profile supports the device combo.
7466 if (!profile->supportsDevice(device)) {
7467 return nullptr;
7468 }
7469 }
7470 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7471 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007472 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007473 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7474 if (status != NO_ERROR) {
7475 return nullptr;
7476 }
7477
7478 // Here is where the out_set_parameters() for card & device gets called
7479 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7480 const audio_devices_t deviceType = device->type();
7481 const String8 &address = String8(device->address().c_str());
7482 if (!address.isEmpty()) {
7483 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7484 mpClientInterface->setParameters(output, String8(param));
7485 free(param);
7486 }
7487 updateAudioProfiles(device, output, profile->getAudioProfiles());
7488 if (!profile->hasValidAudioProfile()) {
7489 ALOGW("%s() missing param", __func__);
7490 desc->close();
7491 return nullptr;
7492 } else if (profile->hasDynamicAudioProfile()) {
7493 desc->close();
7494 output = AUDIO_IO_HANDLE_NONE;
7495 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7496 profile->pickAudioProfile(
7497 config.sample_rate, config.channel_mask, config.format);
7498 config.offload_info.sample_rate = config.sample_rate;
7499 config.offload_info.channel_mask = config.channel_mask;
7500 config.offload_info.format = config.format;
7501
Eric Laurentb4f42a92022-01-17 17:37:31 +01007502 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007503 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7504 if (status != NO_ERROR) {
7505 return nullptr;
7506 }
7507 }
7508
7509 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007510
jiabinbce0c1d2020-10-05 11:20:18 -07007511 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7512 sp<AudioPolicyMix> policyMix;
7513 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7514 policyMix->setOutput(desc);
7515 desc->mPolicyMix = policyMix;
7516 } else {
7517 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7518 address.string());
7519 }
7520
Eric Laurentb4f42a92022-01-17 17:37:31 +01007521 } else if (hasPrimaryOutput() && profile->getModule()
7522 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7523 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7524 // no duplicated output for:
7525 // - direct outputs
7526 // - outputs used by dynamic policy mixes
7527 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007528 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7529
7530 //TODO: configure audio effect output stage here
7531
7532 // open a duplicating output thread for the new output and the primary output
7533 sp<SwAudioOutputDescriptor> dupOutputDesc =
7534 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7535 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7536 if (status == NO_ERROR) {
7537 // add duplicated output descriptor
7538 addOutput(duplicatedOutput, dupOutputDesc);
7539 } else {
7540 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7541 mPrimaryOutput->mIoHandle, output);
7542 desc->close();
7543 removeOutput(output);
7544 nextAudioPortGeneration();
7545 return nullptr;
7546 }
7547 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007548 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7549 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7550 mPrimaryOutput = desc;
7551 }
jiabinbce0c1d2020-10-05 11:20:18 -07007552 return desc;
7553}
7554
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007555} // namespace android