blob: 6f87bf048e9a524c889bad4cb349f80d5360a6cb [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>
Glenn Kasten76a13442020-07-01 12:10:59 -070041#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070042#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070043#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070044#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070045#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070046#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070047#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070048#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <utils/Log.h>
50
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurent3b73df72014-03-11 09:06:29 -070054namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070055
Svet Ganov3e5f14f2021-05-13 22:51:08 +000056using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070057
Eric Laurentdc462862016-07-19 12:29:53 -070058//FIXME: workaround for truncated touch sounds
59// to be removed when the problem is handled by system UI
60#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070061
62// Largest difference in dB on earpiece in call between the voice volume and another
63// media / notification / system volume.
64constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
65
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110067static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
68 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110069 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
70// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110071static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110072 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
73 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
74 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
75
jiabin06e4bab2019-07-29 10:13:34 -070076template <typename T>
77bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
78{
79 if (left.size() != right.size()) {
80 return false;
81 }
82 for (size_t index = 0; index < right.size(); index++) {
83 if (left[index] != right[index]) {
84 return false;
85 }
86 }
87 return true;
88}
89
90template <typename T>
91bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
92{
93 return !(left == right);
94}
95
Eric Laurente552edb2014-03-10 17:42:56 -070096// ----------------------------------------------------------------------------
97// AudioPolicyInterface implementation
98// ----------------------------------------------------------------------------
99
Eric Laurente0720872014-03-11 09:30:41 -0700100status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800101 audio_policy_dev_state_t state,
102 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800103 const char *device_name,
104 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700105{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 status_t status = setDeviceConnectionStateInt(device, state, device_address,
107 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
François Gaffie11d30102018-11-02 16:09:09 +0100112void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
113 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200114{
jiabince9f20e2019-09-12 16:29:15 -0700115 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200116 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700117 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100118 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200119 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
120}
121
François Gaffie11d30102018-11-02 16:09:09 +0100122status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800123 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800124 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800125 const char *device_name,
126 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800127{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800128 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
129 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700130
131 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100132 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700133
François Gaffie11d30102018-11-02 16:09:09 +0100134 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800135 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100136 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700137 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
138}
Paul McLeane743a472015-01-28 11:07:31 -0800139
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700140status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
141 audio_policy_dev_state_t state)
142{
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700144 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700145 SortedVector <audio_io_handle_t> outputs;
146
François Gaffie11d30102018-11-02 16:09:09 +0100147 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700148
Eric Laurente552edb2014-03-10 17:42:56 -0700149 // save a copy of the opened output descriptors before any output is opened or closed
150 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
151 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700152 switch (state)
153 {
154 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800155 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100157 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700158 return INVALID_OPERATION;
159 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800160 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700161 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700162
Eric Laurente552edb2014-03-10 17:42:56 -0700163 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200164 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700165 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700166 }
167
François Gaffie44481e72016-04-20 07:49:57 +0200168 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
169 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100170 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200171
François Gaffie11d30102018-11-02 16:09:09 +0100172 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
173 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200174
Francois Gaffie716e1432019-01-14 16:58:59 +0100175 mHwModules.cleanUpForDevice(device);
176
François Gaffie11d30102018-11-02 16:09:09 +0100177 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700178 return INVALID_OPERATION;
179 }
François Gaffie2110e042015-03-24 08:41:51 +0100180
jiabin1c4794b2020-05-05 10:08:05 -0700181 // Populate encapsulation information when a output device is connected.
182 device->setEncapsulationInfoFromHal(mpClientInterface);
183
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700184 // outputs should never be empty here
185 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
186 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100187 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188
Eric Laurent3ae5f312015-02-03 17:12:08 -0800189 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700191 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100193 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700194 return INVALID_OPERATION;
195 }
196
François Gaffie11d30102018-11-02 16:09:09 +0100197 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700198
Paul McLeane743a472015-01-28 11:07:31 -0800199 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100200 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100203 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700204
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100205 mOutputs.clearSessionRoutesForDevice(device);
206
François Gaffie11d30102018-11-02 16:09:09 +0100207 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100208
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800209 // Reset active device codec
210 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
211
Kriti Dangef6be8f2020-11-05 11:58:19 +0100212 // remove device from mReportedFormatsMap cache
213 mReportedFormatsMap.erase(device);
214
Eric Laurente552edb2014-03-10 17:42:56 -0700215 } break;
216
217 default:
François Gaffie11d30102018-11-02 16:09:09 +0100218 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700219 return BAD_VALUE;
220 }
221
Eric Laurent736a1022019-03-27 18:28:46 -0700222 // Propagate device availability to Engine
223 setEngineDeviceConnectionState(device, state);
224
Eric Laurentae970022019-01-29 14:25:04 -0800225 // No need to evaluate playback routing when connecting a remote submix
226 // output device used by a dynamic policy of type recorder as no
227 // playback use case is affected.
228 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700229 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800230 for (audio_io_handle_t output : outputs) {
231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800232 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
233 if (policyMix != nullptr
234 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700235 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800236 doCheckForDeviceAndOutputChanges = false;
237 break;
238 }
239 }
240 }
241
242 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700243 // outputs must be closed after checkOutputForAllStrategies() is executed
244 if (!outputs.isEmpty()) {
245 for (audio_io_handle_t output : outputs) {
246 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100247 // close unused outputs after device disconnection or direct outputs that have
248 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200249 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
250 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
251 (desc->mDirectOpenCount == 0))
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200252 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
Eric Laurentfa0f6742021-08-17 18:39:44 +0200253 (desc != mSpatializerOutput))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200254 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700255 closeOutput(output);
256 }
Eric Laurente552edb2014-03-10 17:42:56 -0700257 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700258 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
259 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700260 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700261 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800262 };
263
264 if (doCheckForDeviceAndOutputChanges) {
265 checkForDeviceAndOutputChanges(checkCloseOutputs);
266 } else {
267 checkCloseOutputs();
268 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100269 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700270 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100271 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700272 const DeviceVector activeMediaDevices =
273 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700274 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700275 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530276 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
277 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100278 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700279 // do not force device change on duplicated output because if device is 0, it will
280 // also force a device 0 for the two outputs it is duplicated to which may override
281 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100282 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100283 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700284 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700285 // always force when disconnecting (a non-duplicated device)
286 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100287 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700288 }
jiabinbce0c1d2020-10-05 11:20:18 -0700289 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000290 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700291 desc->supportsDevicesForPlayback(activeMediaDevices)) {
292 // Reopen the output to query the dynamic profiles when there is not active
293 // clients or all active clients will be rerouted. Otherwise, set the flag
294 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
295 // can be reopened to query dynamic profiles when all clients are inactive.
296 if (areAllActiveTracksRerouted(desc)) {
297 outputsToReopen.push_back(mOutputs.keyAt(i));
298 } else {
299 desc->mPendingReopenToQueryProfiles = true;
300 }
301 }
302 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
303 // Clear the flag that previously set for re-querying profiles.
304 desc->mPendingReopenToQueryProfiles = false;
305 }
306 }
307 for (const auto& output : outputsToReopen) {
308 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
309 closeOutput(output);
310 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
312
Eric Laurentd60560a2015-04-10 11:31:20 -0700313 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100314 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700315 }
316
Eric Laurent72aa32f2014-05-30 18:51:48 -0700317 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700318 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700319 } // end if is output device
320
Eric Laurente552edb2014-03-10 17:42:56 -0700321 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700322 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100323 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700324 switch (state)
325 {
326 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700327 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100329 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700330 return INVALID_OPERATION;
331 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700332
333 if (mAvailableInputDevices.add(device) < 0) {
334 return NO_MEMORY;
335 }
336
François Gaffie44481e72016-04-20 07:49:57 +0200337 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
338 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100339 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200340
Eric Laurent0dd51852019-04-19 18:18:58 -0700341 if (checkInputsForDevice(device, state) != NO_ERROR) {
342 mAvailableInputDevices.remove(device);
343
François Gaffie11d30102018-11-02 16:09:09 +0100344 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100345
346 mHwModules.cleanUpForDevice(device);
347
Eric Laurentd4692962014-05-05 18:13:44 -0700348 return INVALID_OPERATION;
349 }
350
Eric Laurentd4692962014-05-05 18:13:44 -0700351 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700352
353 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700354 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700355 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100356 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700357 return INVALID_OPERATION;
358 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700359
François Gaffie11d30102018-11-02 16:09:09 +0100360 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700361
362 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100363 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700364
François Gaffie11d30102018-11-02 16:09:09 +0100365 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700366
367 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100368
369 // remove device from mReportedFormatsMap cache
370 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700371 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700372
373 default:
François Gaffie11d30102018-11-02 16:09:09 +0100374 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700375 return BAD_VALUE;
376 }
377
Eric Laurent736a1022019-03-27 18:28:46 -0700378 // Propagate device availability to Engine
379 setEngineDeviceConnectionState(device, state);
380
Eric Laurent0dd51852019-04-19 18:18:58 -0700381 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700382 // As the input device list can impact the output device selection, update
383 // getDeviceForStrategy() cache
384 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700385
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100386 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200387 // Reconnect Audio Source
388 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
389 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
390 checkAudioSourceForAttributes(attributes);
391 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700392 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100393 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700394 }
395
Eric Laurentb52c1522014-05-20 11:27:36 -0700396 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700397 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700399
François Gaffie11d30102018-11-02 16:09:09 +0100400 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700401 return BAD_VALUE;
402}
403
Eric Laurent736a1022019-03-27 18:28:46 -0700404void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
405 audio_policy_dev_state_t state) {
406
407 // the Engine does not have to know about remote submix devices used by dynamic audio policies
408 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
409 return;
410 }
411 mEngine->setDeviceConnectionState(device, state);
412}
413
414
Eric Laurente0720872014-03-11 09:30:41 -0700415audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100416 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700417{
Eric Laurent634b7142016-04-20 13:48:02 -0700418 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800419 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
420 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700421 (strlen(device_address) != 0)/*matchAddress*/);
422
423 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100424 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700425 device, device_address);
426 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
427 }
François Gaffie53615e22015-03-19 09:24:12 +0100428
Eric Laurent3a4311c2014-03-17 12:00:47 -0700429 DeviceVector *deviceVector;
430
Eric Laurente552edb2014-03-10 17:42:56 -0700431 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700432 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700433 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 deviceVector = &mAvailableInputDevices;
435 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100436 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700438 }
Eric Laurent634b7142016-04-20 13:48:02 -0700439
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800440 return (deviceVector->getDevice(
441 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700442 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800443}
444
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800445status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
446 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800447 const char *device_name,
448 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800449{
450 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700451 String8 reply;
452 AudioParameter param;
453 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800454
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800455 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
456 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800457
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800458 // connect/disconnect only 1 device at a time
459 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
460
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800461 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700462 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800463 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800464 // Nothing to do: device is not connected
465 return NO_ERROR;
466 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800467 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800468
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700469 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800470 // configure codecs.
471 // Handle two specific cases by sending a set parameter to
472 // configure A2DP codecs. No need to toggle device state.
473 // Case 1: A2DP active device switches from primary to primary
474 // module
475 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200476 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700477 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800478 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
479 if (availablePrimaryOutputDevices().contains(devDesc) &&
480 (module != 0 && module->getHandle() == primaryHandle)) {
481 reply = mpClientInterface->getParameters(
482 AUDIO_IO_HANDLE_NONE,
483 String8(AudioParameter::keyReconfigA2dpSupported));
484 AudioParameter repliedParameters(reply);
485 repliedParameters.getInt(
486 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
487 if (isReconfigA2dpSupported) {
488 const String8 key(AudioParameter::keyReconfigA2dp);
489 param.add(key, String8("true"));
490 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
491 devDesc->setEncodedFormat(encodedFormat);
492 return NO_ERROR;
493 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700494 }
495 }
cnx421bd2dcc42020-07-11 14:58:44 +0800496 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
497 for (size_t i = 0; i < mOutputs.size(); i++) {
498 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
499 // mute media strategies and delay device switch by the largest
500 // This avoid sending the music tail into the earpiece or headset.
501 setStrategyMute(musicStrategy, true, desc);
502 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
503 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
504 nullptr, true /*fromCache*/).types());
505 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800506 // Toggle the device state: UNAVAILABLE -> AVAILABLE
507 // This will force reading again the device configuration
508 status = setDeviceConnectionState(device,
509 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 device_address, device_name,
511 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512 if (status != NO_ERROR) {
513 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
514 status);
515 return status;
516 }
517
518 status = setDeviceConnectionState(device,
519 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521 if (status != NO_ERROR) {
522 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
523 status);
524 return status;
525 }
526
527 return NO_ERROR;
528}
529
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800530status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
531 std::vector<audio_format_t> *formats)
532{
533 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800534 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800535 std::unordered_set<audio_format_t> formatSet;
536 sp<HwModule> primaryModule =
537 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700538 if (primaryModule == nullptr) {
539 ALOGE("%s() unable to get primary module", __func__);
540 return NO_INIT;
541 }
jiabin9a3361e2019-10-01 09:38:30 -0700542 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
543 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800544 for (const auto& device : declaredDevices) {
545 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800546 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800547 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800548 return status;
549}
550
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100551DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
552{
553 DeviceVector rxSinkdevices{};
554 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
555 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
556 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
557 auto rxSinkDevice = rxSinkdevices.itemAt(0);
558 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
559 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
560 // retrieve Rx Source device descriptor
561 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
562 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
563
564 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
565 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
566 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
567 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
568 return DeviceVector(rxSinkDevice);
569 }
570 }
571 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
572 // the device returned is not necessarily reachable via this output
573 // (filter later by setOutputDevices())
574 return getNewOutputDevices(mPrimaryOutput, fromCache);
575}
576
577status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
578{
579 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
580 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
581 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
582 }
583 return INVALID_OPERATION;
584}
585
586status_t AudioPolicyManager::updateCallRoutingInternal(
587 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700588{
589 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100590 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700591 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700592 if(!hasPrimaryOutput() ||
593 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100594 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700595 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100596 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100597
Francois Gaffie716e1432019-01-14 16:58:59 +0100598 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100599 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100600 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100601
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100602 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100603 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200605 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 // release TX patch if any
607 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100608 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 mCallTxPatch.clear();
610 }
611
François Gaffie9eb18552018-11-05 10:33:26 +0100612 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700613 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100614 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700615 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100616 // retrieve Rx Source and Tx Sink device descriptors
617 sp<DeviceDescriptor> rxSourceDevice =
618 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
619 String8(),
620 AUDIO_FORMAT_DEFAULT);
621 sp<DeviceDescriptor> txSinkDevice =
622 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
623 String8(),
624 AUDIO_FORMAT_DEFAULT);
625
626 // RX and TX Telephony device are declared by Primary Audio HAL
627 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
628 (telephonyRxModule->getHalVersionMajor() >= 3)) {
629 if (rxSourceDevice == 0 || txSinkDevice == 0) {
630 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100631 ALOGE("%s() no telephony Tx and/or RX device", __func__);
632 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100633 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100634 // createAudioPatchInternal now supports both HW / SW bridging
635 createRxPatch = true;
636 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100637 } else {
638 // If the RX device is on the primary HW module, then use legacy routing method for
639 // voice calls via setOutputDevice() on primary output.
640 // Otherwise, create two audio patches for TX and RX path.
641 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
642 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700643 // If the TX device is also on the primary HW module, setOutputDevice() will take care
644 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100645 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
646 (txSinkDevice != 0);
647 }
648 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
649 // Otherwise, create two audio patches for TX and RX path.
650 if (!createRxPatch) {
651 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700652 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200653 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800654 // If the TX device is on the primary HW module but RX device is
655 // on other HW module, SinkMetaData of telephony input should handle it
656 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700657 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700658 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100659 // terminate active capture if on the same HW module as the call TX source device
660 // FIXME: would be better to refine to only inputs whose profile connects to the
661 // call TX device but this information is not in the audio patch and logic here must be
662 // symmetric to the one in startInput()
663 for (const auto& activeDesc : mInputs.getActiveInputs()) {
664 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
665 closeActiveClients(activeDesc);
666 }
667 }
François Gaffie9eb18552018-11-05 10:33:26 +0100668 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800669 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 if (waitMs != nullptr) {
671 *waitMs = muteWaitMs;
672 }
673 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800674}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700675
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800676sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100677 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700678 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700679
François Gaffie11d30102018-11-02 16:09:09 +0100680 if (device == nullptr) {
681 return nullptr;
682 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100683
684 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800685 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100686 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800687 addSource(mAvailableInputDevices.getDevice(
688 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800689 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100690 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800691 addSink(mAvailableOutputDevices.getDevice(
692 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800693 }
694
François Gaffieafd4cea2019-11-18 15:50:22 +0100695 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
696 status_t status =
697 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
698 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
699 if (status != NO_ERROR || index < 0) {
700 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
701 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800702 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100703 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800704}
705
Mikhail Naganov100f0122018-11-29 11:22:16 -0800706bool AudioPolicyManager::isDeviceOfModule(
707 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
708 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
709 if (module != 0) {
710 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
711 .indexOf(devDesc) != NAME_NOT_FOUND
712 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
713 .indexOf(devDesc) != NAME_NOT_FOUND;
714 }
715 return false;
716}
717
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200718void AudioPolicyManager::connectTelephonyRxAudioSource()
719{
720 disconnectTelephonyRxAudioSource();
721 const struct audio_port_config source = {
722 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
723 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
724 };
725 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
726 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
727 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
728}
729
730void AudioPolicyManager::disconnectTelephonyRxAudioSource()
731{
732 stopAudioSource(mCallRxSourceClientPort);
733 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
734}
735
Eric Laurente0720872014-03-11 09:30:41 -0700736void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700737{
738 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100739 // store previous phone state for management of sonification strategy below
740 int oldState = mEngine->getPhoneState();
741
742 if (mEngine->setPhoneState(state) != NO_ERROR) {
743 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700744 return;
745 }
François Gaffie2110e042015-03-24 08:41:51 +0100746 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700747 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700748 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700749 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800750 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700751 }
752
François Gaffie2110e042015-03-24 08:41:51 +0100753 /**
754 * Switching to or from incall state or switching between telephony and VoIP lead to force
755 * routing command.
756 */
Eric Laurent74b71512019-11-06 17:21:57 -0800757 bool force = ((isStateInCall(oldState) != isStateInCall(state))
758 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700759
760 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700761 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700762
Eric Laurente552edb2014-03-10 17:42:56 -0700763 int delayMs = 0;
764 if (isStateInCall(state)) {
765 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100766 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
767 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700768 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700769 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700770 // mute media and sonification strategies and delay device switch by the largest
771 // latency of any output where either strategy is active.
772 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100773 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
774 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
775 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700776 (delayMs < (int)desc->latency()*2)) {
777 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700778 }
François Gaffiec005e562018-11-06 15:04:49 +0100779 setStrategyMute(musicStrategy, true, desc);
780 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
781 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
782 nullptr, true /*fromCache*/).types());
783 setStrategyMute(sonificationStrategy, true, desc);
784 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
785 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
786 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700787 }
788 }
789
Eric Laurent87ffa392015-05-22 10:32:38 -0700790 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700791 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100792 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700793 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100794 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
795 // force routing command to audio hardware when ending call
796 // even if no device change is needed
797 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
798 rxDevices = mPrimaryOutput->devices();
799 }
800 if (oldState == AUDIO_MODE_IN_CALL) {
801 disconnectTelephonyRxAudioSource();
802 if (mCallTxPatch != 0) {
803 releaseAudioPatchInternal(mCallTxPatch->getHandle());
804 mCallTxPatch.clear();
805 }
806 }
François Gaffie11d30102018-11-02 16:09:09 +0100807 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700808 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700809 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700810
811 // reevaluate routing on all outputs in case tracks have been started during the call
812 for (size_t i = 0; i < mOutputs.size(); i++) {
813 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100814 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700815 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100816 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700817 }
818 }
819
Eric Laurente552edb2014-03-10 17:42:56 -0700820 if (isStateInCall(state)) {
821 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700822 // force reevaluating accessibility routing when call starts
823 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 }
825
826 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100827 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
828 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700829}
830
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700831audio_mode_t AudioPolicyManager::getPhoneState() {
832 return mEngine->getPhoneState();
833}
834
Eric Laurente0720872014-03-11 09:30:41 -0700835void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100836 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700837{
François Gaffie2110e042015-03-24 08:41:51 +0100838 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700839 if (config == mEngine->getForceUse(usage)) {
840 return;
841 }
Eric Laurente552edb2014-03-10 17:42:56 -0700842
François Gaffie2110e042015-03-24 08:41:51 +0100843 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
844 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
845 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700846 }
François Gaffie2110e042015-03-24 08:41:51 +0100847 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
848 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
849 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700850
851 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700852 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800853
Eric Laurent22fcda22019-05-17 16:28:47 -0700854 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
855 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
856 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
857 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
858 }
859
Eric Laurentdc462862016-07-19 12:29:53 -0700860 //FIXME: workaround for truncated touch sounds
861 // to be removed when the problem is handled by system UI
862 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700863 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
864 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
865 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700866
867 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100868 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700869}
870
Eric Laurente0720872014-03-11 09:30:41 -0700871void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700872{
873 ALOGV("setSystemProperty() property %s, value %s", property, value);
874}
875
Michael Chana94fbb22018-04-24 14:31:19 +1000876// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
877// search to profiles for direct outputs.
878sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100879 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000880 uint32_t samplingRate,
881 audio_format_t format,
882 audio_channel_mask_t channelMask,
883 audio_output_flags_t flags,
884 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700885{
Michael Chana94fbb22018-04-24 14:31:19 +1000886 if (directOnly) {
887 // only retain flags that will drive the direct output profile selection
888 // if explicitly requested
889 static const uint32_t kRelevantFlags =
890 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700891 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000892 flags =
893 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
894 }
Eric Laurent861a6282015-05-18 15:40:16 -0700895
896 sp<IOProfile> profile;
897
Mikhail Naganovd4120142017-12-06 15:49:22 -0800898 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800899 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100900 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700901 samplingRate, NULL /*updatedSamplingRate*/,
902 format, NULL /*updatedFormat*/,
903 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700904 flags)) {
905 continue;
906 }
907 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100908 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700909 continue;
910 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800911 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700912 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800913 continue;
914 }
Michael Chana94fbb22018-04-24 14:31:19 +1000915 if (!directOnly) return curProfile;
916 // when searching for direct outputs, if several profiles are compatible, give priority
917 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100918 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700919 continue;
920 }
921 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100922 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700923 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700924 }
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
926 }
Eric Laurent861a6282015-05-18 15:40:16 -0700927 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700928}
929
Eric Laurentfa0f6742021-08-17 18:39:44 +0200930sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200931 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices,
932 bool forOpening) const
933{
934 for (const auto& hwModule : mHwModules) {
935 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200936 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200937 continue;
938 }
939 // reject profiles not corresponding to a device currently available
940 DeviceVector supportedDevices = curProfile->getSupportedDevices();
941 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
942 continue;
943 }
944 if (!devices.empty()) {
945 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
946 != devices.size()) {
947 continue;
948 }
949 }
950 if (forOpening && !curProfile->canOpenNewIo()) {
951 continue;
952 }
953 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
954 return curProfile;
955 }
956 }
957 return nullptr;
958}
959
Eric Laurentf4e63452017-11-06 19:31:46 +0000960audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700961{
François Gaffiec005e562018-11-06 15:04:49 +0100962 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800963
964 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
965 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
966 // format, flags, etc. This may result in some discrepancy for functions that utilize
967 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
968 // and AudioSystem::getOutputSamplingRate().
969
François Gaffie11d30102018-11-02 16:09:09 +0100970 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700971 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700972
François Gaffie11d30102018-11-02 16:09:09 +0100973 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
974 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000975 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700976}
977
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700978status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
979 const audio_attributes_t *srcAttr,
980 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700981{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700982 if (srcAttr != NULL) {
983 if (!isValidAttributes(srcAttr)) {
984 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
985 __func__,
986 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
987 srcAttr->tags);
988 return BAD_VALUE;
989 }
990 *dstAttr = *srcAttr;
991 } else {
992 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
993 ALOGE("%s: invalid stream type", __func__);
994 return BAD_VALUE;
995 }
François Gaffiec005e562018-11-06 15:04:49 +0100996 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700997 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700998
999 // Only honor audibility enforced when required. The client will be
1000 // forced to reconnect if the forced usage changes.
1001 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001002 dstAttr->flags = static_cast<audio_flags_mask_t>(
1003 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001004 }
1005
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001006 return NO_ERROR;
1007}
1008
Kevin Rocard153f92d2018-12-18 18:33:28 -08001009status_t AudioPolicyManager::getOutputForAttrInt(
1010 audio_attributes_t *resultAttr,
1011 audio_io_handle_t *output,
1012 audio_session_t session,
1013 const audio_attributes_t *attr,
1014 audio_stream_type_t *stream,
1015 uid_t uid,
1016 const audio_config_t *config,
1017 audio_output_flags_t *flags,
1018 audio_port_handle_t *selectedDeviceId,
1019 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001020 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001021 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001022{
François Gaffiec005e562018-11-06 15:04:49 +01001023 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001024 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001025 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001026 const sp<DeviceDescriptor> requestedDevice =
1027 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1028
Eric Laurent8a1095a2019-11-08 14:44:16 -08001029 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001030 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1031 if (status != NO_ERROR) {
1032 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001033 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001034 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001035 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001036 }
François Gaffiec005e562018-11-06 15:04:49 +01001037 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001038
François Gaffiec005e562018-11-06 15:04:49 +01001039 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1040 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001041
Kevin Rocard153f92d2018-12-18 18:33:28 -08001042 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1043 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1044 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001045 sp<AudioPolicyMix> primaryMix;
1046 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001047 if (status != OK) {
1048 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001049 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001050
Kevin Rocard153f92d2018-12-18 18:33:28 -08001051 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001052 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001053
1054 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001055 if ((usePrimaryOutputFromPolicyMixes
1056 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001057 && !audio_is_linear_pcm(config->format)) {
1058 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001059 return BAD_VALUE;
1060 }
1061 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001062 sp<DeviceDescriptor> deviceDesc =
1063 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1064 primaryMix->mDeviceAddress,
1065 AUDIO_FORMAT_DEFAULT);
1066 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001067 if (deviceDesc != nullptr
1068 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001069 audio_io_handle_t newOutput;
1070 status = openDirectOutput(
1071 *stream, session, config,
1072 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1073 DeviceVector(deviceDesc), &newOutput);
1074 if (status != NO_ERROR) {
1075 policyDesc = nullptr;
1076 } else {
1077 policyDesc = mOutputs.valueFor(newOutput);
1078 primaryMix->setOutput(policyDesc);
1079 }
1080 }
1081 if (policyDesc != nullptr) {
1082 policyDesc->mPolicyMix = primaryMix;
1083 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001084 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001085
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001086 ALOGV("getOutputForAttr() returns output %d", *output);
1087 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1088 *outputType = API_OUT_MIX_PLAYBACK;
1089 } else {
1090 *outputType = API_OUTPUT_LEGACY;
1091 }
1092 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001093 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001094 }
François Gaffiec005e562018-11-06 15:04:49 +01001095 // Virtual sources must always be dynamicaly or explicitly routed
1096 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1097 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1098 return BAD_VALUE;
1099 }
1100 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1101 // in order to let the choice of the order to future vendor engine
1102 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001103
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001104 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001105 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001106 }
1107
Nadav Barb2f18162018-07-18 13:01:53 +03001108 // Set incall music only if device was explicitly set, and fallback to the device which is
1109 // chosen by the engine if not.
1110 // FIXME: provide a more generic approach which is not device specific and move this back
1111 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001112 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001113 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001114 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001115 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001116 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001117 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001118 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001119 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001120 }
1121 }
1122
François Gaffiec005e562018-11-06 15:04:49 +01001123 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1124 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1125 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001126
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001127 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001128 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001129 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001130 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001131 ALOGV("%s() Using MSD devices %s instead of devices %s",
1132 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001133 } else {
1134 *output = AUDIO_IO_HANDLE_NONE;
1135 }
1136 }
1137 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001138 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001139 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001140 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001141 if (*output == AUDIO_IO_HANDLE_NONE) {
1142 return INVALID_OPERATION;
1143 }
Paul McLeanaa981192015-03-21 09:55:15 -07001144
François Gaffiec005e562018-11-06 15:04:49 +01001145 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001146 for (auto &outputDevice : outputDevices) {
1147 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1148 *selectedDeviceId = outputDevice->getId();
1149 break;
1150 }
1151 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001152
Eric Laurent8a1095a2019-11-08 14:44:16 -08001153 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1154 *outputType = API_OUTPUT_TELEPHONY_TX;
1155 } else {
1156 *outputType = API_OUTPUT_LEGACY;
1157 }
1158
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001159 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1160
1161 return NO_ERROR;
1162}
1163
1164status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1165 audio_io_handle_t *output,
1166 audio_session_t session,
1167 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001168 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001169 const audio_config_t *config,
1170 audio_output_flags_t *flags,
1171 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001173 std::vector<audio_io_handle_t> *secondaryOutputs,
1174 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001175{
1176 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1177 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1178 return INVALID_OPERATION;
1179 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001180 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001181 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001182 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001183 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001184 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001185 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001186 const sp<DeviceDescriptor> requestedDevice =
1187 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1188
1189 // Prevent from storing invalid requested device id in clients
1190 const audio_port_handle_t sanitizedRequestedPortId =
1191 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1192 *selectedDeviceId = sanitizedRequestedPortId;
1193
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001194 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001195 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001196 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001197 if (status != NO_ERROR) {
1198 return status;
1199 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001201 if (secondaryOutputs != nullptr) {
1202 for (auto &secondaryMix : secondaryMixes) {
1203 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1204 if (outputDesc != nullptr &&
1205 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1206 secondaryOutputs->push_back(outputDesc->mIoHandle);
1207 weakSecondaryOutputDescs.push_back(outputDesc);
1208 }
1209 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001211
Eric Laurent8fc147b2018-07-22 19:13:55 -07001212 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001213 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001214 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001215 };
jiabin4ef93452019-09-10 14:29:54 -07001216 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001217
Eric Laurentc209fe42020-06-05 18:11:23 -07001218 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001219 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001220 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001221 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001222 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001223 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001224 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001225 std::move(weakSecondaryOutputDescs),
1226 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001227 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001228
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001229 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1230 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001231
Eric Laurente83b55d2014-11-14 10:06:21 -08001232 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001233}
1234
Eric Laurentc529cf62020-04-17 18:19:10 -07001235status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1236 audio_session_t session,
1237 const audio_config_t *config,
1238 audio_output_flags_t flags,
1239 const DeviceVector &devices,
1240 audio_io_handle_t *output) {
1241
1242 *output = AUDIO_IO_HANDLE_NONE;
1243
1244 // skip direct output selection if the request can obviously be attached to a mixed output
1245 // and not explicitly requested
1246 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1247 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1248 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1249 return NAME_NOT_FOUND;
1250 }
1251
1252 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1253 // This prevents creating an offloaded track and tearing it down immediately after start
1254 // when audioflinger detects there is an active non offloadable effect.
1255 // FIXME: We should check the audio session here but we do not have it in this context.
1256 // This may prevent offloading in rare situations where effects are left active by apps
1257 // in the background.
1258 sp<IOProfile> profile;
1259 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1260 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1261 profile = getProfileForOutput(
1262 devices, config->sample_rate, config->format, config->channel_mask,
1263 flags, true /* directOnly */);
1264 }
1265
1266 if (profile == nullptr) {
1267 return NAME_NOT_FOUND;
1268 }
1269
1270 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1271 for (size_t i = 0; i < mOutputs.size(); i++) {
1272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1273 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1274 // reuse direct output if currently open by the same client
1275 // and configured with same parameters
1276 if ((config->sample_rate == desc->getSamplingRate()) &&
1277 (config->format == desc->getFormat()) &&
1278 (config->channel_mask == desc->getChannelMask()) &&
1279 (session == desc->mDirectClientSession)) {
1280 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001281 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001282 mOutputs.keyAt(i), session);
1283 *output = mOutputs.keyAt(i);
1284 return NO_ERROR;
1285 }
1286 }
1287 }
1288
1289 if (!profile->canOpenNewIo()) {
1290 return NAME_NOT_FOUND;
1291 }
1292
1293 sp<SwAudioOutputDescriptor> outputDesc =
1294 new SwAudioOutputDescriptor(profile, mpClientInterface);
1295
Michael Chan6fb34492020-12-08 15:44:49 +11001296 // An MSD patch may be using the only output stream that can service this request. Release
1297 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001298 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001299
Eric Laurentf1f22e72021-07-13 14:04:14 +02001300 status_t status =
1301 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001302
1303 // only accept an output with the requested parameters
1304 if (status != NO_ERROR ||
1305 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1306 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1307 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1308 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1309 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1310 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1311 config->channel_mask, outputDesc->getChannelMask());
1312 if (*output != AUDIO_IO_HANDLE_NONE) {
1313 outputDesc->close();
1314 }
1315 // fall back to mixer output if possible when the direct output could not be open
1316 if (audio_is_linear_pcm(config->format) &&
1317 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1318 return NAME_NOT_FOUND;
1319 }
1320 *output = AUDIO_IO_HANDLE_NONE;
1321 return BAD_VALUE;
1322 }
1323 outputDesc->mDirectOpenCount = 1;
1324 outputDesc->mDirectClientSession = session;
1325
1326 addOutput(*output, outputDesc);
1327 mPreviousOutputs = mOutputs;
1328 ALOGV("%s returns new direct output %d", __func__, *output);
1329 mpClientInterface->onAudioPortListUpdate();
1330 return NO_ERROR;
1331}
1332
François Gaffie11d30102018-11-02 16:09:09 +01001333audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1334 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001335 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001336 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001337 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001338 audio_output_flags_t *flags,
1339 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001340{
Andy Hungc88b0642018-04-27 15:42:35 -07001341 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001342
jiabine375d412019-02-26 12:54:53 -08001343 // Discard haptic channel mask when forcing muting haptic channels.
1344 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001345 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1346 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001347
Eric Laurente552edb2014-03-10 17:42:56 -07001348 // open a direct output if required by specified parameters
1349 //force direct flag if offload flag is set: offloading implies a direct output stream
1350 // and all common behaviors are driven by checking only the direct flag
1351 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001352 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1353 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001354 }
Nadav Bar766fb022018-01-07 12:18:03 +02001355 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1356 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001357 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001358
1359 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1360
Eric Laurente83b55d2014-11-14 10:06:21 -08001361 // only allow deep buffering for music stream type
1362 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001363 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001364 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001365 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001366 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1367 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001368 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001369 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001370 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001371 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001372 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001373 audio_is_linear_pcm(config->format) &&
1374 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001375 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001376 AUDIO_OUTPUT_FLAG_DIRECT);
1377 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001378 }
Eric Laurente552edb2014-03-10 17:42:56 -07001379
Eric Laurentfa0f6742021-08-17 18:39:44 +02001380 if (mSpatializerOutput != nullptr
1381 && canBeSpatialized(attr, config, devices.toTypeAddrVector())) {
1382 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001383 }
1384
Eric Laurentc529cf62020-04-17 18:19:10 -07001385 audio_config_t directConfig = *config;
1386 directConfig.channel_mask = channelMask;
1387 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1388 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001389 return output;
1390 }
1391
Eric Laurent14cbfca2016-03-17 09:42:16 -07001392 // A request for HW A/V sync cannot fallback to a mixed output because time
1393 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001394 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001395 return AUDIO_IO_HANDLE_NONE;
1396 }
1397
Eric Laurente552edb2014-03-10 17:42:56 -07001398 // ignoring channel mask due to downmix capability in mixer
1399
1400 // open a non direct output
1401
1402 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001403 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001404 // get which output is suitable for the specified stream. The actual
1405 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001406 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001407
Eric Laurent8838a382014-09-08 16:44:28 -07001408 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001409 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001410 output = selectOutput(
1411 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001412 }
François Gaffie11d30102018-11-02 16:09:09 +01001413 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001414 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001415 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001416
Eric Laurente552edb2014-03-10 17:42:56 -07001417 return output;
1418}
1419
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001420sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001421 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1422 mAvailableInputDevices);
1423 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1424}
1425
1426DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1427 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1428 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001429}
1430
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001431const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001432 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001433 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1434 if (msdModule != 0) {
1435 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1436 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1437 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1438 const struct audio_port_config *source = &patch->mPatch.sources[j];
1439 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1440 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001441 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001442 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001443 }
1444 }
1445 }
1446 return msdPatches;
1447}
1448
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001449status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1450 const InputProfileCollection &inputProfiles,
1451 const OutputProfileCollection &outputProfiles,
1452 const sp<DeviceDescriptor> &sourceDevice,
1453 const sp<DeviceDescriptor> &sinkDevice,
1454 AudioProfileVector& sourceProfiles,
1455 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001456 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001457 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001458 return NO_INIT;
1459 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001460 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001461 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001462 return NO_INIT;
1463 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001464 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001465 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1466 inProfile->supportsDevice(sourceDevice)) {
1467 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001468 }
1469 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001470 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001471 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001472 outProfile->supportsDevice(sinkDevice)) {
1473 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001474 }
1475 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001476 return NO_ERROR;
1477}
1478
1479status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1480 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1481 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1482{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001483 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001484 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1485 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1486 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001487 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001488 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1489 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001490 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001491 }
1492 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1493 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1494 sinkConfig->format = bestSinkConfig.format;
1495 // For encoded streams force direct flag to prevent downstream mixing.
1496 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1497 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001498 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1499 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001500 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001501 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1502 // raw and IEC61937 framed streams.
1503 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1504 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1505 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001506 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1507 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1508 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1509 sourceConfig->format = bestSinkConfig.format;
1510 // Copy input stream directly without any processing (e.g. resampling).
1511 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1512 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1513 if (hwAvSync) {
1514 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1515 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1516 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1517 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1518 }
1519 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1520 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1521 sinkConfig->config_mask |= config_mask;
1522 sourceConfig->config_mask |= config_mask;
1523 return NO_ERROR;
1524}
1525
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001526PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1527 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001528{
1529 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001530 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1531 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1532 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1533 if (deviceModule == nullptr) {
1534 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1535 return patchBuilder;
1536 }
1537 const InputProfileCollection inputProfiles = msdIsSource ?
1538 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1539 const OutputProfileCollection outputProfiles = msdIsSource ?
1540 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1541
1542 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1543 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1544 device : getMsdAudioOutDevices().itemAt(0);
1545 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1546
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001547 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1548 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001549 AudioProfileVector sourceProfiles;
1550 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001551 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1552 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001553 for (auto hwAvSync : { true, false }) {
1554 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1555 sourceProfiles, sinkProfiles) != NO_ERROR) {
1556 continue;
1557 }
1558 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1559 &sinkConfig) == NO_ERROR) {
1560 // Found a matching config. Re-create PatchBuilder with this config.
1561 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1562 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001563 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001564 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001565 " supporting PCM format conversion.", __func__);
1566 return patchBuilder;
1567}
1568
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001569status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001570 DeviceVector devices;
1571 if (outputDevices != nullptr && outputDevices->size() > 0) {
1572 devices.add(*outputDevices);
1573 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001574 // Use media strategy for unspecified output device. This should only
1575 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1576 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001577 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001578 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001579 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001580 }
Michael Chan6fb34492020-12-08 15:44:49 +11001581 std::vector<PatchBuilder> patchesToCreate;
1582 for (auto i = 0u; i < devices.size(); ++i) {
1583 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001584 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001585 }
1586 // Retain only the MSD patches associated with outputDevices request.
1587 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001588 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001589 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1590 auto retainedPatch = false;
1591 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1592 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1593 patchesToRemove.removeItemsAt(i);
1594 retainedPatch = true;
1595 break;
1596 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001597 }
Michael Chan6fb34492020-12-08 15:44:49 +11001598 if (retainedPatch) {
1599 it = patchesToCreate.erase(it);
1600 continue;
1601 }
1602 ++it;
1603 }
1604 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1605 return NO_ERROR;
1606 }
1607 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1608 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001609 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001610 }
Michael Chan6fb34492020-12-08 15:44:49 +11001611 status_t status = NO_ERROR;
1612 for (const auto &p : patchesToCreate) {
1613 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1614 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1615 char message[256];
1616 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1617 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1618 currStatus == NO_ERROR ? "Success" : "Error",
1619 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1620 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1621 if (currStatus == NO_ERROR) {
1622 ALOGD("%s", message);
1623 } else {
1624 ALOGE("%s", message);
1625 if (status == NO_ERROR) {
1626 status = currStatus;
1627 }
1628 }
1629 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 return status;
1631}
1632
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001633void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1634 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001635 for (size_t i = 0; i < msdPatches.size(); i++) {
1636 const auto& patch = msdPatches[i];
1637 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1638 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1639 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1640 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1641 releaseAudioPatch(patch->getHandle(), mUidCached);
1642 break;
1643 }
1644 }
1645 }
1646}
1647
Eric Laurente0720872014-03-11 09:30:41 -07001648audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001649 audio_output_flags_t flags,
1650 audio_format_t format,
1651 audio_channel_mask_t channelMask,
1652 uint32_t samplingRate,
1653 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001654{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001655 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1656 "%s called with format %#x", __func__, format);
1657
jiabinebb6af42020-06-09 17:31:17 -07001658 // Return the output that haptic-generating attached to when 1) session id is specified,
1659 // 2) haptic-generating effect exists for given session id and 3) the output that
1660 // haptic-generating effect attached to is in given outputs.
1661 if (sessionId != AUDIO_SESSION_NONE) {
1662 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1663 sessionId, FX_IID_HAPTICGENERATOR);
1664 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1665 return hapticGeneratingOutput;
1666 }
1667 }
1668
Eric Laurent16c66dd2019-05-01 17:54:10 -07001669 // Flags disqualifying an output: the match must happen before calling selectOutput()
1670 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1671 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1672
1673 // Flags expressing a functional request: must be honored in priority over
1674 // other criteria
1675 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1676 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1677 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1678 // Flags expressing a performance request: have lower priority than serving
1679 // requested sampling rate or channel mask
1680 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1681 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1682 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1683
1684 const audio_output_flags_t functionalFlags =
1685 (audio_output_flags_t)(flags & kFunctionalFlags);
1686 const audio_output_flags_t performanceFlags =
1687 (audio_output_flags_t)(flags & kPerformanceFlags);
1688
1689 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1690
Eric Laurente552edb2014-03-10 17:42:56 -07001691 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001692 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001693 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001694 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001695 // 2: the output with the highest number of requested functional flags
1696 // 3: the output supporting the exact channel mask
1697 // 4: the output with a higher channel count than requested
1698 // 5: the output with a higher sampling rate than requested
1699 // 6: the output with the highest number of requested performance flags
1700 // 7: the output with the bit depth the closest to the requested one
1701 // 8: the primary output
1702 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001703
Eric Laurent16c66dd2019-05-01 17:54:10 -07001704 // matching criteria values in priority order for best matching output so far
1705 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001706
Eric Laurent16c66dd2019-05-01 17:54:10 -07001707 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1708 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1709 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001710
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001711 for (audio_io_handle_t output : outputs) {
1712 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001713 // matching criteria values in priority order for current output
1714 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001715
Eric Laurent16c66dd2019-05-01 17:54:10 -07001716 if (outputDesc->isDuplicated()) {
1717 continue;
1718 }
1719 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1720 continue;
1721 }
Eric Laurent8838a382014-09-08 16:44:28 -07001722
Eric Laurent16c66dd2019-05-01 17:54:10 -07001723 // If haptic channel is specified, use the haptic output if present.
1724 // When using haptic output, same audio format and sample rate are required.
1725 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001726 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001727 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1728 continue;
1729 }
1730 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001731 && format == outputDesc->getFormat()
1732 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001733 currentMatchCriteria[0] = outputHapticChannelCount;
1734 }
1735
1736 // functional flags match
1737 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1738
1739 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001740 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1741 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001742 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1743 channelCount <= outputChannelCount) {
1744 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001745 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1746 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001747 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001748 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001749 currentMatchCriteria[3] = outputChannelCount;
1750 }
1751
1752 // sampling rate match
1753 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001754 samplingRate <= outputDesc->getSamplingRate()) {
1755 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001756 }
1757
1758 // performance flags match
1759 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1760
1761 // format match
1762 if (format != AUDIO_FORMAT_INVALID) {
1763 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001764 PolicyAudioPort::kFormatDistanceMax -
1765 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001766 }
1767
1768 // primary output match
1769 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1770
1771 // compare match criteria by priority then value
1772 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1773 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1774 bestMatchCriteria = currentMatchCriteria;
1775 bestOutput = output;
1776
1777 std::stringstream result;
1778 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1779 std::ostream_iterator<int>(result, " "));
1780 ALOGV("%s new bestOutput %d criteria %s",
1781 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001782 }
1783 }
1784
Eric Laurent16c66dd2019-05-01 17:54:10 -07001785 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001786}
1787
Eric Laurent8fc147b2018-07-22 19:13:55 -07001788status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001789{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001790 ALOGV("%s portId %d", __FUNCTION__, portId);
1791
1792 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1793 if (outputDesc == 0) {
1794 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001795 return BAD_VALUE;
1796 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001797 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001798
Eric Laurent8fc147b2018-07-22 19:13:55 -07001799 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001800 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001801
Eric Laurent733ce942017-12-07 12:18:25 -08001802 status_t status = outputDesc->start();
1803 if (status != NO_ERROR) {
1804 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001805 }
1806
Eric Laurent97ac8712018-07-27 18:59:02 -07001807 uint32_t delayMs;
1808 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001809
1810 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001811 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001812 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001813 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001814 if (delayMs != 0) {
1815 usleep(delayMs * 1000);
1816 }
1817
1818 return status;
1819}
1820
Eric Laurent97ac8712018-07-27 18:59:02 -07001821status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1822 const sp<TrackClientDescriptor>& client,
1823 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001824{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001825 // cannot start playback of STREAM_TTS if any other output is being used
1826 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001827
1828 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001829 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001830 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001831 auto clientStrategy = client->strategy();
1832 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001833 if (stream == AUDIO_STREAM_TTS) {
1834 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001835 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001836 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001837 return INVALID_OPERATION;
1838 } else {
1839 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1840 }
1841 } else {
1842 // some playback other than beacon starts
1843 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1844 }
1845
Eric Laurent77305a62016-07-25 16:39:22 -07001846 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001847 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001848 bool force = !outputDesc->isActive() &&
1849 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001850
François Gaffie11d30102018-11-02 16:09:09 +01001851 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001852 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001853 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001854 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001855 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001856 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001857 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001858 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001859 } else {
1860 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001861 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001862 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1863 AUDIO_FORMAT_DEFAULT);
1864 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1865 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001866 }
1867
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001868 // requiresMuteCheck is false when we can bypass mute strategy.
1869 // It covers a common case when there is no materially active audio
1870 // and muting would result in unnecessary delay and dropped audio.
1871 const uint32_t outputLatencyMs = outputDesc->latency();
1872 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1873
Eric Laurente552edb2014-03-10 17:42:56 -07001874 // increment usage count for this stream on the requested output:
1875 // NOTE that the usage count is the same for duplicated output and hardware output which is
1876 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001877 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001878
1879 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001880 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1881 client->isPreferredDeviceForExclusiveUse()) {
1882 // Preferred device may be exclusive, use only if no other active clients on this output
1883 devices = DeviceVector(
1884 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1885 } else {
1886 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1887 }
François Gaffie11d30102018-11-02 16:09:09 +01001888 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001889 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001890 }
1891 }
Eric Laurente552edb2014-03-10 17:42:56 -07001892
François Gaffiec005e562018-11-06 15:04:49 +01001893 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001894 selectOutputForMusicEffects();
1895 }
1896
François Gaffie1c878552018-11-22 16:53:21 +01001897 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001898 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001899 if (devices.isEmpty()) {
1900 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001901 }
François Gaffiec005e562018-11-06 15:04:49 +01001902 bool shouldWait =
1903 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1904 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1905 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001906 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001907 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001908 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001909 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001910 // An output has a shared device if
1911 // - managed by the same hw module
1912 // - supports the currently selected device
1913 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001914 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001915
Eric Laurent77305a62016-07-25 16:39:22 -07001916 // force a device change if any other output is:
1917 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001918 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001919 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001920 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001921 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001922 // change the device currently selected by the other output.
1923 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001924 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001925 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001926 force = true;
1927 }
1928 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001929 // a notification so that audio focus effect can propagate, or that a mute/unmute
1930 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001931 const uint32_t latencyMs = desc->latency();
1932 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1933
1934 if (shouldWait && isActive && (waitMs < latencyMs)) {
1935 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001936 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001937
1938 // Require mute check if another output is on a shared device
1939 // and currently active to have proper drain and avoid pops.
1940 // Note restoring AudioTracks onto this output needs to invoke
1941 // a volume ramp if there is no mute.
1942 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001943 }
1944 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001945
1946 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001947 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001948
Eric Laurente552edb2014-03-10 17:42:56 -07001949 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001950 auto &curves = getVolumeCurves(client->attributes());
1951 checkAndSetVolume(curves, client->volumeSource(),
1952 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001953 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001954 outputDesc->devices().types(), 0 /*delay*/,
1955 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001956
1957 // update the outputs if starting an output with a stream that can affect notification
1958 // routing
1959 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001960
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001961 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001962 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001963 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1964 }
Eric Laurentdc462862016-07-19 12:29:53 -07001965
1966 if (waitMs > muteWaitMs) {
1967 *delayMs = waitMs - muteWaitMs;
1968 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001969
1970 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1971 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1972 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1973 // change occurs after the MixerThread starts and causes a stream volume
1974 // glitch.
1975 //
1976 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001977 }
Eric Laurentdc462862016-07-19 12:29:53 -07001978
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001979 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001980 mEngine->getForceUse(
1981 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001982 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001983 }
1984
Eric Laurent97ac8712018-07-27 18:59:02 -07001985 // Automatically enable the remote submix input when output is started on a re routing mix
1986 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001987 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1988 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001989 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1990 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1991 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001992 "remote-submix",
1993 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001994 }
1995
Eric Laurente552edb2014-03-10 17:42:56 -07001996 return NO_ERROR;
1997}
1998
Eric Laurent8fc147b2018-07-22 19:13:55 -07001999status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002000{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002001 ALOGV("%s portId %d", __FUNCTION__, portId);
2002
2003 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2004 if (outputDesc == 0) {
2005 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002006 return BAD_VALUE;
2007 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002008 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002009
Eric Laurent97ac8712018-07-27 18:59:02 -07002010 ALOGV("stopOutput() output %d, stream %d, session %d",
2011 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002012
Eric Laurent97ac8712018-07-27 18:59:02 -07002013 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002014
Eric Laurent733ce942017-12-07 12:18:25 -08002015 if (status == NO_ERROR ) {
2016 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002017 }
2018 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002019}
2020
Eric Laurent97ac8712018-07-27 18:59:02 -07002021status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2022 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002023{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002024 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002025 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002026 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002027
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002028 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2029
François Gaffie1c878552018-11-22 16:53:21 +01002030 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2031 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002032 // Automatically disable the remote submix input when output is stopped on a
2033 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002034 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002035 if (isSingleDeviceType(
2036 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002037 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002038 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002039 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2040 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002041 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002042 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002043 }
2044 }
2045 bool forceDeviceUpdate = false;
2046 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002047 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002048 forceDeviceUpdate = true;
2049 }
2050
Eric Laurente552edb2014-03-10 17:42:56 -07002051 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002052 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002053
Eric Laurente552edb2014-03-10 17:42:56 -07002054 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002055 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002056 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002057 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002058 // delay the device switch by twice the latency because stopOutput() is executed when
2059 // the track stop() command is received and at that time the audio track buffer can
2060 // still contain data that needs to be drained. The latency only covers the audio HAL
2061 // and kernel buffers. Also the latency does not always include additional delay in the
2062 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002063 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002064
2065 // force restoring the device selection on other active outputs if it differs from the
2066 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002067 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002068 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002069 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002070 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002071 desc->isActive() &&
2072 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002073 (newDevices != desc->devices())) {
2074 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2075 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002076
François Gaffie11d30102018-11-02 16:09:09 +01002077 setOutputDevices(desc, newDevices2, force, delayMs);
2078
Eric Laurent57de36c2016-09-28 16:59:11 -07002079 // re-apply device specific volume if not done by setOutputDevice()
2080 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002081 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002082 }
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
2084 }
2085 // update the outputs if stopping one with a stream that can affect notification routing
2086 handleNotificationRoutingForStream(stream);
2087 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002088
2089 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2090 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002091 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002092 }
2093
François Gaffiec005e562018-11-06 15:04:49 +01002094 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002095 selectOutputForMusicEffects();
2096 }
Eric Laurente552edb2014-03-10 17:42:56 -07002097 return NO_ERROR;
2098 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002099 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002100 return INVALID_OPERATION;
2101 }
2102}
2103
jiabinbce0c1d2020-10-05 11:20:18 -07002104bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002105{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002106 ALOGV("%s portId %d", __FUNCTION__, portId);
2107
2108 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2109 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002110 // If an output descriptor is closed due to a device routing change,
2111 // then there are race conditions with releaseOutput from tracks
2112 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2113 // destroyed shortly thereafter.
2114 //
2115 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002116 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002117 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002118 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002119
2120 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002121
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302122 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2123 if (outputDesc->isClientActive(client)) {
2124 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2125 stopOutput(portId);
2126 }
2127
Eric Laurent8fc147b2018-07-22 19:13:55 -07002128 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2129 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002130 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002131 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002132 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002133 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002134 if (--outputDesc->mDirectOpenCount == 0) {
2135 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002136 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002137 }
2138 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302139
Andy Hung39efb7a2018-09-26 15:39:28 -07002140 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002141 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2142 // The output is pending reopened to query dynamic profiles and
2143 // there is no active clients
2144 closeOutput(outputDesc->mIoHandle);
2145 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2146 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2147 if (newOutputDesc == nullptr) {
2148 ALOGE("%s failed to open output", __func__);
2149 }
2150 return true;
2151 }
2152 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002153}
2154
Eric Laurentcaf7f482014-11-25 17:50:47 -08002155status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2156 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002157 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002158 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002159 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002160 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002161 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002162 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002163 input_type_t *inputType,
2164 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002165{
François Gaffiec005e562018-11-06 15:04:49 +01002166 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002167 "flags %#x attributes=%s requested device ID %d",
2168 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2169 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002170
Eric Laurentad2e7b92017-09-14 20:06:42 -07002171 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002172 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002173 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002174 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002175 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002176 sp<AudioInputDescriptor> inputDesc;
2177 sp<RecordClientDescriptor> clientDesc;
2178 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002179 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002180 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002181
2182 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2183 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2184 return INVALID_OPERATION;
2185 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002186
Francois Gaffie716e1432019-01-14 16:58:59 +01002187 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2188 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002189 }
2190
Paul McLean466dc8e2015-04-17 13:15:36 -06002191 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002192 sp<DeviceDescriptor> explicitRoutingDevice =
2193 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002194
Eric Laurentad2e7b92017-09-14 20:06:42 -07002195 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2196 // possible
2197 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2198 *input != AUDIO_IO_HANDLE_NONE) {
2199 ssize_t index = mInputs.indexOfKey(*input);
2200 if (index < 0) {
2201 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2202 status = BAD_VALUE;
2203 goto error;
2204 }
2205 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002206 RecordClientVector clients = inputDesc->getClientsForSession(session);
2207 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002208 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2209 status = BAD_VALUE;
2210 goto error;
2211 }
2212 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2213 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002214 // corresponds to a new client and is only permitted from the same UID.
2215 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002216 if (clients.size() > 1) {
2217 for (const auto& client : clients) {
2218 // The client map is ordered by key values (portId) and portIds are allocated
2219 // incrementaly. So the first client in this list is the one opened by audio flinger
2220 // when the mmap stream is created and should be ignored as it does not correspond
2221 // to an actual client
2222 if (client == *clients.cbegin()) {
2223 continue;
2224 }
2225 if (uid != client->uid() && !client->isSilenced()) {
2226 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2227 uid, client->portId(), client->uid());
2228 status = INVALID_OPERATION;
2229 goto error;
2230 }
Eric Laurent331679c2018-04-16 17:03:16 -07002231 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002232 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002233 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002234 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002235
Eric Laurentfecbceb2021-02-09 14:46:43 +01002236 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002237 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002238 }
2239
2240 *input = AUDIO_IO_HANDLE_NONE;
2241 *inputType = API_INPUT_INVALID;
2242
Francois Gaffie716e1432019-01-14 16:58:59 +01002243 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002244
Francois Gaffie716e1432019-01-14 16:58:59 +01002245 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2246 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2247 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002248 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002249 ALOGW("%s could not find input mix for attr %s",
2250 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002251 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002252 }
jiabinc1de2df2019-05-07 14:26:40 -07002253 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2254 String8(attr->tags + strlen("addr=")),
2255 AUDIO_FORMAT_DEFAULT);
2256 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002257 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002258 __func__, attributes.source, attributes.tags);
2259 status = BAD_VALUE;
2260 goto error;
2261 }
2262
Kevin Rocard25f9b052019-02-27 15:08:54 -08002263 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2264 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2265 } else {
2266 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2267 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002268 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002269 if (explicitRoutingDevice != nullptr) {
2270 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002271 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002272 // Prevent from storing invalid requested device id in clients
2273 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002274 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002275 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2276 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002277 }
François Gaffie11d30102018-11-02 16:09:09 +01002278 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002279 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002280 status = BAD_VALUE;
2281 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002282 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002283 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2284 *inputType = API_INPUT_MIX_CAPTURE;
2285 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002286 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2287 // there is an external policy, but this input is attached to a mix of recorders,
2288 // meaning it receives audio injected into the framework, so the recorder doesn't
2289 // know about it and is therefore considered "legacy"
2290 *inputType = API_INPUT_LEGACY;
2291 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002292 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002293 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002294 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002295 } else {
2296 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002297 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002298
Eric Laurent599c7582015-12-07 18:05:55 -08002299 }
2300
François Gaffiec005e562018-11-06 15:04:49 +01002301 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002302 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002303 status = INVALID_OPERATION;
2304 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002305 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002306
Eric Laurent8f42ea12018-08-08 09:08:25 -07002307exit:
2308
François Gaffiec005e562018-11-06 15:04:49 +01002309 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2310 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002311
Francois Gaffie716e1432019-01-14 16:58:59 +01002312 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002313 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002314 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002315
Mikhail Naganov2996f672019-04-18 12:29:59 -07002316 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002317 requestedDeviceId, attributes.source, flags,
2318 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002319 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002320 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002321
2322 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2323 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002324
Eric Laurent599c7582015-12-07 18:05:55 -08002325 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002326
2327error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002328 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002329}
2330
2331
François Gaffie11d30102018-11-02 16:09:09 +01002332audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002333 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002334 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002335 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002336 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002337 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002338{
2339 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002340 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002341 bool isSoundTrigger = false;
2342
François Gaffiec005e562018-11-06 15:04:49 +01002343 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002344 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2345 if (index >= 0) {
2346 input = mSoundTriggerSessions.valueFor(session);
2347 isSoundTrigger = true;
2348 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2349 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2350 } else {
2351 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002352 }
François Gaffiec005e562018-11-06 15:04:49 +01002353 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002354 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002355 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002356 }
2357
Andy Hungf129b032015-04-07 13:45:50 -07002358 // find a compatible input profile (not necessarily identical in parameters)
2359 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002360 // sampling rate and flags may be updated by getInputProfile
2361 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2362 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002363 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002364 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002365 audio_input_flags_t profileFlags = flags;
2366 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002367 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002368 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002369 profileFlags);
2370 if (profile != 0) {
2371 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002372 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2373 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002374 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2375 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2376 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002377 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2378 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2379 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002380 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002381 }
Eric Laurente552edb2014-03-10 17:42:56 -07002382 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002383 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002384 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002385 if (samplingRate == 0) {
2386 samplingRate = profileSamplingRate;
2387 }
Eric Laurente552edb2014-03-10 17:42:56 -07002388
Eric Laurent322b4d22015-04-03 15:57:54 -07002389 if (profile->getModuleHandle() == 0) {
2390 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002391 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002392 }
2393
Eric Laurentec376dc2021-04-08 20:41:22 +02002394 // Reuse an already opened input if a client with the same session ID already exists
2395 // on that input
2396 for (size_t i = 0; i < mInputs.size(); i++) {
2397 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2398 if (desc->mProfile != profile) {
2399 continue;
2400 }
2401 RecordClientVector clients = desc->clientsList();
2402 for (const auto &client : clients) {
2403 if (session == client->session()) {
2404 return desc->mIoHandle;
2405 }
2406 }
2407 }
2408
Eric Laurent3974e3b2017-12-07 17:58:43 -08002409 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002410 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002411 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002412 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002413 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002414 continue;
2415 }
2416 // if sound trigger, reuse input if used by other sound trigger on same session
2417 // else
2418 // reuse input if active client app is not in IDLE state
2419 //
2420 RecordClientVector clients = desc->clientsList();
2421 bool doClose = false;
2422 for (const auto& client : clients) {
2423 if (isSoundTrigger != client->isSoundTrigger()) {
2424 continue;
2425 }
2426 if (client->isSoundTrigger()) {
2427 if (session == client->session()) {
2428 return desc->mIoHandle;
2429 }
2430 continue;
2431 }
2432 if (client->active() && client->appState() != APP_STATE_IDLE) {
2433 return desc->mIoHandle;
2434 }
2435 doClose = true;
2436 }
2437 if (doClose) {
2438 closeInput(desc->mIoHandle);
2439 } else {
2440 i++;
2441 }
2442 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002443 }
2444
Eric Laurentfe231122017-11-17 17:48:06 -08002445 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002446
Eric Laurentfe231122017-11-17 17:48:06 -08002447 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2448 lConfig.sample_rate = profileSamplingRate;
2449 lConfig.channel_mask = profileChannelMask;
2450 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002451
François Gaffie11d30102018-11-02 16:09:09 +01002452 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002453
2454 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002455 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002456 (profileSamplingRate != lConfig.sample_rate) ||
2457 !audio_formats_match(profileFormat, lConfig.format) ||
2458 (profileChannelMask != lConfig.channel_mask)) {
2459 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002460 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002461 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002462 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002463 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002464 }
Eric Laurent599c7582015-12-07 18:05:55 -08002465 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002466 }
2467
Eric Laurentc722f302014-12-10 11:21:49 -08002468 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002469
Eric Laurent599c7582015-12-07 18:05:55 -08002470 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002471 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002472
Eric Laurent599c7582015-12-07 18:05:55 -08002473 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002474}
2475
Eric Laurent4eb58f12018-12-07 16:41:02 -08002476status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002477{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002478 ALOGV("%s portId %d", __FUNCTION__, portId);
2479
2480 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2481 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002482 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002483 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002484 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002485 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002486 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002487 if (client->active()) {
2488 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2489 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002490 }
2491
Eric Laurent8f42ea12018-08-08 09:08:25 -07002492 audio_session_t session = client->session();
2493
Eric Laurent4eb58f12018-12-07 16:41:02 -08002494 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002495
Eric Laurent4eb58f12018-12-07 16:41:02 -08002496 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002497
Eric Laurent4eb58f12018-12-07 16:41:02 -08002498 status_t status = inputDesc->start();
2499 if (status != NO_ERROR) {
2500 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002501 }
Eric Laurente552edb2014-03-10 17:42:56 -07002502
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002503 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002504 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002505 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002506
Eric Laurent8f42ea12018-08-08 09:08:25 -07002507 // indicate active capture to sound trigger service if starting capture from a mic on
2508 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002509 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002510 if (device != nullptr) {
2511 status = setInputDevice(input, device, true /* force */);
2512 } else {
2513 ALOGW("%s no new input device can be found for descriptor %d",
2514 __FUNCTION__, inputDesc->getId());
2515 status = BAD_VALUE;
2516 }
Eric Laurente552edb2014-03-10 17:42:56 -07002517
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002518 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002519 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002520 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002521 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002522 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2523 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002524 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002525 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002526
François Gaffie11d30102018-11-02 16:09:09 +01002527 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2528 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002529 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002530 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002531 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002532
Eric Laurent8f42ea12018-08-08 09:08:25 -07002533 // automatically enable the remote submix output when input is started if not
2534 // used by a policy mix of type MIX_TYPE_RECORDERS
2535 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002536 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002537 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002538 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002539 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002540 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2541 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002542 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002543 if (address != "") {
2544 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2545 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002546 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002547 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002548 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002549 } else if (status != NO_ERROR) {
2550 // Restore client activity state.
2551 inputDesc->setClientActive(client, false);
2552 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002553 }
2554
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002555 ALOGV("%s input %d source = %d status = %d exit",
2556 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002557
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002558 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002559}
2560
Eric Laurent8fc147b2018-07-22 19:13:55 -07002561status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002562{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002563 ALOGV("%s portId %d", __FUNCTION__, portId);
2564
2565 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2566 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002567 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002568 return BAD_VALUE;
2569 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002570 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002571 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002572 if (!client->active()) {
2573 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002574 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002575 }
Carter Hsue6139d52021-07-08 10:30:20 +08002576 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002577 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002578
Eric Laurent8f42ea12018-08-08 09:08:25 -07002579 inputDesc->stop();
2580 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002581 auto current_source = inputDesc->source();
2582 setInputDevice(input, getNewInputDevice(inputDesc),
2583 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002584 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002585 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002587 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002588 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2589 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002590 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002591 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002592
2593 // automatically disable the remote submix output when input is stopped if not
2594 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002595 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002596 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002597 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002598 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002599 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2600 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002601 }
2602 if (address != "") {
2603 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2604 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002605 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002606 }
2607 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002608 resetInputDevice(input);
2609
2610 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2611 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002612 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2613 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002614 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002615 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002616 }
2617 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002618 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002619 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002620}
2621
Eric Laurent8fc147b2018-07-22 19:13:55 -07002622void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002623{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002624 ALOGV("%s portId %d", __FUNCTION__, portId);
2625
2626 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2627 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002628 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002629 return;
2630 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002631 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002632 audio_io_handle_t input = inputDesc->mIoHandle;
2633
Eric Laurent8f42ea12018-08-08 09:08:25 -07002634 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002635
Andy Hung39efb7a2018-09-26 15:39:28 -07002636 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002637
Andy Hung39efb7a2018-09-26 15:39:28 -07002638 if (inputDesc->getClientCount() > 0) {
2639 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002640 return;
2641 }
2642
Eric Laurent05b90f82014-08-27 15:32:29 -07002643 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002644 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002645 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002646}
2647
Eric Laurent8f42ea12018-08-08 09:08:25 -07002648void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002650 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002651
2652 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002653 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002654 }
2655}
2656
Eric Laurent8f42ea12018-08-08 09:08:25 -07002657void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2658{
2659 stopInput(portId);
2660 releaseInput(portId);
2661}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002662
Eric Laurent0dd51852019-04-19 18:18:58 -07002663void AudioPolicyManager::checkCloseInputs() {
2664 // After connecting or disconnecting an input device, close input if:
2665 // - it has no client (was just opened to check profile) OR
2666 // - none of its supported devices are connected anymore OR
2667 // - one of its clients cannot be routed to one of its supported
2668 // devices anymore. Otherwise update device selection
2669 std::vector<audio_io_handle_t> inputsToClose;
2670 for (size_t i = 0; i < mInputs.size(); i++) {
2671 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2672 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002673 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002674 inputsToClose.push_back(mInputs.keyAt(i));
2675 } else {
2676 bool close = false;
2677 for (const auto& client : input->clientsList()) {
2678 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002679 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002680 if (!input->supportedDevices().contains(device)) {
2681 close = true;
2682 break;
2683 }
2684 }
2685 if (close) {
2686 inputsToClose.push_back(mInputs.keyAt(i));
2687 } else {
2688 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2689 }
2690 }
2691 }
2692
2693 for (const audio_io_handle_t handle : inputsToClose) {
2694 ALOGV("%s closing input %d", __func__, handle);
2695 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002696 }
Eric Laurentd4692962014-05-05 18:13:44 -07002697}
2698
François Gaffie251c7f02018-11-07 10:41:08 +01002699void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002700{
2701 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002702 if (indexMin < 0 || indexMax < 0) {
2703 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2704 return;
2705 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002706 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002707
2708 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002709 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2710 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002711 continue;
2712 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002713 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002714 }
Eric Laurente552edb2014-03-10 17:42:56 -07002715}
2716
Eric Laurente0720872014-03-11 09:30:41 -07002717status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002718 int index,
2719 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002720{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002721 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002722 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2723 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2724 return NO_ERROR;
2725 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002726 ALOGV("%s: stream %s attributes=%s", __func__,
2727 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002728 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002729}
2730
Eric Laurente0720872014-03-11 09:30:41 -07002731status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002732 int *index,
2733 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002734{
François Gaffiec005e562018-11-06 15:04:49 +01002735 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2736 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002737 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002738 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002739 deviceTypes = mEngine->getOutputDevicesForStream(
2740 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002741 }
jiabin9a3361e2019-10-01 09:38:30 -07002742 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002743}
2744
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002745status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002746 int index,
2747 audio_devices_t device)
2748{
2749 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002750 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2751 if (group == VOLUME_GROUP_NONE) {
2752 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002753 return BAD_VALUE;
2754 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002755 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002756 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002757 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002758 VolumeSource vs = toVolumeSource(group);
2759 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2760
2761 status = setVolumeCurveIndex(index, device, curves);
2762 if (status != NO_ERROR) {
2763 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2764 return status;
2765 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002766
jiabin9a3361e2019-10-01 09:38:30 -07002767 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002768 auto curCurvAttrs = curves.getAttributes();
2769 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2770 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002771 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002772 } else if (!curves.getStreamTypes().empty()) {
2773 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002774 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002775 } else {
2776 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2777 return BAD_VALUE;
2778 }
jiabin9a3361e2019-10-01 09:38:30 -07002779 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2780 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002781
François Gaffiecfe17322018-11-07 13:41:29 +01002782 // update volume on all outputs and streams matching the following:
2783 // - The requested stream (or a stream matching for volume control) is active on the output
2784 // - The device (or devices) selected by the engine for this stream includes
2785 // the requested device
2786 // - For non default requested device, currently selected device on the output is either the
2787 // requested device or one of the devices selected by the engine for this stream
2788 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2789 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002790 for (size_t i = 0; i < mOutputs.size(); i++) {
2791 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002792 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002793
jiabin9a3361e2019-10-01 09:38:30 -07002794 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2795 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002796 }
François Gaffieed91f582020-01-31 10:35:37 +01002797 if (!(desc->isActive(vs) || isInCall())) {
2798 continue;
2799 }
2800 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2801 curDevices.find(device) == curDevices.end()) {
2802 continue;
2803 }
2804 bool applyVolume = false;
2805 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2806 curSrcDevices.insert(device);
2807 applyVolume = (curSrcDevices.find(
2808 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2809 } else {
2810 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2811 }
2812 if (!applyVolume) {
2813 continue; // next output
2814 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002815 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2816 // If a higher priority strategy is active, and the output is routed to a device with a
2817 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002818 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002819 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002820 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2821 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2822 false /*preferredDevice*/);
2823 if (activeClients.empty()) {
2824 continue;
2825 }
2826 bool isPreempted = false;
2827 bool isHigherPriority = productStrategy < strategy;
2828 for (const auto &client : activeClients) {
2829 if (isHigherPriority && (client->volumeSource() != vs)) {
2830 ALOGV("%s: Strategy=%d (\nrequester:\n"
2831 " group %d, volumeGroup=%d attributes=%s)\n"
2832 " higher priority source active:\n"
2833 " volumeGroup=%d attributes=%s) \n"
2834 " on output %zu, bailing out", __func__, productStrategy,
2835 group, group, toString(attributes).c_str(),
2836 client->volumeSource(), toString(client->attributes()).c_str(), i);
2837 applyVolume = false;
2838 isPreempted = true;
2839 break;
2840 }
2841 // However, continue for loop to ensure no higher prio clients running on output
2842 if (client->volumeSource() == vs) {
2843 applyVolume = true;
2844 }
2845 }
2846 if (isPreempted || applyVolume) {
2847 break;
2848 }
2849 }
2850 if (!applyVolume) {
2851 continue; // next output
2852 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002853 }
François Gaffieed91f582020-01-31 10:35:37 +01002854 //FIXME: workaround for truncated touch sounds
2855 // delayed volume change for system stream to be removed when the problem is
2856 // handled by system UI
2857 status_t volStatus = checkAndSetVolume(
2858 curves, vs, index, desc, curDevices,
2859 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2860 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2861 if (volStatus != NO_ERROR) {
2862 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002863 }
2864 }
François Gaffiecfe17322018-11-07 13:41:29 +01002865 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2866 return status;
2867}
2868
François Gaffieaaac0fd2018-11-22 17:56:39 +01002869status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002870 audio_devices_t device,
2871 IVolumeCurves &volumeCurves)
2872{
2873 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2874 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002875 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2876 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002877 (index > volumeCurves.getVolumeIndexMax())) {
2878 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2879 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2880 return BAD_VALUE;
2881 }
2882 if (!audio_is_output_device(device)) {
2883 return BAD_VALUE;
2884 }
2885
2886 // Force max volume if stream cannot be muted
2887 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2888
François Gaffieaaac0fd2018-11-22 17:56:39 +01002889 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002890 volumeCurves.addCurrentVolumeIndex(device, index);
2891 return NO_ERROR;
2892}
2893
2894status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2895 int &index,
2896 audio_devices_t device)
2897{
2898 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2899 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002900 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002901 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002902 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2903 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002904 }
jiabin9a3361e2019-10-01 09:38:30 -07002905 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002906}
2907
2908status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2909 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002910 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002911{
jiabin9a3361e2019-10-01 09:38:30 -07002912 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002913 return BAD_VALUE;
2914 }
jiabin9a3361e2019-10-01 09:38:30 -07002915 index = curves.getVolumeIndex(deviceTypes);
2916 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002917 return NO_ERROR;
2918}
2919
2920status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2921 int &index)
2922{
2923 index = getVolumeCurves(attr).getVolumeIndexMin();
2924 return NO_ERROR;
2925}
2926
2927status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2928 int &index)
2929{
2930 index = getVolumeCurves(attr).getVolumeIndexMax();
2931 return NO_ERROR;
2932}
2933
Eric Laurent36829f92017-04-07 19:04:42 -07002934audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002935{
2936 // select one output among several suitable for global effects.
2937 // The priority is as follows:
2938 // 1: An offloaded output. If the effect ends up not being offloadable,
2939 // AudioFlinger will invalidate the track and the offloaded output
2940 // will be closed causing the effect to be moved to a PCM output.
2941 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002942 // 3: The primary output
2943 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002944
François Gaffiec005e562018-11-06 15:04:49 +01002945 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2946 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002947 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002948
Eric Laurent36829f92017-04-07 19:04:42 -07002949 if (outputs.size() == 0) {
2950 return AUDIO_IO_HANDLE_NONE;
2951 }
Eric Laurente552edb2014-03-10 17:42:56 -07002952
Eric Laurent36829f92017-04-07 19:04:42 -07002953 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2954 bool activeOnly = true;
2955
2956 while (output == AUDIO_IO_HANDLE_NONE) {
2957 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2958 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2959 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2960
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002961 for (audio_io_handle_t output : outputs) {
2962 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002963 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002964 continue;
2965 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002966 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2967 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002968 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002969 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002970 }
2971 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002972 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002973 }
2974 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002975 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002976 }
2977 }
2978 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2979 output = outputOffloaded;
2980 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2981 output = outputDeepBuffer;
2982 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2983 output = outputPrimary;
2984 } else {
2985 output = outputs[0];
2986 }
2987 activeOnly = false;
2988 }
2989
2990 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002991 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002992 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2993 mMusicEffectOutput = output;
2994 }
2995
2996 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002997 return output;
2998}
2999
Eric Laurent36829f92017-04-07 19:04:42 -07003000audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3001{
3002 return selectOutputForMusicEffects();
3003}
3004
Eric Laurente0720872014-03-11 09:30:41 -07003005status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003006 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003007 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003008 int session,
3009 int id)
3010{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003011 if (session != AUDIO_SESSION_DEVICE) {
3012 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003013 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003014 index = mInputs.indexOfKey(io);
3015 if (index < 0) {
3016 ALOGW("registerEffect() unknown io %d", io);
3017 return INVALID_OPERATION;
3018 }
Eric Laurente552edb2014-03-10 17:42:56 -07003019 }
3020 }
François Gaffiec005e562018-11-06 15:04:49 +01003021 return mEffects.registerEffect(desc, io, session, id,
3022 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3023 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003024}
3025
Eric Laurentc241b0d2018-11-28 09:08:49 -08003026status_t AudioPolicyManager::unregisterEffect(int id)
3027{
3028 if (mEffects.getEffect(id) == nullptr) {
3029 return INVALID_OPERATION;
3030 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003031 if (mEffects.isEffectEnabled(id)) {
3032 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3033 setEffectEnabled(id, false);
3034 }
3035 return mEffects.unregisterEffect(id);
3036}
3037
3038status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3039{
3040 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3041 if (effect == nullptr) {
3042 return INVALID_OPERATION;
3043 }
3044
3045 status_t status = mEffects.setEffectEnabled(id, enabled);
3046 if (status == NO_ERROR) {
3047 mInputs.trackEffectEnabled(effect, enabled);
3048 }
3049 return status;
3050}
3051
Eric Laurent6c796322019-04-09 14:13:17 -07003052
3053status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3054{
3055 mEffects.moveEffects(ids, io);
3056 return NO_ERROR;
3057}
3058
Eric Laurentc75307b2015-03-17 15:29:32 -07003059bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3060{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003061 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003062}
3063
3064bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3065{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003066 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003067}
3068
Eric Laurente0720872014-03-11 09:30:41 -07003069bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003070{
3071 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003072 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003073 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003074 return true;
3075 }
3076 }
3077 return false;
3078}
3079
Eric Laurent275e8e92014-11-30 15:14:47 -08003080// Register a list of custom mixes with their attributes and format.
3081// When a mix is registered, corresponding input and output profiles are
3082// added to the remote submix hw module. The profile contains only the
3083// parameters (sampling rate, format...) specified by the mix.
3084// The corresponding input remote submix device is also connected.
3085//
3086// When a remote submix device is connected, the address is checked to select the
3087// appropriate profile and the corresponding input or output stream is opened.
3088//
3089// When capture starts, getInputForAttr() will:
3090// - 1 look for a mix matching the address passed in attribtutes tags if any
3091// - 2 if none found, getDeviceForInputSource() will:
3092// - 2.1 look for a mix matching the attributes source
3093// - 2.2 if none found, default to device selection by policy rules
3094// At this time, the corresponding output remote submix device is also connected
3095// and active playback use cases can be transferred to this mix if needed when reconnecting
3096// after AudioTracks are invalidated
3097//
3098// When playback starts, getOutputForAttr() will:
3099// - 1 look for a mix matching the address passed in attribtutes tags if any
3100// - 2 if none found, look for a mix matching the attributes usage
3101// - 3 if none found, default to device and output selection by policy rules.
3102
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003103status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003104{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003105 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3106 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003107 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003108 sp<HwModule> rSubmixModule;
3109 // examine each mix's route type
3110 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003111 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003112 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3113 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3114 ALOGE("Unsupported Policy Mix %zu of %zu: "
3115 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3116 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003117 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003118 break;
3119 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003120 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3121 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003122 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003123 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3124 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003125 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003126 rSubmixModule = mHwModules.getModuleFromName(
3127 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3128 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003129 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003130 i);
3131 res = INVALID_OPERATION;
3132 break;
3133 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003134 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003135
Eric Laurent97ac8712018-07-27 18:59:02 -07003136 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003137 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003138 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003139 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003140 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3141 } else {
3142 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3143 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003144 }
François Gaffie036e1e92015-03-19 10:16:24 +01003145
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003146 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003147 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003148 res = INVALID_OPERATION;
3149 break;
3150 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003151 audio_config_t outputConfig = mix.mFormat;
3152 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003153 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3154 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003155 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3156 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003157 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003158 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003159 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003160 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003161
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003162 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003163 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3164 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3165 ALOGE("Failed to set remote submix device available, type %u, address %s",
3166 mix.mDeviceType, address.string());
3167 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003168 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003169 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3170 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003171 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003172 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003173 i, mixes.size(), type, address.string());
3174
3175 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3176 mix.mDeviceType, mix.mDeviceAddress,
3177 String8(), AUDIO_FORMAT_DEFAULT);
3178 if (device == nullptr) {
3179 res = INVALID_OPERATION;
3180 break;
3181 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003182
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003183 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003184 // First try to find an already opened output supporting the device
3185 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003186 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003187
Eric Laurentc529cf62020-04-17 18:19:10 -07003188 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003189 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003190 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3191 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003192 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003193 } else {
3194 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003195 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003196 }
3197 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003198 // If no output found, try to find a direct output profile supporting the device
3199 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3200 sp<HwModule> module = mHwModules[i];
3201 for (size_t j = 0;
3202 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3203 j++) {
3204 sp<IOProfile> profile = module->getOutputProfiles()[j];
3205 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3206 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3207 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3208 address.string());
3209 res = INVALID_OPERATION;
3210 } else {
3211 foundOutput = true;
3212 }
3213 }
3214 }
3215 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003216 if (res != NO_ERROR) {
3217 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003218 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003219 res = INVALID_OPERATION;
3220 break;
3221 } else if (!foundOutput) {
3222 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003223 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003224 res = INVALID_OPERATION;
3225 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003226 } else {
3227 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003228 }
Eric Laurentc722f302014-12-10 11:21:49 -08003229 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003230 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003231 if (res != NO_ERROR) {
3232 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003233 } else if (checkOutputs) {
3234 checkForDeviceAndOutputChanges();
3235 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003236 }
3237 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003238}
3239
3240status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3241{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003242 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003243 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003244 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003245 sp<HwModule> rSubmixModule;
3246 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003247 for (const auto& mix : mixes) {
3248 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003249
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003250 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003251 rSubmixModule = mHwModules.getModuleFromName(
3252 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3253 if (rSubmixModule == 0) {
3254 res = INVALID_OPERATION;
3255 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003256 }
3257 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003258
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003259 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003260
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003261 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003262 res = INVALID_OPERATION;
3263 continue;
3264 }
3265
Kevin Rocard04ed0462019-05-02 17:53:24 -07003266 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3267 if (getDeviceConnectionState(device, address.string()) ==
3268 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3269 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3270 address.string(), "remote-submix",
3271 AUDIO_FORMAT_DEFAULT);
3272 if (res != OK) {
3273 ALOGE("Error making RemoteSubmix device unavailable for mix "
3274 "with type %d, address %s", device, address.string());
3275 }
3276 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003277 }
jiabin5740f082019-08-19 15:08:30 -07003278 rSubmixModule->removeOutputProfile(address.c_str());
3279 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003280
Kevin Rocard153f92d2018-12-18 18:33:28 -08003281 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003282 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003283 res = INVALID_OPERATION;
3284 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003285 } else {
3286 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003287 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003288 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003289 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003290 if (res == NO_ERROR && checkOutputs) {
3291 checkForDeviceAndOutputChanges();
3292 updateCallAndOutputRouting();
3293 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003294 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003295}
3296
Mikhail Naganov100f0122018-11-29 11:22:16 -08003297void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3298{
3299 size_t i = 0;
3300 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3301 for (const auto& fmt : mManualSurroundFormats) {
3302 if (i++ != 0) dst->append(", ");
3303 std::string sfmt;
3304 FormatConverter::toString(fmt, sfmt);
3305 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3306 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3307 }
3308}
3309
Eric Laurentc529cf62020-04-17 18:19:10 -07003310// Returns true if all devices types match the predicate and are supported by one HW module
3311bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003312 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003313 std::function<bool(audio_devices_t)> predicate,
3314 const char *context) {
3315 for (size_t i = 0; i < devices.size(); i++) {
3316 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003317 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003318 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003319 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003320 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003321 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003322 return false;
3323 }
3324 }
3325 return true;
3326}
3327
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003328status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003329 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003330 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003331 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3332 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003333 }
3334 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003335 if (res != NO_ERROR) {
3336 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3337 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003338 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003339
3340 checkForDeviceAndOutputChanges();
3341 updateCallAndOutputRouting();
3342
3343 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003344}
3345
3346status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3347 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003348 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3349 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003350 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003351 __FUNCTION__, uid);
3352 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003353 }
3354
Eric Laurentc529cf62020-04-17 18:19:10 -07003355 checkForDeviceAndOutputChanges();
3356 updateCallAndOutputRouting();
3357
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003358 return res;
3359}
3360
Eric Laurent2517af32020-11-25 15:31:27 +01003361
jiabin0a488932020-08-07 17:32:40 -07003362status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3363 device_role_t role,
3364 const AudioDeviceTypeAddrVector &devices) {
3365 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3366 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003367
Eric Laurentc529cf62020-04-17 18:19:10 -07003368 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003369 return BAD_VALUE;
3370 }
jiabin0a488932020-08-07 17:32:40 -07003371 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003372 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003373 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3374 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003375 return status;
3376 }
3377
3378 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003379
3380 bool forceVolumeReeval = false;
3381 // FIXME: workaround for truncated touch sounds
3382 // to be removed when the problem is handled by system UI
3383 uint32_t delayMs = 0;
3384 if (strategy == mCommunnicationStrategy) {
3385 forceVolumeReeval = true;
3386 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3387 updateInputRouting();
3388 }
3389 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003390
3391 return NO_ERROR;
3392}
3393
3394void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3395{
3396 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003397 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003398 // Only apply special touch sound delay once
3399 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003400 }
3401 for (size_t i = 0; i < mOutputs.size(); i++) {
3402 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3403 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3404 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3405 // As done in setDeviceConnectionState, we could also fix default device issue by
3406 // preventing the force re-routing in case of default dev that distinguishes on address.
3407 // Let's give back to engine full device choice decision however.
3408 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003409 // Only apply special touch sound delay once
3410 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003411 }
3412 if (forceVolumeReeval && !newDevices.isEmpty()) {
3413 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3414 }
3415 }
3416}
3417
Eric Laurent2517af32020-11-25 15:31:27 +01003418void AudioPolicyManager::updateInputRouting() {
3419 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303420 // Skip for hotword recording as the input device switch
3421 // is handled within sound trigger HAL
3422 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3423 continue;
3424 }
Eric Laurent2517af32020-11-25 15:31:27 +01003425 auto newDevice = getNewInputDevice(activeDesc);
3426 // Force new input selection if the new device can not be reached via current input
3427 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3428 setInputDevice(activeDesc->mIoHandle, newDevice);
3429 } else {
3430 closeInput(activeDesc->mIoHandle);
3431 }
3432 }
3433}
3434
jiabin0a488932020-08-07 17:32:40 -07003435status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3436 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003437{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003438 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003439
jiabin0a488932020-08-07 17:32:40 -07003440 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003441 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003442 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3443 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003444 return status;
3445 }
3446
3447 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003448
3449 bool forceVolumeReeval = false;
3450 // FIXME: workaround for truncated touch sounds
3451 // to be removed when the problem is handled by system UI
3452 uint32_t delayMs = 0;
3453 if (strategy == mCommunnicationStrategy) {
3454 forceVolumeReeval = true;
3455 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3456 updateInputRouting();
3457 }
3458 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003459
3460 return NO_ERROR;
3461}
3462
jiabin0a488932020-08-07 17:32:40 -07003463status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3464 device_role_t role,
3465 AudioDeviceTypeAddrVector &devices) {
3466 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003467}
3468
Jiabin Huang3b98d322020-09-03 17:54:16 +00003469status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3470 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3471 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3472 dumpAudioDeviceTypeAddrVector(devices).c_str());
3473
Mikhail Naganov55773032020-10-01 15:08:13 -07003474 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003475 return BAD_VALUE;
3476 }
3477 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3478 ALOGW_IF(status != NO_ERROR,
3479 "Engine could not set preferred devices %s for audio source %d role %d",
3480 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3481
3482 return status;
3483}
3484
3485status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3486 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3487 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3488 dumpAudioDeviceTypeAddrVector(devices).c_str());
3489
Mikhail Naganov55773032020-10-01 15:08:13 -07003490 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003491 return BAD_VALUE;
3492 }
3493 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3494 ALOGW_IF(status != NO_ERROR,
3495 "Engine could not add preferred devices %s for audio source %d role %d",
3496 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3497
Eric Laurent2517af32020-11-25 15:31:27 +01003498 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003499 return status;
3500}
3501
3502status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3503 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3504{
3505 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3506 dumpAudioDeviceTypeAddrVector(devices).c_str());
3507
Mikhail Naganov55773032020-10-01 15:08:13 -07003508 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003509 return BAD_VALUE;
3510 }
3511
3512 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3513 audioSource, role, devices);
3514 ALOGW_IF(status != NO_ERROR,
3515 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3516
Eric Laurent2517af32020-11-25 15:31:27 +01003517 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003518 return status;
3519}
3520
3521status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3522 device_role_t role) {
3523 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3524
3525 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3526 ALOGW_IF(status != NO_ERROR,
3527 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3528
Eric Laurent2517af32020-11-25 15:31:27 +01003529 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003530 return status;
3531}
3532
3533status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3534 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3535 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3536}
3537
Oscar Azucena90e77632019-11-27 17:12:28 -08003538status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003539 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003540 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003541 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3542 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003543 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003544 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3545 if (status != NO_ERROR) {
3546 ALOGE("%s() could not set device affinity for userId %d",
3547 __FUNCTION__, userId);
3548 return status;
3549 }
3550
3551 // reevaluate outputs for all devices
3552 checkForDeviceAndOutputChanges();
3553 updateCallAndOutputRouting();
3554
3555 return NO_ERROR;
3556}
3557
3558status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003559 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003560 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3561 if (status != NO_ERROR) {
3562 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3563 __FUNCTION__, userId);
3564 return status;
3565 }
3566
3567 // reevaluate outputs for all devices
3568 checkForDeviceAndOutputChanges();
3569 updateCallAndOutputRouting();
3570
3571 return NO_ERROR;
3572}
3573
Andy Hungc29d82b2018-10-05 12:23:17 -07003574void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003575{
Andy Hungc29d82b2018-10-05 12:23:17 -07003576 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3577 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003578 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003579 std::string stateLiteral;
3580 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003581 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003582 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3583 "communications", "media", "record", "dock", "system",
3584 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3585 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3586 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003587 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3588 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3589 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3590 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3591 dst->append(" (MANUAL: ");
3592 dumpManualSurroundFormats(dst);
3593 dst->append(")");
3594 }
3595 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003596 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003597 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3598 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003599 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003600 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003601
Andy Hungc29d82b2018-10-05 12:23:17 -07003602 mAvailableOutputDevices.dump(dst, String8("Available output"));
3603 mAvailableInputDevices.dump(dst, String8("Available input"));
3604 mHwModulesAll.dump(dst);
3605 mOutputs.dump(dst);
3606 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003607 mEffects.dump(dst);
3608 mAudioPatches.dump(dst);
3609 mPolicyMixes.dump(dst);
3610 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003611
Kevin Rocardb99cc752019-03-21 20:52:24 -07003612 dst->appendFormat(" AllowedCapturePolicies:\n");
3613 for (auto& policy : mAllowedCapturePolicies) {
3614 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3615 }
3616
François Gaffiec005e562018-11-06 15:04:49 +01003617 dst->appendFormat("\nPolicy Engine dump:\n");
3618 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003619}
3620
3621status_t AudioPolicyManager::dump(int fd)
3622{
3623 String8 result;
3624 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003625 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003626 return NO_ERROR;
3627}
3628
Kevin Rocardb99cc752019-03-21 20:52:24 -07003629status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3630{
3631 mAllowedCapturePolicies[uid] = capturePolicy;
3632 return NO_ERROR;
3633}
3634
Eric Laurente552edb2014-03-10 17:42:56 -07003635// This function checks for the parameters which can be offloaded.
3636// This can be enhanced depending on the capability of the DSP and policy
3637// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003638audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003639{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003640 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003641 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003642 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003643 offloadInfo.format,
3644 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3645 offloadInfo.has_video);
3646
Andy Hung2ddee192015-12-18 17:34:44 -08003647 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003648 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003649 }
3650
Eric Laurente552edb2014-03-10 17:42:56 -07003651 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003652 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003653 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3654 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003655 }
3656
3657 // Check if stream type is music, then only allow offload as of now.
3658 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3659 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003660 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3661 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003662 }
3663
3664 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003665 const bool allowOffloadWithVideo =
3666 property_get_bool("audio.offload.video", false /* default_value */);
3667 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003668 ALOGV("%s: has_video == true, returning false", __func__);
3669 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003670 }
3671
3672 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003673 const int min_duration_secs = property_get_int32(
3674 "audio.offload.min.duration.secs", -1 /* default_value */);
3675 if (min_duration_secs >= 0) {
3676 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003677 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3678 __func__, min_duration_secs);
3679 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003680 }
3681 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003682 ALOGV("%s: Offload denied by duration < default min(=%u)",
3683 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3684 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003685 }
3686
3687 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3688 // creating an offloaded track and tearing it down immediately after start when audioflinger
3689 // detects there is an active non offloadable effect.
3690 // FIXME: We should check the audio session here but we do not have it in this context.
3691 // This may prevent offloading in rare situations where effects are left active by apps
3692 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003693 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003694 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003695 }
3696
3697 // See if there is a profile to support this.
3698 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003699 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003700 offloadInfo.sample_rate,
3701 offloadInfo.format,
3702 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003703 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3704 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003705 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3706 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3707 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003708 if (profile == nullptr) {
3709 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3710 }
3711 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3712 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3713 }
3714 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003715}
3716
Michael Chana94fbb22018-04-24 14:31:19 +10003717bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3718 const audio_attributes_t& attributes) {
3719 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003720 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003721 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003722 config.sample_rate,
3723 config.format,
3724 config.channel_mask,
3725 output_flags,
3726 true /* directOnly */);
3727 ALOGV("%s() profile %sfound with name: %s, "
3728 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3729 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003730 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003731 config.sample_rate, config.format, config.channel_mask, output_flags);
3732 return (profile != 0);
3733}
3734
Eric Laurent6a94d692014-05-20 11:18:06 -07003735status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3736 audio_port_type_t type,
3737 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003738 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003739 unsigned int *generation)
3740{
jiabin19cdba52020-11-24 11:28:58 -08003741 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3742 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003743 return BAD_VALUE;
3744 }
3745 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003746 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003747 *num_ports = 0;
3748 }
3749
3750 size_t portsWritten = 0;
3751 size_t portsMax = *num_ports;
3752 *num_ports = 0;
3753 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003754 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3755 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003756 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003757 for (const auto& dev : mAvailableOutputDevices) {
3758 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003759 continue;
3760 }
3761 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003762 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003763 }
3764 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003765 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003766 }
3767 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003768 for (const auto& dev : mAvailableInputDevices) {
3769 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003770 continue;
3771 }
3772 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003773 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003774 }
3775 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003776 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003777 }
3778 }
3779 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3780 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3781 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3782 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3783 }
3784 *num_ports += mInputs.size();
3785 }
3786 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003787 size_t numOutputs = 0;
3788 for (size_t i = 0; i < mOutputs.size(); i++) {
3789 if (!mOutputs[i]->isDuplicated()) {
3790 numOutputs++;
3791 if (portsWritten < portsMax) {
3792 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3793 }
3794 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 }
Eric Laurent84c70242014-06-23 08:46:27 -07003796 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003797 }
3798 }
3799 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003800 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003801 return NO_ERROR;
3802}
3803
jiabin19cdba52020-11-24 11:28:58 -08003804status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003805{
Eric Laurent99fcae42018-05-17 16:59:18 -07003806 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3807 return BAD_VALUE;
3808 }
3809 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3810 if (dev != 0) {
3811 dev->toAudioPort(port);
3812 return NO_ERROR;
3813 }
3814 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3815 if (dev != 0) {
3816 dev->toAudioPort(port);
3817 return NO_ERROR;
3818 }
3819 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3820 if (out != 0) {
3821 out->toAudioPort(port);
3822 return NO_ERROR;
3823 }
3824 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3825 if (in != 0) {
3826 in->toAudioPort(port);
3827 return NO_ERROR;
3828 }
3829 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003830}
3831
François Gaffieafd4cea2019-11-18 15:50:22 +01003832status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3833 audio_patch_handle_t *handle,
3834 uid_t uid, uint32_t delayMs,
3835 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003836{
François Gaffieafd4cea2019-11-18 15:50:22 +01003837 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003838 if (handle == NULL || patch == NULL) {
3839 return BAD_VALUE;
3840 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003841 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003842
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003843 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003844 return BAD_VALUE;
3845 }
3846 // only one source per audio patch supported for now
3847 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003848 return INVALID_OPERATION;
3849 }
Eric Laurent874c42872014-08-08 15:13:39 -07003850
3851 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 return INVALID_OPERATION;
3853 }
Eric Laurent874c42872014-08-08 15:13:39 -07003854 for (size_t i = 0; i < patch->num_sinks; i++) {
3855 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3856 return INVALID_OPERATION;
3857 }
3858 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003859
3860 sp<AudioPatch> patchDesc;
3861 ssize_t index = mAudioPatches.indexOfKey(*handle);
3862
François Gaffieafd4cea2019-11-18 15:50:22 +01003863 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3864 patch->sources[0].role,
3865 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003866#if LOG_NDEBUG == 0
3867 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003868 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3869 patch->sinks[i].role,
3870 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003871 }
3872#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003873
3874 if (index >= 0) {
3875 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003876 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3877 __func__, mUidCached, patchDesc->getUid(), uid);
3878 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003879 return INVALID_OPERATION;
3880 }
3881 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003882 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003883 }
3884
3885 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003886 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003887 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003888 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003889 return BAD_VALUE;
3890 }
Eric Laurent84c70242014-06-23 08:46:27 -07003891 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3892 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003893 if (patchDesc != 0) {
3894 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003895 ALOGV("%s source id differs for patch current id %d new id %d",
3896 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003897 return BAD_VALUE;
3898 }
3899 }
Eric Laurent874c42872014-08-08 15:13:39 -07003900 DeviceVector devices;
3901 for (size_t i = 0; i < patch->num_sinks; i++) {
3902 // Only support mix to devices connection
3903 // TODO add support for mix to mix connection
3904 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003905 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003906 return INVALID_OPERATION;
3907 }
3908 sp<DeviceDescriptor> devDesc =
3909 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3910 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003911 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003912 return BAD_VALUE;
3913 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003914
François Gaffie11d30102018-11-02 16:09:09 +01003915 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003916 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003917 NULL, // updatedSamplingRate
3918 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003919 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003920 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003921 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003922 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003923 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003924 return INVALID_OPERATION;
3925 }
3926 devices.add(devDesc);
3927 }
3928 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003929 return INVALID_OPERATION;
3930 }
Eric Laurent874c42872014-08-08 15:13:39 -07003931
Eric Laurent6a94d692014-05-20 11:18:06 -07003932 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003933 ALOGV("%s setting device %s on output %d",
3934 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003935 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003936 index = mAudioPatches.indexOfKey(*handle);
3937 if (index >= 0) {
3938 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003939 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003940 }
3941 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003942 patchDesc->setUid(uid);
3943 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003944 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003945 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003946 return INVALID_OPERATION;
3947 }
3948 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3949 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3950 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003951 // only one sink supported when connecting an input device to a mix
3952 if (patch->num_sinks > 1) {
3953 return INVALID_OPERATION;
3954 }
François Gaffie53615e22015-03-19 09:24:12 +01003955 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003956 if (inputDesc == NULL) {
3957 return BAD_VALUE;
3958 }
3959 if (patchDesc != 0) {
3960 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3961 return BAD_VALUE;
3962 }
3963 }
François Gaffie11d30102018-11-02 16:09:09 +01003964 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003965 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003966 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003967 return BAD_VALUE;
3968 }
3969
François Gaffie11d30102018-11-02 16:09:09 +01003970 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003971 patch->sinks[0].sample_rate,
3972 NULL, /*updatedSampleRate*/
3973 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003974 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003975 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003976 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003977 // FIXME for the parameter type,
3978 // and the NONE
3979 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003980 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003981 return INVALID_OPERATION;
3982 }
3983 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003984 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003985 device->toString().c_str(), inputDesc->mIoHandle);
3986 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003987 index = mAudioPatches.indexOfKey(*handle);
3988 if (index >= 0) {
3989 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003990 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003991 }
3992 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003993 patchDesc->setUid(uid);
3994 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003996 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003997 return INVALID_OPERATION;
3998 }
3999 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4000 // device to device connection
4001 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004002 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004003 return BAD_VALUE;
4004 }
4005 }
François Gaffie11d30102018-11-02 16:09:09 +01004006 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004007 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004008 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004009 return BAD_VALUE;
4010 }
Eric Laurent874c42872014-08-08 15:13:39 -07004011
Eric Laurent6a94d692014-05-20 11:18:06 -07004012 //update source and sink with our own data as the data passed in the patch may
4013 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004014 PatchBuilder patchBuilder;
4015 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004016
4017 // if first sink is to MSD, establish single MSD patch
4018 if (getMsdAudioOutDevices().contains(
4019 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4020 ALOGV("%s patching to MSD", __FUNCTION__);
4021 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4022 goto installPatch;
4023 }
4024
François Gaffieafd4cea2019-11-18 15:50:22 +01004025 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4026 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004027
Eric Laurent874c42872014-08-08 15:13:39 -07004028 for (size_t i = 0; i < patch->num_sinks; i++) {
4029 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004030 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004031 return INVALID_OPERATION;
4032 }
François Gaffie11d30102018-11-02 16:09:09 +01004033 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004034 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004035 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004036 return BAD_VALUE;
4037 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004038 audio_port_config sinkPortConfig = {};
4039 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4040 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004041
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004042 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4043 // volume management purpose (tracking activity)
4044 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4045 // in config XML to reach the sink so that is can be declared as available.
4046 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4047 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4048 if (sourceDesc != nullptr) {
4049 // take care of dynamic routing for SwOutput selection,
4050 audio_attributes_t attributes = sourceDesc->attributes();
4051 audio_stream_type_t stream = sourceDesc->stream();
4052 audio_attributes_t resultAttr;
4053 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4054 config.sample_rate = sourceDesc->config().sample_rate;
4055 config.channel_mask = sourceDesc->config().channel_mask;
4056 config.format = sourceDesc->config().format;
4057 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4058 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4059 bool isRequestedDeviceForExclusiveUse = false;
4060 output_type_t outputType;
4061 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4062 &stream, sourceDesc->uid(), &config, &flags,
4063 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4064 nullptr, &outputType);
4065 if (output == AUDIO_IO_HANDLE_NONE) {
4066 ALOGV("%s no output for device %s",
4067 __FUNCTION__, sinkDevice->toString().c_str());
4068 return INVALID_OPERATION;
4069 }
4070 outputDesc = mOutputs.valueFor(output);
4071 if (outputDesc->isDuplicated()) {
4072 ALOGE("%s output is duplicated", __func__);
4073 return INVALID_OPERATION;
4074 }
4075 sourceDesc->setSwOutput(outputDesc);
4076 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004077 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004078 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004079 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004080 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004081 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4082 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004083 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4084 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004085 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4086 (sourceDesc != nullptr &&
4087 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004088 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004089 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004090 return INVALID_OPERATION;
4091 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004092 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004093 SortedVector<audio_io_handle_t> outputs =
4094 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4095 // if the sink device is reachable via an opened output stream, request to
4096 // go via this output stream by adding a second source to the patch
4097 // description
4098 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004099 if (output != AUDIO_IO_HANDLE_NONE) {
4100 outputDesc = mOutputs.valueFor(output);
4101 if (outputDesc->isDuplicated()) {
4102 ALOGV("%s output for device %s is duplicated",
4103 __FUNCTION__, sinkDevice->toString().c_str());
4104 return INVALID_OPERATION;
4105 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004106 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004107 }
4108 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004109 audio_port_config srcMixPortConfig = {};
4110 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004111 // for volume control, we may need a valid stream
4112 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4113 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4114 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004115 }
Eric Laurent83b88082014-06-20 18:31:16 -07004116 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004117 }
4118 // TODO: check from routing capabilities in config file and other conflicting patches
4119
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004120installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004121 status_t status = installPatch(
4122 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004123 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004124 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004125 return INVALID_OPERATION;
4126 }
4127 } else {
4128 return BAD_VALUE;
4129 }
4130 } else {
4131 return BAD_VALUE;
4132 }
4133 return NO_ERROR;
4134}
4135
4136status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4137 uid_t uid)
4138{
4139 ALOGV("releaseAudioPatch() patch %d", handle);
4140
4141 ssize_t index = mAudioPatches.indexOfKey(handle);
4142
4143 if (index < 0) {
4144 return BAD_VALUE;
4145 }
4146 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004147 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4148 __func__, mUidCached, patchDesc->getUid(), uid);
4149 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004150 return INVALID_OPERATION;
4151 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004152 return releaseAudioPatchInternal(handle);
4153}
Eric Laurent6a94d692014-05-20 11:18:06 -07004154
François Gaffieafd4cea2019-11-18 15:50:22 +01004155status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4156 uint32_t delayMs)
4157{
4158 ALOGV("%s patch %d", __func__, handle);
4159 if (mAudioPatches.indexOfKey(handle) < 0) {
4160 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4161 return BAD_VALUE;
4162 }
4163 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004164 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004165 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004166 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004167 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004168 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004169 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004170 return BAD_VALUE;
4171 }
4172
François Gaffie11d30102018-11-02 16:09:09 +01004173 setOutputDevices(outputDesc,
4174 getNewOutputDevices(outputDesc, true /*fromCache*/),
4175 true,
4176 0,
4177 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004178 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4179 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004180 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004181 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004182 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004183 return BAD_VALUE;
4184 }
4185 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004186 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 true,
4188 NULL);
4189 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004190 status_t status =
4191 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4192 ALOGV("%s patch panel returned %d patchHandle %d",
4193 __func__, status, patchDesc->getAfHandle());
4194 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004195 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004196 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004197 // SW Bridge
4198 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4199 sp<SwAudioOutputDescriptor> outputDesc =
4200 mOutputs.getOutputFromId(patch->sources[1].id);
4201 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004202 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4203 // releaseOutput has already called closeOuput in case of direct output
4204 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004205 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004206 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4207 // force SwOutput patch removal as AF counter part patch has already gone.
4208 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4209 removeAudioPatch(outputDesc->getPatchHandle());
4210 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004211 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4212 setOutputDevices(outputDesc,
4213 getNewOutputDevices(outputDesc, true /*fromCache*/),
4214 true, /*force*/
4215 0,
4216 NULL);
4217 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004218 } else {
4219 return BAD_VALUE;
4220 }
4221 } else {
4222 return BAD_VALUE;
4223 }
4224 return NO_ERROR;
4225}
4226
4227status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4228 struct audio_patch *patches,
4229 unsigned int *generation)
4230{
François Gaffie53615e22015-03-19 09:24:12 +01004231 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004232 return BAD_VALUE;
4233 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004234 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004235 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004236}
4237
Eric Laurente1715a42014-05-20 11:30:42 -07004238status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004239{
Eric Laurente1715a42014-05-20 11:30:42 -07004240 ALOGV("setAudioPortConfig()");
4241
4242 if (config == NULL) {
4243 return BAD_VALUE;
4244 }
4245 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4246 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004247 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4248 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004249 }
4250
Eric Laurenta121f902014-06-03 13:32:54 -07004251 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004252 if (config->type == AUDIO_PORT_TYPE_MIX) {
4253 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004254 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004255 if (outputDesc == NULL) {
4256 return BAD_VALUE;
4257 }
Eric Laurent84c70242014-06-23 08:46:27 -07004258 ALOG_ASSERT(!outputDesc->isDuplicated(),
4259 "setAudioPortConfig() called on duplicated output %d",
4260 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004261 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004262 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004263 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004264 if (inputDesc == NULL) {
4265 return BAD_VALUE;
4266 }
Eric Laurenta121f902014-06-03 13:32:54 -07004267 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004268 } else {
4269 return BAD_VALUE;
4270 }
4271 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4272 sp<DeviceDescriptor> deviceDesc;
4273 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4274 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4275 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4276 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4277 } else {
4278 return BAD_VALUE;
4279 }
4280 if (deviceDesc == NULL) {
4281 return BAD_VALUE;
4282 }
Eric Laurenta121f902014-06-03 13:32:54 -07004283 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004284 } else {
4285 return BAD_VALUE;
4286 }
4287
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004288 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004289 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4290 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004291 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004292 audioPortConfig->toAudioPortConfig(&newConfig, config);
4293 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004294 }
Eric Laurenta121f902014-06-03 13:32:54 -07004295 if (status != NO_ERROR) {
4296 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004297 }
Eric Laurente1715a42014-05-20 11:30:42 -07004298
4299 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004300}
4301
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004302void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4303{
Eric Laurentd60560a2015-04-10 11:31:20 -07004304 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004305 clearAudioPatches(uid);
4306 clearSessionRoutes(uid);
4307}
4308
Eric Laurent6a94d692014-05-20 11:18:06 -07004309void AudioPolicyManager::clearAudioPatches(uid_t uid)
4310{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004311 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004312 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004313 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004314 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004315 }
4316 }
4317}
4318
François Gaffiec005e562018-11-06 15:04:49 +01004319void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004320{
François Gaffiec005e562018-11-06 15:04:49 +01004321 // Take the first attributes following the product strategy as it is used to retrieve the routed
4322 // device. All attributes wihin a strategy follows the same "routing strategy"
4323 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4324 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004325 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004326 for (size_t j = 0; j < mOutputs.size(); j++) {
4327 if (mOutputs.keyAt(j) == ouptutToSkip) {
4328 continue;
4329 }
4330 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004331 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004332 continue;
4333 }
4334 // If the default device for this strategy is on another output mix,
4335 // invalidate all tracks in this strategy to force re connection.
4336 // Otherwise select new device on the output mix.
4337 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004338 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4339 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004340 }
4341 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004342 setOutputDevices(
4343 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004344 }
4345 }
4346}
4347
4348void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4349{
4350 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004351 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004352 for (size_t i = 0; i < mOutputs.size(); i++) {
4353 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004354 for (const auto& client : outputDesc->getClientIterable()) {
4355 if (client->hasPreferredDevice() && client->uid() == uid) {
4356 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004357 auto clientStrategy = client->strategy();
4358 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4359 end(affectedStrategies)) {
4360 continue;
4361 }
4362 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004363 }
4364 }
4365 }
4366 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004367 for (const auto& strategy : affectedStrategies) {
4368 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004369 }
4370
4371 // remove input routes associated with this uid
4372 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004373 for (size_t i = 0; i < mInputs.size(); i++) {
4374 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004375 for (const auto& client : inputDesc->getClientIterable()) {
4376 if (client->hasPreferredDevice() && client->uid() == uid) {
4377 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4378 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004379 }
4380 }
4381 }
4382 // reroute inputs if necessary
4383 SortedVector<audio_io_handle_t> inputsToClose;
4384 for (size_t i = 0; i < mInputs.size(); i++) {
4385 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004386 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004387 inputsToClose.add(inputDesc->mIoHandle);
4388 }
4389 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004390 for (const auto& input : inputsToClose) {
4391 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004392 }
4393}
4394
Eric Laurentd60560a2015-04-10 11:31:20 -07004395void AudioPolicyManager::clearAudioSources(uid_t uid)
4396{
4397 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004398 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4399 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004400 stopAudioSource(mAudioSources.keyAt(i));
4401 }
4402 }
4403}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004404
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004405status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4406 audio_io_handle_t *ioHandle,
4407 audio_devices_t *device)
4408{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004409 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4410 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004411 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004412 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004413
François Gaffiedf372692015-03-19 10:43:27 +01004414 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004415}
4416
Eric Laurentd60560a2015-04-10 11:31:20 -07004417status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004418 const audio_attributes_t *attributes,
4419 audio_port_handle_t *portId,
4420 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004421{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004422 ALOGV("%s", __FUNCTION__);
4423 *portId = AUDIO_PORT_HANDLE_NONE;
4424
4425 if (source == NULL || attributes == NULL || portId == NULL) {
4426 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4427 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004428 return BAD_VALUE;
4429 }
4430
Eric Laurentd60560a2015-04-10 11:31:20 -07004431 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4432 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004433 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4434 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004435 return INVALID_OPERATION;
4436 }
4437
François Gaffie11d30102018-11-02 16:09:09 +01004438 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004439 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004440 String8(source->ext.device.address),
4441 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004442 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004443 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004444 return BAD_VALUE;
4445 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004446
jiabin4ef93452019-09-10 14:29:54 -07004447 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004448
François Gaffieaaac0fd2018-11-22 17:56:39 +01004449 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004451 mEngine->getStreamTypeForAttributes(*attributes),
4452 mEngine->getProductStrategyForAttributes(*attributes),
4453 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004454
4455 status_t status = connectAudioSource(sourceDesc);
4456 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004457 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004458 }
4459 return status;
4460}
4461
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004462status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004463{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004464 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004465
4466 // make sure we only have one patch per source.
4467 disconnectAudioSource(sourceDesc);
4468
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004469 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004470 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4471 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4472 sourceDesc->srcDevice()->type(),
4473 String8(sourceDesc->srcDevice()->address().c_str()),
4474 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004475 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004476 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004477 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004478 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004479 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4480 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4481 return INVALID_OPERATION;
4482 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004483 PatchBuilder patchBuilder;
4484 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4485 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4486 status_t status =
4487 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4488 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4489 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4490 return INVALID_OPERATION;
4491 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004492 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004493 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4494 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4495 if (swOutput != 0) {
4496 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004497 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004498 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004499 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004500 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004501 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004502 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004503 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004504 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004505 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004506 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004507 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004508 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4509 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004510 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004511 if (delayMs != 0) {
4512 usleep(delayMs * 1000);
4513 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004514 } else {
4515 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4516 if (hwOutputDesc != 0) {
4517 // create Hwoutput and add to mHwOutputs
4518 } else {
4519 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4520 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004521 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004522 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004523
4524FailureSourceActive:
4525 swOutput->stop();
4526 releaseOutput(sourceDesc->portId());
4527FailureSourceAdded:
4528 sourceDesc->setSwOutput(nullptr);
4529FailureReleasePatch:
4530 releaseAudioPatchInternal(handle);
4531 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004532}
4533
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004534status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004535{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004536 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4537 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004538 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004539 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004540 return BAD_VALUE;
4541 }
4542 status_t status = disconnectAudioSource(sourceDesc);
4543
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004544 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004545 return status;
4546}
4547
Andy Hung2ddee192015-12-18 17:34:44 -08004548status_t AudioPolicyManager::setMasterMono(bool mono)
4549{
4550 if (mMasterMono == mono) {
4551 return NO_ERROR;
4552 }
4553 mMasterMono = mono;
4554 // if enabling mono we close all offloaded devices, which will invalidate the
4555 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4556 // for recreating the new AudioTrack as non-offloaded PCM.
4557 //
4558 // If disabling mono, we leave all tracks as is: we don't know which clients
4559 // and tracks are able to be recreated as offloaded. The next "song" should
4560 // play back offloaded.
4561 if (mMasterMono) {
4562 Vector<audio_io_handle_t> offloaded;
4563 for (size_t i = 0; i < mOutputs.size(); ++i) {
4564 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4565 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4566 offloaded.push(desc->mIoHandle);
4567 }
4568 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004569 for (const auto& handle : offloaded) {
4570 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004571 }
4572 }
4573 // update master mono for all remaining outputs
4574 for (size_t i = 0; i < mOutputs.size(); ++i) {
4575 updateMono(mOutputs.keyAt(i));
4576 }
4577 return NO_ERROR;
4578}
4579
4580status_t AudioPolicyManager::getMasterMono(bool *mono)
4581{
4582 *mono = mMasterMono;
4583 return NO_ERROR;
4584}
4585
Eric Laurentac9cef52017-06-09 15:46:26 -07004586float AudioPolicyManager::getStreamVolumeDB(
4587 audio_stream_type_t stream, int index, audio_devices_t device)
4588{
jiabin9a3361e2019-10-01 09:38:30 -07004589 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004590}
4591
jiabin81772902018-04-02 17:52:27 -07004592status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4593 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004594 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004595{
Kriti Dang6537def2021-03-02 13:46:59 +01004596 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4597 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004598 return BAD_VALUE;
4599 }
Kriti Dang6537def2021-03-02 13:46:59 +01004600 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4601 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004602
4603 size_t formatsWritten = 0;
4604 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004605
Kriti Dang6537def2021-03-02 13:46:59 +01004606 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004607 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4608 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004609 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004610 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004611 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004612 bool formatEnabled = true;
4613 switch (forceUse) {
4614 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004615 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004616 break;
4617 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4618 formatEnabled = false;
4619 break;
4620 default: // AUTO or ALWAYS => true
4621 break;
jiabin81772902018-04-02 17:52:27 -07004622 }
4623 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4624 }
jiabin81772902018-04-02 17:52:27 -07004625 }
4626 return NO_ERROR;
4627}
4628
Kriti Dang6537def2021-03-02 13:46:59 +01004629status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4630 audio_format_t *surroundFormats) {
4631 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4632 return BAD_VALUE;
4633 }
4634 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4635 __func__, *numSurroundFormats, surroundFormats);
4636
4637 size_t formatsWritten = 0;
4638 size_t formatsMax = *numSurroundFormats;
4639 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4640
4641 // Return formats from all device profiles that have already been resolved by
4642 // checkOutputsForDevice().
4643 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4644 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4645 audio_devices_t deviceType = device->type();
4646 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4647 // returns formats reported by HDMI devices.
4648 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4649 continue;
4650 }
4651 // Formats reported by sink devices
4652 std::unordered_set<audio_format_t> formatset;
4653 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4654 formatset.insert(it->second.begin(), it->second.end());
4655 }
4656
4657 // Formats hard-coded in the in policy configuration file (if any).
4658 FormatVector encodedFormats = device->encodedFormats();
4659 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4660 // Filter the formats which are supported by the vendor hardware.
4661 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4662 if (mConfig.getSurroundFormats().count(*it) != 0) {
4663 formats.insert(*it);
4664 } else {
4665 for (const auto& pair : mConfig.getSurroundFormats()) {
4666 if (pair.second.count(*it) != 0) {
4667 formats.insert(pair.first);
4668 break;
4669 }
4670 }
4671 }
4672 }
4673 }
4674 *numSurroundFormats = formats.size();
4675 for (const auto& format: formats) {
4676 if (formatsWritten < formatsMax) {
4677 surroundFormats[formatsWritten++] = format;
4678 }
4679 }
4680 return NO_ERROR;
4681}
4682
jiabin81772902018-04-02 17:52:27 -07004683status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4684{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004685 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004686 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4687 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004688 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004689 return BAD_VALUE;
4690 }
4691
Mikhail Naganov100f0122018-11-29 11:22:16 -08004692 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4693 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004694 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004695 return INVALID_OPERATION;
4696 }
4697
Mikhail Naganov100f0122018-11-29 11:22:16 -08004698 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004699 return NO_ERROR;
4700 }
4701
Mikhail Naganov100f0122018-11-29 11:22:16 -08004702 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004703 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004704 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004705 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004706 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004707 }
4708 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004709 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004710 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004711 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004712 }
4713 }
4714
4715 sp<SwAudioOutputDescriptor> outputDesc;
4716 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004717 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4718 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004719 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4720 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004721 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004722 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004723 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4724 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4725 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004726 name.c_str(),
4727 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004728 if (status != NO_ERROR) {
4729 continue;
4730 }
4731 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4732 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4733 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004734 name.c_str(),
4735 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004736 profileUpdated |= (status == NO_ERROR);
4737 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004738 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004739 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004740 AUDIO_DEVICE_IN_HDMI);
4741 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4742 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004743 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004744 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004745 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4746 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4747 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004748 name.c_str(),
4749 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004750 if (status != NO_ERROR) {
4751 continue;
4752 }
4753 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4754 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4755 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004756 name.c_str(),
4757 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004758 profileUpdated |= (status == NO_ERROR);
4759 }
4760
jiabin81772902018-04-02 17:52:27 -07004761 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004762 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004763 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004764 }
4765
4766 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4767}
4768
Eric Laurent5ada82e2019-08-29 17:53:54 -07004769void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004770{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004771 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004772 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004773 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004774 }
4775}
4776
jiabin6012f912018-11-02 17:06:30 -07004777bool AudioPolicyManager::isHapticPlaybackSupported()
4778{
4779 for (const auto& hwModule : mHwModules) {
4780 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4781 for (const auto &outProfile : outputProfiles) {
4782 struct audio_port audioPort;
4783 outProfile->toAudioPort(&audioPort);
4784 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4785 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4786 return true;
4787 }
4788 }
4789 }
4790 }
4791 return false;
4792}
4793
Eric Laurent8340e672019-11-06 11:01:08 -08004794bool AudioPolicyManager::isCallScreenModeSupported()
4795{
4796 return getConfig().isCallScreenModeSupported();
4797}
4798
4799
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004800status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004801{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004802 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004803 if (!sourceDesc->isConnected()) {
4804 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4805 return NO_ERROR;
4806 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004807 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4808 if (swOutput != 0) {
4809 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004810 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004811 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004812 }
jiabinbce0c1d2020-10-05 11:20:18 -07004813 if (releaseOutput(sourceDesc->portId())) {
4814 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4815 // no need to release audio patch here but just return NO_ERROR.
4816 return NO_ERROR;
4817 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004818 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004819 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004820 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004821 // close Hwoutput and remove from mHwOutputs
4822 } else {
4823 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4824 }
4825 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004826 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4827 sourceDesc->disconnect();
4828 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004829}
4830
François Gaffiec005e562018-11-06 15:04:49 +01004831sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4832 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004833{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004834 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004835 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004836 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004837 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004838 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4839 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004840 source = sourceDesc;
4841 break;
4842 }
4843 }
4844 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004845}
4846
Eric Laurentfa0f6742021-08-17 18:39:44 +02004847bool AudioPolicyManager::canBeSpatialized(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004848 const audio_config_t *config,
4849 const AudioDeviceTypeAddrVector &devices) const
4850{
4851 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
4852 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004853 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004854 // and game usages.
4855 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER &&
4856 attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
4857 return false;
4858 }
4859
4860 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02004861 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
4862 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004863 // to the specified devices must exist.
4864 sp<IOProfile> profile =
Eric Laurentfa0f6742021-08-17 18:39:44 +02004865 getSpatializerOutputProfile(config, devices, false /*forOpening*/);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004866 if (profile == nullptr) {
4867 return false;
4868 }
4869
4870 // The caller can have the audio config criteria ignored by either passing a null ptr or
4871 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004872 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004873 // 5.1, 7.1and 7.1.4 audio.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004874 // If the spatializer output is already opened, only channel masks included in the
4875 // spatializer output mixer channel mask are allowed.
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004876 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
4877 if (config->channel_mask != AUDIO_CHANNEL_OUT_5POINT1
4878 && config->channel_mask != AUDIO_CHANNEL_OUT_7POINT1
4879 && config->channel_mask != AUDIO_CHANNEL_OUT_7POINT1POINT4) {
4880 return false;
4881 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004882 if (mSpatializerOutput != nullptr) {
4883 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004884 != config->channel_mask) {
4885 return false;
4886 }
4887 }
4888 }
4889
4890 return true;
4891}
4892
4893void AudioPolicyManager::checkVirtualizerClientRoutes() {
4894 std::set<audio_stream_type_t> streamsToInvalidate;
4895 for (size_t i = 0; i < mOutputs.size(); i++) {
4896 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
4897 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
4898 audio_attributes_t attr = client->attributes();
4899 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
4900 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4901 audio_config_base_t clientConfig = client->config();
4902 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurentfa0f6742021-08-17 18:39:44 +02004903 if (canBeSpatialized(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004904 streamsToInvalidate.insert(client->stream());
4905 }
4906 }
4907 }
4908
4909 for (audio_stream_type_t stream : streamsToInvalidate) {
4910 mpClientInterface->invalidateStream(stream);
4911 }
4912}
4913
Eric Laurentfa0f6742021-08-17 18:39:44 +02004914status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004915 const audio_attributes_t *attr,
4916 audio_io_handle_t *output) {
4917 *output = AUDIO_IO_HANDLE_NONE;
4918
Eric Laurentfa0f6742021-08-17 18:39:44 +02004919 if (mSpatializerOutput != nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004920 return INVALID_OPERATION;
4921 }
4922
4923 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
4924 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4925 audio_config_t *configPtr = nullptr;
4926 audio_config_t config;
4927 if (mixerConfig != nullptr) {
4928 config = audio_config_initializer(mixerConfig);
4929 configPtr = &config;
4930 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004931 if (!canBeSpatialized(attr, configPtr, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004932 return BAD_VALUE;
4933 }
4934
4935 sp<IOProfile> profile =
Eric Laurentfa0f6742021-08-17 18:39:44 +02004936 getSpatializerOutputProfile(configPtr, devicesTypeAddress, true /*forOpening*/);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004937 if (profile == nullptr) {
4938 return BAD_VALUE;
4939 }
4940
Eric Laurentfa0f6742021-08-17 18:39:44 +02004941 mSpatializerOutput = new SwAudioOutputDescriptor(profile, mpClientInterface);
4942 status_t status = mSpatializerOutput->open(nullptr, mixerConfig, devices,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004943 mEngine->getStreamTypeForAttributes(*attr),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02004944 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004945 if (status != NO_ERROR) {
4946 ALOGV("%s failed opening output: status %d, output %d", __func__, status, *output);
4947 if (*output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02004948 mSpatializerOutput->close();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004949 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004950 mSpatializerOutput.clear();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004951 *output = AUDIO_IO_HANDLE_NONE;
4952 return status;
4953 }
4954
4955 checkVirtualizerClientRoutes();
4956
Eric Laurentfa0f6742021-08-17 18:39:44 +02004957 addOutput(*output, mSpatializerOutput);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004958 mPreviousOutputs = mOutputs;
4959 mpClientInterface->onAudioPortListUpdate();
4960
Eric Laurentfa0f6742021-08-17 18:39:44 +02004961 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004962 return NO_ERROR;
4963}
4964
Eric Laurentfa0f6742021-08-17 18:39:44 +02004965status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
4966 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004967 return INVALID_OPERATION;
4968 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004969 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004970 return BAD_VALUE;
4971 }
4972 closeOutput(output);
Eric Laurentfa0f6742021-08-17 18:39:44 +02004973 mSpatializerOutput.clear();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004974 return NO_ERROR;
4975}
4976
Eric Laurente552edb2014-03-10 17:42:56 -07004977// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004978// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004979// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004980uint32_t AudioPolicyManager::nextAudioPortGeneration()
4981{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004982 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004983}
4984
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004985static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004986 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4987 !audioPolicyXmlConfigFile.empty()) {
4988 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4989 if (ret == NO_ERROR) {
4990 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004991 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004992 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004993 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004994 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004995}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004996
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004997AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4998 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004999 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005000 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005001 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005002 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005003 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005004 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005005 mAudioPortGeneration(1),
5006 mBeaconMuteRefCount(0),
5007 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005008 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005009 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005010 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005011 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005012{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005013}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005014
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005015AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5016 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5017{
5018 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005019}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005020
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005021void AudioPolicyManager::loadConfig() {
5022 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005023 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005024 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005025 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005026 //TODO: b/193496180 use spatializer flag at audio HAL when available
5027 getConfig().convertSpatializerFlag();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005028}
5029
5030status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005031 {
5032 auto engLib = EngineLibrary::load(
5033 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5034 if (!engLib) {
5035 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5036 return NO_INIT;
5037 }
5038 mEngine = engLib->createEngine();
5039 if (mEngine == nullptr) {
5040 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5041 return NO_INIT;
5042 }
François Gaffie2110e042015-03-24 08:41:51 +01005043 }
5044 mEngine->setObserver(this);
5045 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005046 if (status != NO_ERROR) {
5047 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5048 return status;
5049 }
François Gaffie2110e042015-03-24 08:41:51 +01005050
Eric Laurent1d69c872021-01-11 18:53:01 +01005051 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5052 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5053
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005054 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005055 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005056 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005057
Eric Laurent3a4311c2014-03-17 12:00:47 -07005058 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005059 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5060 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5061 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005062 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005063 }
jiabin9ff780e2018-03-19 18:19:52 -07005064 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005065 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005066 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005067 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005068 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005069 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005070 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005071 }
5072 }
5073 }
Eric Laurente552edb2014-03-10 17:42:56 -07005074
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005075 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005076
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005077 // Silence ALOGV statements
5078 property_set("log.tag." LOG_TAG, "D");
5079
Eric Laurente552edb2014-03-10 17:42:56 -07005080 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005081 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005082}
5083
Eric Laurente0720872014-03-11 09:30:41 -07005084AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005085{
Eric Laurente552edb2014-03-10 17:42:56 -07005086 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005087 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005088 }
5089 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005090 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005091 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005092 mAvailableOutputDevices.clear();
5093 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005094 mOutputs.clear();
5095 mInputs.clear();
5096 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005097 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005098 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005099}
5100
Eric Laurente0720872014-03-11 09:30:41 -07005101status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005102{
Eric Laurent87ffa392015-05-22 10:32:38 -07005103 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005104}
5105
Eric Laurente552edb2014-03-10 17:42:56 -07005106// ---
5107
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005108void AudioPolicyManager::onNewAudioModulesAvailable()
5109{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005110 DeviceVector newDevices;
5111 onNewAudioModulesAvailableInt(&newDevices);
5112 if (!newDevices.empty()) {
5113 nextAudioPortGeneration();
5114 mpClientInterface->onAudioPortListUpdate();
5115 }
5116}
5117
5118void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5119{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005120 for (const auto& hwModule : mHwModulesAll) {
5121 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5122 continue;
5123 }
5124 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5125 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5126 ALOGW("could not open HW module %s", hwModule->getName());
5127 continue;
5128 }
5129 mHwModules.push_back(hwModule);
5130 // open all output streams needed to access attached devices
5131 // except for direct output streams that are only opened when they are actually
5132 // required by an app.
5133 // This also validates mAvailableOutputDevices list
5134 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5135 if (!outProfile->canOpenNewIo()) {
5136 ALOGE("Invalid Output profile max open count %u for profile %s",
5137 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5138 continue;
5139 }
5140 if (!outProfile->hasSupportedDevices()) {
5141 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5142 continue;
5143 }
5144 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
5145 mTtsOutputAvailable = true;
5146 }
5147
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005148 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5149 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5150 sp<DeviceDescriptor> supportedDevice = 0;
5151 if (supportedDevices.contains(mDefaultOutputDevice)) {
5152 supportedDevice = mDefaultOutputDevice;
5153 } else {
5154 // choose first device present in profile's SupportedDevices also part of
5155 // mAvailableOutputDevices.
5156 if (availProfileDevices.isEmpty()) {
5157 continue;
5158 }
5159 supportedDevice = availProfileDevices.itemAt(0);
5160 }
5161 if (!mOutputDevicesAll.contains(supportedDevice)) {
5162 continue;
5163 }
5164 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5165 mpClientInterface);
5166 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005167 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5168 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005169 AUDIO_STREAM_DEFAULT,
5170 AUDIO_OUTPUT_FLAG_NONE, &output);
5171 if (status != NO_ERROR) {
5172 ALOGW("Cannot open output stream for devices %s on hw module %s",
5173 supportedDevice->toString().c_str(), hwModule->getName());
5174 continue;
5175 }
5176 for (const auto &device : availProfileDevices) {
5177 // give a valid ID to an attached device once confirmed it is reachable
5178 if (!device->isAttached()) {
5179 device->attach(hwModule);
5180 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005181 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005182 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005183 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5184 }
5185 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005186 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005187 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5188 mPrimaryOutput = outputDesc;
5189 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005190 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0
Eric Laurent1c5e2e32021-08-18 18:50:28 +02005191 || (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0 ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005192 outputDesc->close();
5193 } else {
5194 addOutput(output, outputDesc);
5195 setOutputDevices(outputDesc,
5196 DeviceVector(supportedDevice),
5197 true,
5198 0,
5199 NULL);
5200 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005201 }
5202 // open input streams needed to access attached devices to validate
5203 // mAvailableInputDevices list
5204 for (const auto& inProfile : hwModule->getInputProfiles()) {
5205 if (!inProfile->canOpenNewIo()) {
5206 ALOGE("Invalid Input profile max open count %u for profile %s",
5207 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5208 continue;
5209 }
5210 if (!inProfile->hasSupportedDevices()) {
5211 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5212 continue;
5213 }
5214 // chose first device present in profile's SupportedDevices also part of
5215 // available input devices
5216 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5217 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5218 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005219 ALOGV("%s: Input device list is empty! for profile %s",
5220 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005221 continue;
5222 }
5223 sp<AudioInputDescriptor> inputDesc =
5224 new AudioInputDescriptor(inProfile, mpClientInterface);
5225
5226 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5227 status_t status = inputDesc->open(nullptr,
5228 availProfileDevices.itemAt(0),
5229 AUDIO_SOURCE_MIC,
5230 AUDIO_INPUT_FLAG_NONE,
5231 &input);
5232 if (status != NO_ERROR) {
5233 ALOGW("Cannot open input stream for device %s on hw module %s",
5234 availProfileDevices.toString().c_str(),
5235 hwModule->getName());
5236 continue;
5237 }
5238 for (const auto &device : availProfileDevices) {
5239 // give a valid ID to an attached device once confirmed it is reachable
5240 if (!device->isAttached()) {
5241 device->attach(hwModule);
5242 device->importAudioPortAndPickAudioProfile(inProfile, true);
5243 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005244 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005245 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5246 }
5247 }
5248 inputDesc->close();
5249 }
5250 }
5251}
5252
Eric Laurent98e38192018-02-15 18:31:53 -08005253void AudioPolicyManager::addOutput(audio_io_handle_t output,
5254 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005255{
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005257 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005258 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005259 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005260 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005261}
5262
François Gaffie53615e22015-03-19 09:24:12 +01005263void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5264{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005265 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5266 ALOGV("%s: removing primary output", __func__);
5267 mPrimaryOutput = nullptr;
5268 }
François Gaffie53615e22015-03-19 09:24:12 +01005269 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005270 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005271}
5272
Eric Laurent98e38192018-02-15 18:31:53 -08005273void AudioPolicyManager::addInput(audio_io_handle_t input,
5274 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005275{
Eric Laurent1c333e22014-05-20 10:48:17 -07005276 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005278}
Eric Laurente552edb2014-03-10 17:42:56 -07005279
François Gaffie11d30102018-11-02 16:09:09 +01005280status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005281 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005282 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005283{
François Gaffie11d30102018-11-02 16:09:09 +01005284 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005285 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005286 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005287
François Gaffie11d30102018-11-02 16:09:09 +01005288 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005289 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005290 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005291 }
Eric Laurente552edb2014-03-10 17:42:56 -07005292
Eric Laurent3b73df72014-03-11 09:06:29 -07005293 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005294 // first call getAudioPort to get the supported attributes from the HAL
5295 struct audio_port_v7 port = {};
5296 device->toAudioPort(&port);
5297 status_t status = mpClientInterface->getAudioPort(&port);
5298 if (status == NO_ERROR) {
5299 device->importAudioPort(port);
5300 }
5301
5302 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005303 for (size_t i = 0; i < mOutputs.size(); i++) {
5304 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005305 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005306 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005307 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5308 mOutputs.keyAt(i), device->toString().c_str());
5309 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005310 }
5311 }
5312 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005314 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005315 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5316 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005317 if (profile->supportsDevice(device)) {
5318 profiles.add(profile);
5319 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5320 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005321 }
5322 }
5323 }
5324
Eric Laurent7b279bb2015-12-14 10:18:23 -08005325 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005326
Eric Laurente552edb2014-03-10 17:42:56 -07005327 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005328 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005329 return BAD_VALUE;
5330 }
5331
5332 // open outputs for matching profiles if needed. Direct outputs are also opened to
5333 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5334 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005335 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005336
5337 // nothing to do if one output is already opened for this profile
5338 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005339 for (j = 0; j < outputs.size(); j++) {
5340 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005341 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005342 // matching profile: save the sample rates, format and channel masks supported
5343 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005344 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005345 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005346 }
Eric Laurente552edb2014-03-10 17:42:56 -07005347 break;
5348 }
5349 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005350 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005351 continue;
5352 }
5353
Eric Laurent3974e3b2017-12-07 17:58:43 -08005354 if (!profile->canOpenNewIo()) {
5355 ALOGW("Max Output number %u already opened for this profile %s",
5356 profile->maxOpenCount, profile->getTagName().c_str());
5357 continue;
5358 }
5359
Eric Laurent83efe1c2017-07-09 16:51:08 -07005360 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005361 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005362 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5363 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005364 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005365 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005366 profiles.removeAt(profile_index);
5367 profile_index--;
5368 } else {
5369 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005370 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005371 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005372 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5373 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005374 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005375 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005376
François Gaffie11d30102018-11-02 16:09:09 +01005377 if (device_distinguishes_on_address(deviceType)) {
5378 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5379 device->toString().c_str());
5380 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5381 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005382 }
Eric Laurente552edb2014-03-10 17:42:56 -07005383 ALOGV("checkOutputsForDevice(): adding output %d", output);
5384 }
5385 }
5386
5387 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005388 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005389 return BAD_VALUE;
5390 }
Eric Laurentd4692962014-05-05 18:13:44 -07005391 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005392 // check if one opened output is not needed any more after disconnecting one device
5393 for (size_t i = 0; i < mOutputs.size(); i++) {
5394 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005395 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005396 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005397 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005398 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005399 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005400 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005401 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5402 mOutputs.keyAt(i));
5403 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005404 }
Eric Laurente552edb2014-03-10 17:42:56 -07005405 }
5406 }
Eric Laurentd4692962014-05-05 18:13:44 -07005407 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005408 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005409 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5410 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005411 if (!profile->supportsDevice(device)) {
5412 continue;
5413 }
5414 ALOGV("checkOutputsForDevice(): "
5415 "clearing direct output profile %zu on module %s",
5416 j, hwModule->getName());
5417 profile->clearAudioProfiles();
5418 if (!profile->hasDynamicAudioProfile()) {
5419 continue;
5420 }
5421 // When a device is disconnected, if there is an IOProfile that contains dynamic
5422 // profiles and supports the disconnected device, call getAudioPort to repopulate
5423 // the capabilities of the devices that is supported by the IOProfile.
5424 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5425 if (supportedDevice == device ||
5426 !mAvailableOutputDevices.contains(supportedDevice)) {
5427 continue;
5428 }
5429 struct audio_port_v7 port;
5430 supportedDevice->toAudioPort(&port);
5431 status_t status = mpClientInterface->getAudioPort(&port);
5432 if (status == NO_ERROR) {
5433 supportedDevice->importAudioPort(port);
5434 }
Eric Laurente552edb2014-03-10 17:42:56 -07005435 }
5436 }
5437 }
5438 }
5439 return NO_ERROR;
5440}
5441
François Gaffie11d30102018-11-02 16:09:09 +01005442status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005443 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005444{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005445 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005446
François Gaffie11d30102018-11-02 16:09:09 +01005447 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005448 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005449 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005450 }
5451
Eric Laurentd4692962014-05-05 18:13:44 -07005452 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005453 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005454 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005455 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005456 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005457 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005458 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005459 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005460
François Gaffie11d30102018-11-02 16:09:09 +01005461 if (profile->supportsDevice(device)) {
5462 profiles.add(profile);
5463 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5464 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005465 }
5466 }
5467 }
5468
Eric Laurent0dd51852019-04-19 18:18:58 -07005469 if (profiles.isEmpty()) {
5470 ALOGW("%s: No input profile available for device %s",
5471 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005472 return BAD_VALUE;
5473 }
5474
5475 // open inputs for matching profiles if needed. Direct inputs are also opened to
5476 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5477 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5478
Eric Laurent1c333e22014-05-20 10:48:17 -07005479 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005480
Eric Laurentd4692962014-05-05 18:13:44 -07005481 // nothing to do if one input is already opened for this profile
5482 size_t input_index;
5483 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5484 desc = mInputs.valueAt(input_index);
5485 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005486 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005487 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005488 }
Eric Laurentd4692962014-05-05 18:13:44 -07005489 break;
5490 }
5491 }
5492 if (input_index != mInputs.size()) {
5493 continue;
5494 }
5495
Eric Laurent3974e3b2017-12-07 17:58:43 -08005496 if (!profile->canOpenNewIo()) {
5497 ALOGW("Max Input number %u already opened for this profile %s",
5498 profile->maxOpenCount, profile->getTagName().c_str());
5499 continue;
5500 }
5501
Eric Laurentfe231122017-11-17 17:48:06 -08005502 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005503 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005504 status_t status = desc->open(nullptr,
5505 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005506 AUDIO_SOURCE_MIC,
5507 AUDIO_INPUT_FLAG_NONE,
5508 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005509
Eric Laurentcf2c0212014-07-25 16:20:43 -07005510 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005511 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005512 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005513 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005514 mpClientInterface->setParameters(input, String8(param));
5515 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005516 }
François Gaffie11d30102018-11-02 16:09:09 +01005517 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005518 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005519 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005520 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005521 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005522 }
5523
Eric Laurent0dd51852019-04-19 18:18:58 -07005524 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005525 addInput(input, desc);
5526 }
5527 } // endif input != 0
5528
Eric Laurentcf2c0212014-07-25 16:20:43 -07005529 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005530 ALOGW("%s could not open input for device %s", __func__,
5531 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005532 profiles.removeAt(profile_index);
5533 profile_index--;
5534 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005535 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005536 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005537 }
Eric Laurentd4692962014-05-05 18:13:44 -07005538 ALOGV("checkInputsForDevice(): adding input %d", input);
5539 }
5540 } // end scan profiles
5541
5542 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005543 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005544 return BAD_VALUE;
5545 }
5546 } else {
5547 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005548 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005549 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005550 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005551 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005552 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005553 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005554 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005555 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5556 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005557 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005558 }
5559 }
5560 }
5561 } // end disconnect
5562
5563 return NO_ERROR;
5564}
5565
5566
Eric Laurente0720872014-03-11 09:30:41 -07005567void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005568{
5569 ALOGV("closeOutput(%d)", output);
5570
François Gaffie1c878552018-11-22 16:53:21 +01005571 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5572 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005573 ALOGW("closeOutput() unknown output %d", output);
5574 return;
5575 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005576 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005577 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005578
Eric Laurente552edb2014-03-10 17:42:56 -07005579 // look for duplicated outputs connected to the output being removed.
5580 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005581 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5582 if (dupOutput->isDuplicated() &&
5583 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5584 sp<SwAudioOutputDescriptor> remainingOutput =
5585 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005586 // As all active tracks on duplicated output will be deleted,
5587 // and as they were also referenced on the other output, the reference
5588 // count for their stream type must be adjusted accordingly on
5589 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005590 const bool wasActive = remainingOutput->isActive();
5591 // Note: no-op on the closing output where all clients has already been set inactive
5592 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005593 // stop() will be a no op if the output is still active but is needed in case all
5594 // active streams refcounts where cleared above
5595 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005596 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005597 }
Eric Laurente552edb2014-03-10 17:42:56 -07005598 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5599 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5600
5601 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005602 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005603 }
5604 }
5605
Eric Laurent05b90f82014-08-27 15:32:29 -07005606 nextAudioPortGeneration();
5607
François Gaffie1c878552018-11-22 16:53:21 +01005608 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005609 if (index >= 0) {
5610 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005611 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5612 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005613 mAudioPatches.removeItemsAt(index);
5614 mpClientInterface->onAudioPatchListUpdate();
5615 }
5616
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005617 if (closingOutputWasActive) {
5618 closingOutput->stop();
5619 }
François Gaffie1c878552018-11-22 16:53:21 +01005620 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005621
François Gaffie53615e22015-03-19 09:24:12 +01005622 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005623 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005624
5625 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5626 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005627 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005628 bool directOutputOpen = false;
5629 for (size_t i = 0; i < mOutputs.size(); i++) {
5630 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5631 directOutputOpen = true;
5632 break;
5633 }
5634 }
5635 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005636 ALOGV("no direct outputs open, reset MSD patches");
5637 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5638 // how output devices for patching are resolved. Avoid by caching and reusing the
5639 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5640 // devices to patch to. This may be complicated by the fact that devices may become
5641 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005642 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005643 }
5644 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005645}
5646
5647void AudioPolicyManager::closeInput(audio_io_handle_t input)
5648{
5649 ALOGV("closeInput(%d)", input);
5650
5651 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5652 if (inputDesc == NULL) {
5653 ALOGW("closeInput() unknown input %d", input);
5654 return;
5655 }
5656
Eric Laurent6a94d692014-05-20 11:18:06 -07005657 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005658
François Gaffie11d30102018-11-02 16:09:09 +01005659 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005660 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005661 if (index >= 0) {
5662 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005663 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5664 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005665 mAudioPatches.removeItemsAt(index);
5666 mpClientInterface->onAudioPatchListUpdate();
5667 }
5668
Eric Laurentfe231122017-11-17 17:48:06 -08005669 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005670 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005671
François Gaffie11d30102018-11-02 16:09:09 +01005672 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5673 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005674 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005675 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005676 }
Eric Laurente552edb2014-03-10 17:42:56 -07005677}
5678
François Gaffie11d30102018-11-02 16:09:09 +01005679SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5680 const DeviceVector &devices,
5681 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005682{
5683 SortedVector<audio_io_handle_t> outputs;
5684
François Gaffie11d30102018-11-02 16:09:09 +01005685 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005686 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005687 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005688 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005689 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005690 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005691 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005692 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005693 outputs.add(openOutputs.keyAt(i));
5694 }
5695 }
5696 return outputs;
5697}
5698
Mikhail Naganov37977152018-07-11 15:54:44 -07005699void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5700{
5701 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5702 // output is suspended before any tracks are moved to it
5703 checkA2dpSuspend();
5704 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005705 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005706 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005707 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005708 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005709 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5710 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5711 // configuration changes will ultimately be rerouted correctly. We can still avoid
5712 // unnecessary rerouting by caching and reusing the arguments to
5713 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5714 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005715 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005716 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005717 // an event that changed routing likely occurred, inform upper layers
5718 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005719}
5720
François Gaffiec005e562018-11-06 15:04:49 +01005721bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5722 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005723{
François Gaffiec005e562018-11-06 15:04:49 +01005724 return mEngine->getProductStrategyForAttributes(lAttr) ==
5725 mEngine->getProductStrategyForAttributes(rAttr);
5726}
5727
Francois Gaffieff1eb522020-05-06 18:37:04 +02005728void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5729{
5730 for (size_t i = 0; i < mAudioSources.size(); i++) {
5731 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5732 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005733 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5734 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005735 connectAudioSource(sourceDesc);
5736 }
5737 }
5738}
5739
5740void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5741{
5742 for (size_t i = 0; i < mAudioSources.size(); i++) {
5743 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5744 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5745 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5746 disconnectAudioSource(sourceDesc);
5747 }
5748 }
5749}
5750
François Gaffiec005e562018-11-06 15:04:49 +01005751void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5752{
5753 auto psId = mEngine->getProductStrategyForAttributes(attr);
5754
5755 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5756 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005757
François Gaffie11d30102018-11-02 16:09:09 +01005758 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5759 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005760
Eric Laurentc209fe42020-06-05 18:11:23 -07005761 uint32_t maxLatency = 0;
5762 bool invalidate = false;
5763 // take into account dynamic audio policies related changes: if a client is now associated
5764 // to a different policy mix than at creation time, invalidate corresponding stream
5765 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5766 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5767 if (desc->isDuplicated()) {
5768 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005769 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005770 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5771 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5772 continue;
5773 }
5774 sp<AudioPolicyMix> primaryMix;
5775 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5776 client->flags(), primaryMix, nullptr);
5777 if (status != OK) {
5778 continue;
5779 }
yucliuf4de36d2020-09-14 14:57:56 -07005780 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005781 invalidate = true;
5782 if (desc->isStrategyActive(psId)) {
5783 maxLatency = desc->latency();
5784 }
5785 break;
5786 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005787 }
5788 }
5789
Eric Laurentc209fe42020-06-05 18:11:23 -07005790 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005791 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5792 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005793 for (audio_io_handle_t srcOut : srcOutputs) {
5794 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005795 if (desc == nullptr) continue;
5796
5797 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005798 maxLatency = desc->latency();
5799 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005800
5801 if (invalidate) continue;
5802
5803 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005804 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005805 // a client on a non direct outputs has necessarily a linear PCM format
5806 // so we can call selectOutput() safely
5807 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5808 client->flags(),
5809 client->config().format,
5810 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005811 client->config().sample_rate,
5812 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005813 if (newOutput != srcOut) {
5814 invalidate = true;
5815 break;
5816 }
5817 } else {
5818 sp<IOProfile> profile = getProfileForOutput(newDevices,
5819 client->config().sample_rate,
5820 client->config().format,
5821 client->config().channel_mask,
5822 client->flags(),
5823 true /* directOnly */);
5824 if (profile != desc->mProfile) {
5825 invalidate = true;
5826 break;
5827 }
5828 }
5829 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005830 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005831
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005832 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005833 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005834 std::to_string(srcOutputs[0]).c_str(),
5835 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005836 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005837 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005838 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005839 if (desc == nullptr) continue;
5840
5841 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005842 setStrategyMute(psId, true, desc);
5843 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005844 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005845 }
François Gaffiec005e562018-11-06 15:04:49 +01005846 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005847 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005848 connectAudioSource(source);
5849 }
Eric Laurente552edb2014-03-10 17:42:56 -07005850 }
5851
François Gaffiec005e562018-11-06 15:04:49 +01005852 // Move effects associated to this stream from previous output to new output
5853 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005854 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005855 }
François Gaffiec005e562018-11-06 15:04:49 +01005856 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005857 if (invalidate) {
5858 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5859 mpClientInterface->invalidateStream(stream);
5860 }
Eric Laurente552edb2014-03-10 17:42:56 -07005861 }
5862 }
5863}
5864
Eric Laurente0720872014-03-11 09:30:41 -07005865void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005866{
François Gaffiec005e562018-11-06 15:04:49 +01005867 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5868 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5869 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005870 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005871 }
Eric Laurente552edb2014-03-10 17:42:56 -07005872}
5873
Kevin Rocard153f92d2018-12-18 18:33:28 -08005874void AudioPolicyManager::checkSecondaryOutputs() {
5875 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00005876 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005877 for (size_t i = 0; i < mOutputs.size(); i++) {
5878 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5879 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005880 sp<AudioPolicyMix> primaryMix;
5881 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005882 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005883 client->flags(), primaryMix, &secondaryMixes);
5884 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5885 for (auto &secondaryMix : secondaryMixes) {
5886 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5887 if (outputDesc != nullptr &&
5888 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5889 secondaryDescs.push_back(outputDesc);
5890 }
5891 }
5892
jiabin10a03f12021-05-07 23:46:28 +00005893 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005894 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00005895 } else if (!std::equal(
5896 client->getSecondaryOutputs().begin(),
5897 client->getSecondaryOutputs().end(),
5898 secondaryDescs.begin(), secondaryDescs.end())) {
5899 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5900 std::vector<audio_io_handle_t> secondaryOutputIds;
5901 for (const auto& secondaryDesc : secondaryDescs) {
5902 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5903 weakSecondaryDescs.push_back(secondaryDesc);
5904 }
5905 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5906 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005907 }
5908 }
5909 }
jiabin10a03f12021-05-07 23:46:28 +00005910 if (!trackSecondaryOutputs.empty()) {
5911 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5912 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005913 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00005914 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005915 mpClientInterface->invalidateStream(stream);
5916 }
5917}
5918
Eric Laurent2517af32020-11-25 15:31:27 +01005919bool AudioPolicyManager::isScoRequestedForComm() const {
5920 AudioDeviceTypeAddrVector devices;
5921 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5922 for (const auto &device : devices) {
5923 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5924 return true;
5925 }
5926 }
5927 return false;
5928}
5929
Eric Laurente0720872014-03-11 09:30:41 -07005930void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005931{
François Gaffie53615e22015-03-19 09:24:12 +01005932 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005933 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005934 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005935 return;
5936 }
5937
Eric Laurent3a4311c2014-03-17 12:00:47 -07005938 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005939 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5940 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005941 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005942
5943 // if suspended, restore A2DP output if:
5944 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005945 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005946 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005947 //
Eric Laurentf732e072016-08-03 19:30:28 -07005948 // if not suspended, suspend A2DP output if:
5949 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005950 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005951 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005952 //
5953 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005954 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005955 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005956 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005957 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005958
5959 mpClientInterface->restoreOutput(a2dpOutput);
5960 mA2dpSuspended = false;
5961 }
5962 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005963 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005964 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005965 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005966 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005967
5968 mpClientInterface->suspendOutput(a2dpOutput);
5969 mA2dpSuspended = true;
5970 }
5971 }
5972}
5973
François Gaffie11d30102018-11-02 16:09:09 +01005974DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5975 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005976{
François Gaffie11d30102018-11-02 16:09:09 +01005977 DeviceVector devices;
5978
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005979 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005980 if (index >= 0) {
5981 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005982 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005983 ALOGV("%s device %s forced by patch %d", __func__,
5984 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5985 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005986 }
5987 }
5988
Dean Wheatley514b4312020-06-17 21:45:00 +10005989 // Do not retrieve engine device for outputs through MSD
5990 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5991 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5992 return outputDesc->devices();
5993 }
5994
Eric Laurent97ac8712018-07-27 18:59:02 -07005995 // Honor explicit routing requests only if no client using default routing is active on this
5996 // input: a specific app can not force routing for other apps by setting a preferred device.
5997 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005998 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005999 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006000 if (device != nullptr) {
6001 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006002 }
6003
François Gaffiea807ef92018-11-05 10:44:33 +01006004 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6005 // of setForceUse / Default Bus device here
6006 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6007 if (device != nullptr) {
6008 return DeviceVector(device);
6009 }
6010
François Gaffiec005e562018-11-06 15:04:49 +01006011 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6012 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6013 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306014 auto hasStreamActive = [&](auto stream) {
6015 return hasStream(streams, stream) && isStreamActive(stream, 0);
6016 };
Eric Laurent484e9272018-06-07 17:29:23 -07006017
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306018 auto doGetOutputDevicesForVoice = [&]() {
6019 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
6020 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
6021 (isInCall() ||
6022 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
6023 };
6024
6025 // With low-latency playing on speaker, music on WFD, when the first low-latency
6026 // output is stopped, getNewOutputDevices checks for a product strategy
6027 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006028 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306029 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6030 // stream is associated to the output descriptor.
6031 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6032 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6033 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6034 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006035 // Retrieval of devices for voice DL is done on primary output profile, cannot
6036 // check the route (would force modifying configuration file for this profile)
6037 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6038 break;
6039 }
Eric Laurente552edb2014-03-10 17:42:56 -07006040 }
François Gaffiec005e562018-11-06 15:04:49 +01006041 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006042 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006043}
6044
François Gaffie11d30102018-11-02 16:09:09 +01006045sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6046 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006047{
François Gaffie11d30102018-11-02 16:09:09 +01006048 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006049
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006050 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006051 if (index >= 0) {
6052 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006053 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006054 ALOGV("getNewInputDevice() device %s forced by patch %d",
6055 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6056 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006057 }
6058 }
6059
Eric Laurent97ac8712018-07-27 18:59:02 -07006060 // Honor explicit routing requests only if no client using default routing is active on this
6061 // input: a specific app can not force routing for other apps by setting a preferred device.
6062 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006063 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6064 if (device != nullptr) {
6065 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006066 }
6067
Eric Laurentdc95a252018-04-12 12:46:56 -07006068 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006069 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006070 audio_attributes_t attributes;
6071 uid_t uid;
6072 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6073 if (topClient != nullptr) {
6074 attributes = topClient->attributes();
6075 uid = topClient->uid();
6076 } else {
6077 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6078 uid = 0;
6079 }
6080
Francois Gaffie716e1432019-01-14 16:58:59 +01006081 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6082 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006083 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006084 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006085 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006086 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006087
Eric Laurente552edb2014-03-10 17:42:56 -07006088 return device;
6089}
6090
Eric Laurent794fde22016-03-11 09:50:45 -08006091bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6092 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006093 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006094}
6095
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006096DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006097 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006098 // getOutputDevicesForStream's behavior for invalid streams.
6099 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6100 // device for music stream), but we want to return the empty set.
6101 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006102 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006103 }
François Gaffie11d30102018-11-02 16:09:09 +01006104 DeviceVector activeDevices;
6105 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006106 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6107 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006108 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006109 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006110 }
François Gaffiec005e562018-11-06 15:04:49 +01006111 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006112 devices.merge(curDevices);
6113 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006114 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07006115 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01006116 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006117 }
6118 }
Eric Laurente552edb2014-03-10 17:42:56 -07006119 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006120
Eric Laurentb0688d62018-08-14 15:49:18 -07006121 // Favor devices selected on active streams if any to report correct device in case of
6122 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006123 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006124 devices = activeDevices;
6125 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006126 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6127 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006128 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006129 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006130 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006131 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006132 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006133 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006134}
6135
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006136status_t AudioPolicyManager::getDevicesForAttributes(
6137 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6138 if (devices == nullptr) {
6139 return BAD_VALUE;
6140 }
6141 // check dynamic policies but only for primary descriptors (secondary not used for audible
6142 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006143 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006144 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006145 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006146 if (status != OK) {
6147 return status;
6148 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006149 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6150 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6151 devices->push_back(device);
6152 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006153 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006154 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6155 for (const auto& device : curDevices) {
6156 devices->push_back(device->getDeviceTypeAddr());
6157 }
6158 return NO_ERROR;
6159}
6160
Eric Laurente0720872014-03-11 09:30:41 -07006161void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006162 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006163 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006164 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006165 updateDevicesAndOutputs();
6166 break;
6167 default:
6168 break;
6169 }
6170}
6171
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006172uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006173
6174 // skip beacon mute management if a dedicated TTS output is available
6175 if (mTtsOutputAvailable) {
6176 return 0;
6177 }
6178
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006179 switch(event) {
6180 case STARTING_OUTPUT:
6181 mBeaconMuteRefCount++;
6182 break;
6183 case STOPPING_OUTPUT:
6184 if (mBeaconMuteRefCount > 0) {
6185 mBeaconMuteRefCount--;
6186 }
6187 break;
6188 case STARTING_BEACON:
6189 mBeaconPlayingRefCount++;
6190 break;
6191 case STOPPING_BEACON:
6192 if (mBeaconPlayingRefCount > 0) {
6193 mBeaconPlayingRefCount--;
6194 }
6195 break;
6196 }
6197
6198 if (mBeaconMuteRefCount > 0) {
6199 // any playback causes beacon to be muted
6200 return setBeaconMute(true);
6201 } else {
6202 // no other playback: unmute when beacon starts playing, mute when it stops
6203 return setBeaconMute(mBeaconPlayingRefCount == 0);
6204 }
6205}
6206
6207uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6208 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6209 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6210 // keep track of muted state to avoid repeating mute/unmute operations
6211 if (mBeaconMuted != mute) {
6212 // mute/unmute AUDIO_STREAM_TTS on all outputs
6213 ALOGV("\t muting %d", mute);
6214 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006215 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006216 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006217 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006218 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006219 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006220 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006221 maxLatency = latency;
6222 }
6223 }
6224 mBeaconMuted = mute;
6225 return maxLatency;
6226 }
6227 return 0;
6228}
6229
Eric Laurente0720872014-03-11 09:30:41 -07006230void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006231{
François Gaffiec005e562018-11-06 15:04:49 +01006232 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006233 mPreviousOutputs = mOutputs;
6234}
6235
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006236uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006237 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006238 uint32_t delayMs)
6239{
6240 // mute/unmute strategies using an incompatible device combination
6241 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6242 // if unmuting, unmute only after the specified delay
6243 if (outputDesc->isDuplicated()) {
6244 return 0;
6245 }
6246
6247 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006248 DeviceVector devices = outputDesc->devices();
6249 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006250
François Gaffiec005e562018-11-06 15:04:49 +01006251 auto productStrategies = mEngine->getOrderedProductStrategies();
6252 for (const auto &productStrategy : productStrategies) {
6253 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6254 DeviceVector curDevices =
6255 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6256 curDevices = curDevices.filter(outputDesc->supportedDevices());
6257 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006258 bool doMute = false;
6259
François Gaffiec005e562018-11-06 15:04:49 +01006260 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006261 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006262 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6263 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006264 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006265 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006266 }
Eric Laurent99401132014-05-07 19:48:15 -07006267 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006268 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006269 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006270 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006271 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006272 continue;
6273 }
François Gaffiec005e562018-11-06 15:04:49 +01006274 ALOGVV("%s() %s (curDevice %s)", __func__,
6275 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6276 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6277 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006278 if (mute) {
6279 // FIXME: should not need to double latency if volume could be applied
6280 // immediately by the audioflinger mixer. We must account for the delay
6281 // between now and the next time the audioflinger thread for this output
6282 // will process a buffer (which corresponds to one buffer size,
6283 // usually 1/2 or 1/4 of the latency).
6284 if (muteWaitMs < desc->latency() * 2) {
6285 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006286 }
6287 }
6288 }
6289 }
6290 }
6291 }
6292
Eric Laurent99401132014-05-07 19:48:15 -07006293 // temporary mute output if device selection changes to avoid volume bursts due to
6294 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006295 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006296 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6297 // temporary mute duration is conservatively set to 4 times the reported latency
6298 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6299 if (muteWaitMs < tempMuteWaitMs) {
6300 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006301 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006302 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6303 // make sure that we do not start the temporary mute period too early in case of
6304 // delayed device change
6305 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6306 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006307 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006308 }
6309 }
6310
Eric Laurente552edb2014-03-10 17:42:56 -07006311 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6312 if (muteWaitMs > delayMs) {
6313 muteWaitMs -= delayMs;
6314 usleep(muteWaitMs * 1000);
6315 return muteWaitMs;
6316 }
6317 return 0;
6318}
6319
François Gaffie11d30102018-11-02 16:09:09 +01006320uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6321 const DeviceVector &devices,
6322 bool force,
6323 int delayMs,
6324 audio_patch_handle_t *patchHandle,
6325 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006326{
François Gaffie11d30102018-11-02 16:09:09 +01006327 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006328 uint32_t muteWaitMs;
6329
6330 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006331 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6332 nullptr /* patchHandle */, requiresMuteCheck);
6333 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6334 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006335 return muteWaitMs;
6336 }
Eric Laurente552edb2014-03-10 17:42:56 -07006337
6338 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006339 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006340 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006341
François Gaffie11d30102018-11-02 16:09:09 +01006342 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6343
6344 if (!filteredDevices.isEmpty()) {
6345 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006346 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006347
6348 // if the outputs are not materially active, there is no need to mute.
6349 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006350 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006351 } else {
6352 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6353 muteWaitMs = 0;
6354 }
Eric Laurente552edb2014-03-10 17:42:56 -07006355
Eric Laurent79ea9582020-06-11 18:49:24 -07006356 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6357 // output profile or if new device is not supported AND previous device(s) is(are) still
6358 // available (otherwise reset device must be done on the output)
6359 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6360 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6361 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6362 // restore previous device after evaluating strategy mute state
6363 outputDesc->setDevices(prevDevices);
6364 return muteWaitMs;
6365 }
6366
Eric Laurente552edb2014-03-10 17:42:56 -07006367 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006368 // the requested device is AUDIO_DEVICE_NONE
6369 // OR the requested device is the same as current device
6370 // AND force is not specified
6371 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006372 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006373 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006374 !force && outputDesc->getPatchHandle() != 0) {
6375 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6376 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006377 return muteWaitMs;
6378 }
6379
François Gaffie11d30102018-11-02 16:09:09 +01006380 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006381
Eric Laurente552edb2014-03-10 17:42:56 -07006382 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006383 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006384 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006385 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006386 PatchBuilder patchBuilder;
6387 patchBuilder.addSource(outputDesc);
6388 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6389 for (const auto &filteredDevice : filteredDevices) {
6390 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006391 }
6392
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006393 // Add half reported latency to delayMs when muteWaitMs is null in order
6394 // to avoid disordered sequence of muting volume and changing devices.
6395 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6396 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006397 }
Eric Laurente552edb2014-03-10 17:42:56 -07006398
6399 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006400 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006401
6402 return muteWaitMs;
6403}
6404
Eric Laurentc75307b2015-03-17 15:29:32 -07006405status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006406 int delayMs,
6407 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006408{
Eric Laurent6a94d692014-05-20 11:18:06 -07006409 ssize_t index;
6410 if (patchHandle) {
6411 index = mAudioPatches.indexOfKey(*patchHandle);
6412 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006413 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006414 }
6415 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006416 return INVALID_OPERATION;
6417 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006418 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006419 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006420 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006421 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006422 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006423 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006424 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006425 return status;
6426}
6427
6428status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006429 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006430 bool force,
6431 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006432{
6433 status_t status = NO_ERROR;
6434
Eric Laurent1f2f2232014-06-02 12:01:23 -07006435 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006436 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6437 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006438
François Gaffie11d30102018-11-02 16:09:09 +01006439 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006440 PatchBuilder patchBuilder;
6441 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006442 // AUDIO_SOURCE_HOTWORD is for internal use only:
6443 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006444 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6445 auto result = usecase;
6446 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6447 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6448 }
6449 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006450 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006451 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006452 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006453 }
6454 }
6455 return status;
6456}
6457
Eric Laurent6a94d692014-05-20 11:18:06 -07006458status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6459 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006460{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006461 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006462 ssize_t index;
6463 if (patchHandle) {
6464 index = mAudioPatches.indexOfKey(*patchHandle);
6465 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006466 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006467 }
6468 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006469 return INVALID_OPERATION;
6470 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006471 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006472 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006473 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006474 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006475 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006476 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006477 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006478 return status;
6479}
6480
François Gaffie11d30102018-11-02 16:09:09 +01006481sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006482 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006483 audio_format_t& format,
6484 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006485 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006486{
6487 // Choose an input profile based on the requested capture parameters: select the first available
6488 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006489 //
6490 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6491 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006492
Glenn Kasten730b9262018-03-29 15:01:26 -07006493 sp<IOProfile> firstInexact;
6494 uint32_t updatedSamplingRate = 0;
6495 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6496 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006497 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006498 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006499 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006500 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006501 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006502 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006503 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006504 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006505 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006506 &channelMask /*updatedChannelMask*/,
6507 // FIXME ugly cast
6508 (audio_output_flags_t) flags,
6509 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006510 return profile;
6511 }
François Gaffie11d30102018-11-02 16:09:09 +01006512 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006513 samplingRate,
6514 &updatedSamplingRate,
6515 format,
6516 &updatedFormat,
6517 channelMask,
6518 &updatedChannelMask,
6519 // FIXME ugly cast
6520 (audio_output_flags_t) flags,
6521 false /*exactMatchRequiredForInputFlags*/)) {
6522 firstInexact = profile;
6523 }
6524
Eric Laurente552edb2014-03-10 17:42:56 -07006525 }
6526 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006527 if (firstInexact != nullptr) {
6528 samplingRate = updatedSamplingRate;
6529 format = updatedFormat;
6530 channelMask = updatedChannelMask;
6531 return firstInexact;
6532 }
Eric Laurente552edb2014-03-10 17:42:56 -07006533 return NULL;
6534}
6535
François Gaffieaaac0fd2018-11-22 17:56:39 +01006536float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6537 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006538 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006539 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006540{
jiabin9a3361e2019-10-01 09:38:30 -07006541 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006542
6543 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6544 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6545 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6546 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006547 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6548 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6549 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6550 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006551 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006552
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006553 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006554 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6555 mOutputs.isActive(ringVolumeSrc, 0)) {
6556 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006557 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006558 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006559 }
6560
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006561 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006562 if ((volumeSource != callVolumeSrc && (isInCall() ||
6563 mOutputs.isActiveLocally(callVolumeSrc))) &&
6564 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6565 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6566 volumeSource == alarmVolumeSrc ||
6567 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6568 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6569 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006570 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006571 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006572 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006573 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006574 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006575 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006576 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6577 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6578 // programmatically muted.
6579 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6580 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6581 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006582 bool exemptFromCapping =
6583 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6584 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006585 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6586 volumeSource, volumeDb);
6587 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006588 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6589 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6590 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006591 }
6592 }
Eric Laurente552edb2014-03-10 17:42:56 -07006593 // if a headset is connected, apply the following rules to ring tones and notifications
6594 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006595 // - always attenuate notifications volume by 6dB
6596 // - attenuate ring tones volume by 6dB unless music is not playing and
6597 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006598 // - if music is playing, always limit the volume to current music volume,
6599 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006600 if (!Intersection(deviceTypes,
6601 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6602 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006603 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6604 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006605 ((volumeSource == alarmVolumeSrc ||
6606 volumeSource == ringVolumeSrc) ||
6607 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6608 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6609 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6610 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6611 curves.canBeMuted()) {
6612
Eric Laurente552edb2014-03-10 17:42:56 -07006613 // when the phone is ringing we must consider that music could have been paused just before
6614 // by the music application and behave as if music was active if the last music track was
6615 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006616 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006617 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006618 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006619 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006620 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6621 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006622 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006623 float musicVolDb = computeVolume(musicCurves,
6624 musicVolumeSrc,
6625 musicCurves.getVolumeIndex(musicDevice),
6626 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006627 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6628 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6629 if (volumeDb > minVolDb) {
6630 volumeDb = minVolDb;
6631 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006632 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006633 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6634 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6635 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006636 // on A2DP, also ensure notification volume is not too low compared to media when
6637 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006638 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006639 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006640 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6641 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006642 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6643 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006644 }
6645 }
jiabin9a3361e2019-10-01 09:38:30 -07006646 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006647 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006648 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006649 }
6650 }
6651
François Gaffie43c73442018-11-08 08:21:55 +01006652 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006653}
6654
Eric Laurent3839bc02018-07-10 18:33:34 -07006655int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006656 VolumeSource fromVolumeSource,
6657 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006658{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006659 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006660 return srcIndex;
6661 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006662 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6663 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006664 float minSrc = (float)srcCurves.getVolumeIndexMin();
6665 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6666 float minDst = (float)dstCurves.getVolumeIndexMin();
6667 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006668
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006669 // preserve mute request or correct range
6670 if (srcIndex < minSrc) {
6671 if (srcIndex == 0) {
6672 return 0;
6673 }
6674 srcIndex = minSrc;
6675 } else if (srcIndex > maxSrc) {
6676 srcIndex = maxSrc;
6677 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006678 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6679}
6680
François Gaffieaaac0fd2018-11-22 17:56:39 +01006681status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6682 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006683 int index,
6684 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006685 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006686 int delayMs,
6687 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006688{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006689 // do not change actual attributes volume if the attributes is muted
6690 if (outputDesc->isMuted(volumeSource)) {
6691 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6692 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006693 return NO_ERROR;
6694 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006695 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6696 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6697 bool isVoiceVolSrc = callVolSrc == volumeSource;
6698 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6699
Eric Laurent2517af32020-11-25 15:31:27 +01006700 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006701 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006702 // if sco and call follow same curves, bypass forceUseForComm
6703 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006704 ((isVoiceVolSrc && isScoRequested) ||
6705 (isBtScoVolSrc && !isScoRequested))) {
6706 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6707 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006708 // Do not return an error here as AudioService will always set both voice call
6709 // and bluetooth SCO volumes due to stream aliasing.
6710 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006711 }
jiabin9a3361e2019-10-01 09:38:30 -07006712 if (deviceTypes.empty()) {
6713 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006714 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006715
jiabin9a3361e2019-10-01 09:38:30 -07006716 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6717 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006718 // Force VoIP volume to max for bluetooth SCO device except if muted
6719 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006720 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006721 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006722 }
jiabin9a3361e2019-10-01 09:38:30 -07006723 outputDesc->setVolume(
6724 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006725
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006726 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006727 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006728 // 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 +01006729 if (isVoiceVolSrc) {
6730 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006731 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006732 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006733 }
Eric Laurent18fba842016-03-31 14:41:26 -07006734 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006735 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6736 mLastVoiceVolume = voiceVolume;
6737 }
6738 }
Eric Laurente552edb2014-03-10 17:42:56 -07006739 return NO_ERROR;
6740}
6741
Eric Laurentc75307b2015-03-17 15:29:32 -07006742void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006743 const DeviceTypeSet& deviceTypes,
6744 int delayMs,
6745 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006746{
jiabincd510522020-01-22 09:40:55 -08006747 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006748 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6749 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6750 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006751 curves.getVolumeIndex(deviceTypes),
6752 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006753 }
6754}
6755
François Gaffiec005e562018-11-06 15:04:49 +01006756void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6757 bool on,
6758 const sp<AudioOutputDescriptor>& outputDesc,
6759 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006760 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006761{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006762 std::vector<VolumeSource> sourcesToMute;
6763 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6764 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6765 toString(attributes).c_str(), on, outputDesc->getId());
6766 VolumeSource source = toVolumeSource(attributes);
6767 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6768 sourcesToMute.push_back(source);
6769 }
Eric Laurente552edb2014-03-10 17:42:56 -07006770 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006771 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006772 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006773 }
6774
Eric Laurente552edb2014-03-10 17:42:56 -07006775}
6776
François Gaffieaaac0fd2018-11-22 17:56:39 +01006777void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6778 bool on,
6779 const sp<AudioOutputDescriptor>& outputDesc,
6780 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006781 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006782{
jiabin9a3361e2019-10-01 09:38:30 -07006783 if (deviceTypes.empty()) {
6784 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006785 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006786 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006787 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006788 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006789 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006790 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6791 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6792 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006793 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006794 }
6795 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006796 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6797 // ignored
6798 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006799 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006800 if (!outputDesc->isMuted(volumeSource)) {
6801 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006802 return;
6803 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006804 if (outputDesc->decMuteCount(volumeSource) == 0) {
6805 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006806 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006807 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006808 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006809 delayMs);
6810 }
6811 }
6812}
6813
François Gaffie53615e22015-03-19 09:24:12 +01006814bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6815{
François Gaffiec005e562018-11-06 15:04:49 +01006816 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006817 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6818 return true;
6819 }
6820
6821 // has known usage?
6822 switch (paa->usage) {
6823 case AUDIO_USAGE_UNKNOWN:
6824 case AUDIO_USAGE_MEDIA:
6825 case AUDIO_USAGE_VOICE_COMMUNICATION:
6826 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6827 case AUDIO_USAGE_ALARM:
6828 case AUDIO_USAGE_NOTIFICATION:
6829 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6830 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6831 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6832 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6833 case AUDIO_USAGE_NOTIFICATION_EVENT:
6834 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6835 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6836 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6837 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006838 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006839 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006840 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006841 case AUDIO_USAGE_EMERGENCY:
6842 case AUDIO_USAGE_SAFETY:
6843 case AUDIO_USAGE_VEHICLE_STATUS:
6844 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006845 break;
6846 default:
6847 return false;
6848 }
6849 return true;
6850}
6851
François Gaffie2110e042015-03-24 08:41:51 +01006852audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6853{
6854 return mEngine->getForceUse(usage);
6855}
6856
6857bool AudioPolicyManager::isInCall()
6858{
6859 return isStateInCall(mEngine->getPhoneState());
6860}
6861
6862bool AudioPolicyManager::isStateInCall(int state)
6863{
6864 return is_state_in_call(state);
6865}
6866
Eric Laurent74b71512019-11-06 17:21:57 -08006867bool AudioPolicyManager::isCallAudioAccessible()
6868{
6869 audio_mode_t mode = mEngine->getPhoneState();
6870 return (mode == AUDIO_MODE_IN_CALL)
6871 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6872 || (mode == AUDIO_MODE_CALL_SCREEN);
6873}
6874
Eric Laurentd60560a2015-04-10 11:31:20 -07006875void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6876{
6877 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006878 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006879 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006880 sourceDesc->sinkDevice()->equals(deviceDesc))
6881 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006882 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006883 }
6884 }
6885
6886 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6887 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6888 bool release = false;
6889 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6890 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6891 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6892 source->ext.device.type == deviceDesc->type()) {
6893 release = true;
6894 }
6895 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006896 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006897 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6898 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6899 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006900 sink->ext.device.type == deviceDesc->type() &&
6901 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6902 || strncmp(sink->ext.device.address, address,
6903 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006904 release = true;
6905 }
6906 }
6907 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006908 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6909 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006910 }
6911 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006912
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006913 mInputs.clearSessionRoutesForDevice(deviceDesc);
6914
Francois Gaffie716e1432019-01-14 16:58:59 +01006915 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006916}
6917
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006918void AudioPolicyManager::modifySurroundFormats(
6919 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006920 std::unordered_set<audio_format_t> enforcedSurround(
6921 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006922 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6923 for (const auto& pair : mConfig.getSurroundFormats()) {
6924 allSurround.insert(pair.first);
6925 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6926 }
Phil Burk09bc4612016-02-24 15:58:15 -08006927
6928 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6929 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006930 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006931 // This is the resulting set of formats depending on the surround mode:
6932 // 'all surround' = allSurround
6933 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6934 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6935 // 'manual surround' = mManualSurroundFormats
6936 // AUTO: formats v 'enforced surround'
6937 // ALWAYS: formats v 'all surround' v 'enforced surround'
6938 // NEVER: formats ^ 'non-surround'
6939 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006940
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006941 std::unordered_set<audio_format_t> formatSet;
6942 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6943 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006944 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006945 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006946 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006947 formatSet.insert(*formatIter);
6948 }
6949 }
6950 } else {
6951 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6952 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006953 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006954
jiabin81772902018-04-02 17:52:27 -07006955 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006956 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006957 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6958 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6959 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006960 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006961 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6962 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6963 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006964 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006965 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006966 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006967 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006968 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006969 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006970}
6971
jiabin06e4bab2019-07-29 10:13:34 -07006972void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6973 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006974 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6975 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6976
6977 // If NEVER, then remove support for channelMasks > stereo.
6978 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006979 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6980 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006981 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006982 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006983 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006984 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006985 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006986 }
6987 }
jiabin81772902018-04-02 17:52:27 -07006988 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6989 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6990 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006991 bool supports5dot1 = false;
6992 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006993 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006994 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6995 supports5dot1 = true;
6996 break;
6997 }
6998 }
6999 // If not then add 5.1 support.
7000 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007001 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007002 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007003 }
Phil Burk09bc4612016-02-24 15:58:15 -08007004 }
7005}
7006
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007007void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007008 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007009 AudioProfileVector &profiles)
7010{
7011 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007012 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007013
François Gaffie112b0af2015-11-19 16:13:25 +01007014 // Format MUST be checked first to update the list of AudioProfile
7015 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007016 reply = mpClientInterface->getParameters(
7017 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007018 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007019 AudioParameter repliedParameters(reply);
7020 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007021 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007022 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7023 return;
7024 }
Phil Burk09bc4612016-02-24 15:58:15 -08007025 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007026 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007027 if (device == AUDIO_DEVICE_OUT_HDMI
7028 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007029 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007030 }
jiabin3e277cc2019-09-10 14:27:34 -07007031 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007032 }
François Gaffie112b0af2015-11-19 16:13:25 +01007033
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007034 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007035 ChannelMaskSet channelMasks;
7036 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007037 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007038 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007039
7040 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007041 reply = mpClientInterface->getParameters(
7042 ioHandle,
7043 requestedParameters.toString() + ";" +
7044 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007045 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007046 AudioParameter repliedParameters(reply);
7047 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007048 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007049 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007050 }
7051 }
7052 if (profiles.hasDynamicChannelsFor(format)) {
7053 reply = mpClientInterface->getParameters(ioHandle,
7054 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007055 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007056 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007057 AudioParameter repliedParameters(reply);
7058 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007059 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007060 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007061 if (device == AUDIO_DEVICE_OUT_HDMI
7062 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007063 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007064 }
François Gaffie112b0af2015-11-19 16:13:25 +01007065 }
7066 }
jiabin3e277cc2019-09-10 14:27:34 -07007067 addDynamicAudioProfileAndSort(
7068 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007069 }
7070}
Eric Laurentd60560a2015-04-10 11:31:20 -07007071
Mikhail Naganovdc769682018-05-04 15:34:08 -07007072status_t AudioPolicyManager::installPatch(const char *caller,
7073 audio_patch_handle_t *patchHandle,
7074 AudioIODescriptorInterface *ioDescriptor,
7075 const struct audio_patch *patch,
7076 int delayMs)
7077{
7078 ssize_t index = mAudioPatches.indexOfKey(
7079 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7080 *patchHandle : ioDescriptor->getPatchHandle());
7081 sp<AudioPatch> patchDesc;
7082 status_t status = installPatch(
7083 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7084 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007085 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007086 }
7087 return status;
7088}
7089
7090status_t AudioPolicyManager::installPatch(const char *caller,
7091 ssize_t index,
7092 audio_patch_handle_t *patchHandle,
7093 const struct audio_patch *patch,
7094 int delayMs,
7095 uid_t uid,
7096 sp<AudioPatch> *patchDescPtr)
7097{
7098 sp<AudioPatch> patchDesc;
7099 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7100 if (index >= 0) {
7101 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007102 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007103 }
7104
7105 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7106 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7107 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7108 if (status == NO_ERROR) {
7109 if (index < 0) {
7110 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007111 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007112 } else {
7113 patchDesc->mPatch = *patch;
7114 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007115 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007116 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007117 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007118 }
7119 nextAudioPortGeneration();
7120 mpClientInterface->onAudioPatchListUpdate();
7121 }
7122 if (patchDescPtr) *patchDescPtr = patchDesc;
7123 return status;
7124}
7125
jiabinbce0c1d2020-10-05 11:20:18 -07007126bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7127{
7128 const TrackClientVector activeClients = output->getActiveClients();
7129 if (activeClients.empty()) {
7130 return true;
7131 }
7132 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7133 if (index < 0) {
7134 ALOGE("%s, no audio patch found while there are active clients on output %d",
7135 __func__, output->getId());
7136 return false;
7137 }
7138 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7139 DeviceVector routedDevices;
7140 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7141 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7142 patchDesc->mPatch.sinks[i].id);
7143 if (device == nullptr) {
7144 ALOGE("%s, no audio device found with id(%d)",
7145 __func__, patchDesc->mPatch.sinks[i].id);
7146 return false;
7147 }
7148 routedDevices.add(device);
7149 }
7150 for (const auto& client : activeClients) {
7151 // TODO: b/175343099 only travel the valid client
7152 sp<DeviceDescriptor> preferredDevice =
7153 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7154 if (mEngine->getOutputDevicesForAttributes(
7155 client->attributes(), preferredDevice, false) == routedDevices) {
7156 return false;
7157 }
7158 }
7159 return true;
7160}
7161
7162sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7163 const sp<IOProfile>& profile, const DeviceVector& devices)
7164{
7165 for (const auto& device : devices) {
7166 // TODO: This should be checking if the profile supports the device combo.
7167 if (!profile->supportsDevice(device)) {
7168 return nullptr;
7169 }
7170 }
7171 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7172 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02007173 status_t status = desc->open(nullptr /* halConfig */, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007174 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7175 if (status != NO_ERROR) {
7176 return nullptr;
7177 }
7178
7179 // Here is where the out_set_parameters() for card & device gets called
7180 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7181 const audio_devices_t deviceType = device->type();
7182 const String8 &address = String8(device->address().c_str());
7183 if (!address.isEmpty()) {
7184 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7185 mpClientInterface->setParameters(output, String8(param));
7186 free(param);
7187 }
7188 updateAudioProfiles(device, output, profile->getAudioProfiles());
7189 if (!profile->hasValidAudioProfile()) {
7190 ALOGW("%s() missing param", __func__);
7191 desc->close();
7192 return nullptr;
7193 } else if (profile->hasDynamicAudioProfile()) {
7194 desc->close();
7195 output = AUDIO_IO_HANDLE_NONE;
7196 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7197 profile->pickAudioProfile(
7198 config.sample_rate, config.channel_mask, config.format);
7199 config.offload_info.sample_rate = config.sample_rate;
7200 config.offload_info.channel_mask = config.channel_mask;
7201 config.offload_info.format = config.format;
7202
Eric Laurentf1f22e72021-07-13 14:04:14 +02007203 status = desc->open(&config, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007204 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7205 if (status != NO_ERROR) {
7206 return nullptr;
7207 }
7208 }
7209
7210 addOutput(output, desc);
7211 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7212 sp<AudioPolicyMix> policyMix;
7213 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7214 policyMix->setOutput(desc);
7215 desc->mPolicyMix = policyMix;
7216 } else {
7217 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7218 address.string());
7219 }
7220
7221 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7222 // no duplicated output for direct outputs and
7223 // outputs used by dynamic policy mixes
7224 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7225
7226 //TODO: configure audio effect output stage here
7227
7228 // open a duplicating output thread for the new output and the primary output
7229 sp<SwAudioOutputDescriptor> dupOutputDesc =
7230 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7231 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7232 if (status == NO_ERROR) {
7233 // add duplicated output descriptor
7234 addOutput(duplicatedOutput, dupOutputDesc);
7235 } else {
7236 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7237 mPrimaryOutput->mIoHandle, output);
7238 desc->close();
7239 removeOutput(output);
7240 nextAudioPortGeneration();
7241 return nullptr;
7242 }
7243 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007244 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7245 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7246 mPrimaryOutput = desc;
7247 }
jiabinbce0c1d2020-10-05 11:20:18 -07007248 return desc;
7249}
7250
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007251} // namespace android