blob: a2dbeb22535bc5860a0db8d97949e41a5c0e2164 [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>
jiabinf042b9b2021-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 Ganov33761132021-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 Ganov33761132021-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 Ganov33761132021-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 Ganov33761132021-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, "
2167 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2168 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002169
Eric Laurentad2e7b92017-09-14 20:06:42 -07002170 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002171 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002172 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002173 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002174 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002175 sp<AudioInputDescriptor> inputDesc;
2176 sp<RecordClientDescriptor> clientDesc;
2177 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002178 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002179 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002180
2181 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2182 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2183 return INVALID_OPERATION;
2184 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002185
Francois Gaffie716e1432019-01-14 16:58:59 +01002186 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2187 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002188 }
2189
Paul McLean466dc8e2015-04-17 13:15:36 -06002190 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002191 sp<DeviceDescriptor> explicitRoutingDevice =
2192 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002193
Eric Laurentad2e7b92017-09-14 20:06:42 -07002194 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2195 // possible
2196 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2197 *input != AUDIO_IO_HANDLE_NONE) {
2198 ssize_t index = mInputs.indexOfKey(*input);
2199 if (index < 0) {
2200 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2201 status = BAD_VALUE;
2202 goto error;
2203 }
2204 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002205 RecordClientVector clients = inputDesc->getClientsForSession(session);
2206 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002207 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2208 status = BAD_VALUE;
2209 goto error;
2210 }
2211 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2212 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002213 // corresponds to a new client and is only permitted from the same UID.
2214 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 if (clients.size() > 1) {
2216 for (const auto& client : clients) {
2217 // The client map is ordered by key values (portId) and portIds are allocated
2218 // incrementaly. So the first client in this list is the one opened by audio flinger
2219 // when the mmap stream is created and should be ignored as it does not correspond
2220 // to an actual client
2221 if (client == *clients.cbegin()) {
2222 continue;
2223 }
2224 if (uid != client->uid() && !client->isSilenced()) {
2225 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2226 uid, client->portId(), client->uid());
2227 status = INVALID_OPERATION;
2228 goto error;
2229 }
Eric Laurent331679c2018-04-16 17:03:16 -07002230 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002231 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002232 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002233 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002234
Eric Laurentfecbceb2021-02-09 14:46:43 +01002235 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002236 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002237 }
2238
2239 *input = AUDIO_IO_HANDLE_NONE;
2240 *inputType = API_INPUT_INVALID;
2241
Francois Gaffie716e1432019-01-14 16:58:59 +01002242 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002243
Francois Gaffie716e1432019-01-14 16:58:59 +01002244 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2245 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2246 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002247 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002248 ALOGW("%s could not find input mix for attr %s",
2249 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002250 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002251 }
jiabinc1de2df2019-05-07 14:26:40 -07002252 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2253 String8(attr->tags + strlen("addr=")),
2254 AUDIO_FORMAT_DEFAULT);
2255 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002256 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002257 __func__, attributes.source, attributes.tags);
2258 status = BAD_VALUE;
2259 goto error;
2260 }
2261
Kevin Rocard25f9b052019-02-27 15:08:54 -08002262 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2263 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2264 } else {
2265 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2266 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002267 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002268 if (explicitRoutingDevice != nullptr) {
2269 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002270 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002271 // Prevent from storing invalid requested device id in clients
2272 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002273 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002274 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2275 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002276 }
François Gaffie11d30102018-11-02 16:09:09 +01002277 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002278 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002279 status = BAD_VALUE;
2280 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002281 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002282 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2283 *inputType = API_INPUT_MIX_CAPTURE;
2284 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002285 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2286 // there is an external policy, but this input is attached to a mix of recorders,
2287 // meaning it receives audio injected into the framework, so the recorder doesn't
2288 // know about it and is therefore considered "legacy"
2289 *inputType = API_INPUT_LEGACY;
2290 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002291 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002292 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002293 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002294 } else {
2295 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002296 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002297
Eric Laurent599c7582015-12-07 18:05:55 -08002298 }
2299
François Gaffiec005e562018-11-06 15:04:49 +01002300 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002301 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002302 status = INVALID_OPERATION;
2303 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002304 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002305
Eric Laurent8f42ea12018-08-08 09:08:25 -07002306exit:
2307
François Gaffiec005e562018-11-06 15:04:49 +01002308 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2309 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002310
Francois Gaffie716e1432019-01-14 16:58:59 +01002311 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002312 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002313 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002314
Mikhail Naganov2996f672019-04-18 12:29:59 -07002315 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002316 requestedDeviceId, attributes.source, flags,
2317 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002318 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002319 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002320
2321 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2322 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002323
Eric Laurent599c7582015-12-07 18:05:55 -08002324 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002325
2326error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002327 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002328}
2329
2330
François Gaffie11d30102018-11-02 16:09:09 +01002331audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002332 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002333 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002334 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002335 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002336 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002337{
2338 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002339 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002340 bool isSoundTrigger = false;
2341
François Gaffiec005e562018-11-06 15:04:49 +01002342 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002343 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2344 if (index >= 0) {
2345 input = mSoundTriggerSessions.valueFor(session);
2346 isSoundTrigger = true;
2347 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2348 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2349 } else {
2350 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002351 }
François Gaffiec005e562018-11-06 15:04:49 +01002352 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002353 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002354 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002355 }
2356
Andy Hungf129b032015-04-07 13:45:50 -07002357 // find a compatible input profile (not necessarily identical in parameters)
2358 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002359 // sampling rate and flags may be updated by getInputProfile
2360 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2361 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002362 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002363 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002364 audio_input_flags_t profileFlags = flags;
2365 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002366 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002367 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002368 profileFlags);
2369 if (profile != 0) {
2370 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002371 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2372 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002373 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2374 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2375 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002376 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2377 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2378 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002379 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002380 }
Eric Laurente552edb2014-03-10 17:42:56 -07002381 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002382 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002383 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002384 if (samplingRate == 0) {
2385 samplingRate = profileSamplingRate;
2386 }
Eric Laurente552edb2014-03-10 17:42:56 -07002387
Eric Laurent322b4d22015-04-03 15:57:54 -07002388 if (profile->getModuleHandle() == 0) {
2389 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002390 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002391 }
2392
Eric Laurentec376dc2021-04-08 20:41:22 +02002393 // Reuse an already opened input if a client with the same session ID already exists
2394 // on that input
2395 for (size_t i = 0; i < mInputs.size(); i++) {
2396 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2397 if (desc->mProfile != profile) {
2398 continue;
2399 }
2400 RecordClientVector clients = desc->clientsList();
2401 for (const auto &client : clients) {
2402 if (session == client->session()) {
2403 return desc->mIoHandle;
2404 }
2405 }
2406 }
2407
Eric Laurent3974e3b2017-12-07 17:58:43 -08002408 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002409 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002410 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002411 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002412 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002413 continue;
2414 }
2415 // if sound trigger, reuse input if used by other sound trigger on same session
2416 // else
2417 // reuse input if active client app is not in IDLE state
2418 //
2419 RecordClientVector clients = desc->clientsList();
2420 bool doClose = false;
2421 for (const auto& client : clients) {
2422 if (isSoundTrigger != client->isSoundTrigger()) {
2423 continue;
2424 }
2425 if (client->isSoundTrigger()) {
2426 if (session == client->session()) {
2427 return desc->mIoHandle;
2428 }
2429 continue;
2430 }
2431 if (client->active() && client->appState() != APP_STATE_IDLE) {
2432 return desc->mIoHandle;
2433 }
2434 doClose = true;
2435 }
2436 if (doClose) {
2437 closeInput(desc->mIoHandle);
2438 } else {
2439 i++;
2440 }
2441 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002442 }
2443
Eric Laurentfe231122017-11-17 17:48:06 -08002444 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002445
Eric Laurentfe231122017-11-17 17:48:06 -08002446 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2447 lConfig.sample_rate = profileSamplingRate;
2448 lConfig.channel_mask = profileChannelMask;
2449 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002450
François Gaffie11d30102018-11-02 16:09:09 +01002451 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002452
2453 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002454 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002455 (profileSamplingRate != lConfig.sample_rate) ||
2456 !audio_formats_match(profileFormat, lConfig.format) ||
2457 (profileChannelMask != lConfig.channel_mask)) {
2458 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002459 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002460 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002461 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002462 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002463 }
Eric Laurent599c7582015-12-07 18:05:55 -08002464 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002465 }
2466
Eric Laurentc722f302014-12-10 11:21:49 -08002467 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002468
Eric Laurent599c7582015-12-07 18:05:55 -08002469 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002470 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002471
Eric Laurent599c7582015-12-07 18:05:55 -08002472 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002473}
2474
Eric Laurent4eb58f12018-12-07 16:41:02 -08002475status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002476{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002477 ALOGV("%s portId %d", __FUNCTION__, portId);
2478
2479 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2480 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002481 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002482 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002483 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002484 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002485 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002486 if (client->active()) {
2487 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2488 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002489 }
2490
Eric Laurent8f42ea12018-08-08 09:08:25 -07002491 audio_session_t session = client->session();
2492
Eric Laurent4eb58f12018-12-07 16:41:02 -08002493 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002494
Eric Laurent4eb58f12018-12-07 16:41:02 -08002495 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002496
Eric Laurent4eb58f12018-12-07 16:41:02 -08002497 status_t status = inputDesc->start();
2498 if (status != NO_ERROR) {
2499 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002500 }
Eric Laurente552edb2014-03-10 17:42:56 -07002501
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002502 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002503 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002504 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002505
Eric Laurent8f42ea12018-08-08 09:08:25 -07002506 // indicate active capture to sound trigger service if starting capture from a mic on
2507 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002508 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002509 if (device != nullptr) {
2510 status = setInputDevice(input, device, true /* force */);
2511 } else {
2512 ALOGW("%s no new input device can be found for descriptor %d",
2513 __FUNCTION__, inputDesc->getId());
2514 status = BAD_VALUE;
2515 }
Eric Laurente552edb2014-03-10 17:42:56 -07002516
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002517 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002518 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002519 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002520 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002521 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2522 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002523 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002524 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002525
François Gaffie11d30102018-11-02 16:09:09 +01002526 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2527 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002528 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002529 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002530 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002531
Eric Laurent8f42ea12018-08-08 09:08:25 -07002532 // automatically enable the remote submix output when input is started if not
2533 // used by a policy mix of type MIX_TYPE_RECORDERS
2534 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002535 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002536 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002537 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002538 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002539 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2540 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002541 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002542 if (address != "") {
2543 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2544 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002545 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002546 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002547 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002548 } else if (status != NO_ERROR) {
2549 // Restore client activity state.
2550 inputDesc->setClientActive(client, false);
2551 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002552 }
2553
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002554 ALOGV("%s input %d source = %d status = %d exit",
2555 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002556
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002557 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002558}
2559
Eric Laurent8fc147b2018-07-22 19:13:55 -07002560status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002561{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002562 ALOGV("%s portId %d", __FUNCTION__, portId);
2563
2564 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2565 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002566 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002567 return BAD_VALUE;
2568 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002569 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002570 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002571 if (!client->active()) {
2572 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002573 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002574 }
Carter Hsue6139d52021-07-08 10:30:20 +08002575 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002576 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002577
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578 inputDesc->stop();
2579 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002580 auto current_source = inputDesc->source();
2581 setInputDevice(input, getNewInputDevice(inputDesc),
2582 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002583 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002584 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002585 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002586 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002587 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2588 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002589 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002590 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002591
2592 // automatically disable the remote submix output when input is stopped if not
2593 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002594 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002595 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002596 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002597 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002598 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2599 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002600 }
2601 if (address != "") {
2602 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2603 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002604 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002605 }
2606 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002607 resetInputDevice(input);
2608
2609 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2610 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002611 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2612 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002613 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002614 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002615 }
2616 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002617 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002618 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002619}
2620
Eric Laurent8fc147b2018-07-22 19:13:55 -07002621void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002622{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002623 ALOGV("%s portId %d", __FUNCTION__, portId);
2624
2625 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2626 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002627 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002628 return;
2629 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002630 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002631 audio_io_handle_t input = inputDesc->mIoHandle;
2632
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002634
Andy Hung39efb7a2018-09-26 15:39:28 -07002635 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002636
Andy Hung39efb7a2018-09-26 15:39:28 -07002637 if (inputDesc->getClientCount() > 0) {
2638 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002639 return;
2640 }
2641
Eric Laurent05b90f82014-08-27 15:32:29 -07002642 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002643 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002644 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002645}
2646
Eric Laurent8f42ea12018-08-08 09:08:25 -07002647void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002648{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002649 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002650
2651 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002652 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002653 }
2654}
2655
Eric Laurent8f42ea12018-08-08 09:08:25 -07002656void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2657{
2658 stopInput(portId);
2659 releaseInput(portId);
2660}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002661
Eric Laurent0dd51852019-04-19 18:18:58 -07002662void AudioPolicyManager::checkCloseInputs() {
2663 // After connecting or disconnecting an input device, close input if:
2664 // - it has no client (was just opened to check profile) OR
2665 // - none of its supported devices are connected anymore OR
2666 // - one of its clients cannot be routed to one of its supported
2667 // devices anymore. Otherwise update device selection
2668 std::vector<audio_io_handle_t> inputsToClose;
2669 for (size_t i = 0; i < mInputs.size(); i++) {
2670 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2671 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002672 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002673 inputsToClose.push_back(mInputs.keyAt(i));
2674 } else {
2675 bool close = false;
2676 for (const auto& client : input->clientsList()) {
2677 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002678 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002679 if (!input->supportedDevices().contains(device)) {
2680 close = true;
2681 break;
2682 }
2683 }
2684 if (close) {
2685 inputsToClose.push_back(mInputs.keyAt(i));
2686 } else {
2687 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2688 }
2689 }
2690 }
2691
2692 for (const audio_io_handle_t handle : inputsToClose) {
2693 ALOGV("%s closing input %d", __func__, handle);
2694 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002695 }
Eric Laurentd4692962014-05-05 18:13:44 -07002696}
2697
François Gaffie251c7f02018-11-07 10:41:08 +01002698void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002699{
2700 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002701 if (indexMin < 0 || indexMax < 0) {
2702 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2703 return;
2704 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002705 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002706
2707 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002708 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2709 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002710 continue;
2711 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002712 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002713 }
Eric Laurente552edb2014-03-10 17:42:56 -07002714}
2715
Eric Laurente0720872014-03-11 09:30:41 -07002716status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002717 int index,
2718 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002719{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002720 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002721 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2722 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2723 return NO_ERROR;
2724 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002725 ALOGV("%s: stream %s attributes=%s", __func__,
2726 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002727 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002728}
2729
Eric Laurente0720872014-03-11 09:30:41 -07002730status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002731 int *index,
2732 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002733{
François Gaffiec005e562018-11-06 15:04:49 +01002734 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2735 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002736 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002737 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002738 deviceTypes = mEngine->getOutputDevicesForStream(
2739 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002740 }
jiabin9a3361e2019-10-01 09:38:30 -07002741 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002742}
2743
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002744status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002745 int index,
2746 audio_devices_t device)
2747{
2748 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002749 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2750 if (group == VOLUME_GROUP_NONE) {
2751 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002752 return BAD_VALUE;
2753 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002754 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002755 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002756 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002757 VolumeSource vs = toVolumeSource(group);
2758 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2759
2760 status = setVolumeCurveIndex(index, device, curves);
2761 if (status != NO_ERROR) {
2762 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2763 return status;
2764 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002765
jiabin9a3361e2019-10-01 09:38:30 -07002766 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002767 auto curCurvAttrs = curves.getAttributes();
2768 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2769 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002770 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002771 } else if (!curves.getStreamTypes().empty()) {
2772 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002773 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002774 } else {
2775 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2776 return BAD_VALUE;
2777 }
jiabin9a3361e2019-10-01 09:38:30 -07002778 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2779 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002780
François Gaffiecfe17322018-11-07 13:41:29 +01002781 // update volume on all outputs and streams matching the following:
2782 // - The requested stream (or a stream matching for volume control) is active on the output
2783 // - The device (or devices) selected by the engine for this stream includes
2784 // the requested device
2785 // - For non default requested device, currently selected device on the output is either the
2786 // requested device or one of the devices selected by the engine for this stream
2787 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2788 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002789 for (size_t i = 0; i < mOutputs.size(); i++) {
2790 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002791 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002792
jiabin9a3361e2019-10-01 09:38:30 -07002793 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2794 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002795 }
François Gaffieed91f582020-01-31 10:35:37 +01002796 if (!(desc->isActive(vs) || isInCall())) {
2797 continue;
2798 }
2799 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2800 curDevices.find(device) == curDevices.end()) {
2801 continue;
2802 }
2803 bool applyVolume = false;
2804 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2805 curSrcDevices.insert(device);
2806 applyVolume = (curSrcDevices.find(
2807 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2808 } else {
2809 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2810 }
2811 if (!applyVolume) {
2812 continue; // next output
2813 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002814 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2815 // If a higher priority strategy is active, and the output is routed to a device with a
2816 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002817 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002818 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002819 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2820 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2821 false /*preferredDevice*/);
2822 if (activeClients.empty()) {
2823 continue;
2824 }
2825 bool isPreempted = false;
2826 bool isHigherPriority = productStrategy < strategy;
2827 for (const auto &client : activeClients) {
2828 if (isHigherPriority && (client->volumeSource() != vs)) {
2829 ALOGV("%s: Strategy=%d (\nrequester:\n"
2830 " group %d, volumeGroup=%d attributes=%s)\n"
2831 " higher priority source active:\n"
2832 " volumeGroup=%d attributes=%s) \n"
2833 " on output %zu, bailing out", __func__, productStrategy,
2834 group, group, toString(attributes).c_str(),
2835 client->volumeSource(), toString(client->attributes()).c_str(), i);
2836 applyVolume = false;
2837 isPreempted = true;
2838 break;
2839 }
2840 // However, continue for loop to ensure no higher prio clients running on output
2841 if (client->volumeSource() == vs) {
2842 applyVolume = true;
2843 }
2844 }
2845 if (isPreempted || applyVolume) {
2846 break;
2847 }
2848 }
2849 if (!applyVolume) {
2850 continue; // next output
2851 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002852 }
François Gaffieed91f582020-01-31 10:35:37 +01002853 //FIXME: workaround for truncated touch sounds
2854 // delayed volume change for system stream to be removed when the problem is
2855 // handled by system UI
2856 status_t volStatus = checkAndSetVolume(
2857 curves, vs, index, desc, curDevices,
2858 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2859 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2860 if (volStatus != NO_ERROR) {
2861 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002862 }
2863 }
François Gaffiecfe17322018-11-07 13:41:29 +01002864 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2865 return status;
2866}
2867
François Gaffieaaac0fd2018-11-22 17:56:39 +01002868status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002869 audio_devices_t device,
2870 IVolumeCurves &volumeCurves)
2871{
2872 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2873 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002874 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2875 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002876 (index > volumeCurves.getVolumeIndexMax())) {
2877 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2878 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2879 return BAD_VALUE;
2880 }
2881 if (!audio_is_output_device(device)) {
2882 return BAD_VALUE;
2883 }
2884
2885 // Force max volume if stream cannot be muted
2886 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2887
François Gaffieaaac0fd2018-11-22 17:56:39 +01002888 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002889 volumeCurves.addCurrentVolumeIndex(device, index);
2890 return NO_ERROR;
2891}
2892
2893status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2894 int &index,
2895 audio_devices_t device)
2896{
2897 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2898 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002899 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002900 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002901 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2902 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002903 }
jiabin9a3361e2019-10-01 09:38:30 -07002904 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002905}
2906
2907status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2908 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002909 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002910{
jiabin9a3361e2019-10-01 09:38:30 -07002911 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002912 return BAD_VALUE;
2913 }
jiabin9a3361e2019-10-01 09:38:30 -07002914 index = curves.getVolumeIndex(deviceTypes);
2915 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002916 return NO_ERROR;
2917}
2918
2919status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2920 int &index)
2921{
2922 index = getVolumeCurves(attr).getVolumeIndexMin();
2923 return NO_ERROR;
2924}
2925
2926status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2927 int &index)
2928{
2929 index = getVolumeCurves(attr).getVolumeIndexMax();
2930 return NO_ERROR;
2931}
2932
Eric Laurent36829f92017-04-07 19:04:42 -07002933audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002934{
2935 // select one output among several suitable for global effects.
2936 // The priority is as follows:
2937 // 1: An offloaded output. If the effect ends up not being offloadable,
2938 // AudioFlinger will invalidate the track and the offloaded output
2939 // will be closed causing the effect to be moved to a PCM output.
2940 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002941 // 3: The primary output
2942 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002943
François Gaffiec005e562018-11-06 15:04:49 +01002944 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2945 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002946 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002947
Eric Laurent36829f92017-04-07 19:04:42 -07002948 if (outputs.size() == 0) {
2949 return AUDIO_IO_HANDLE_NONE;
2950 }
Eric Laurente552edb2014-03-10 17:42:56 -07002951
Eric Laurent36829f92017-04-07 19:04:42 -07002952 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2953 bool activeOnly = true;
2954
2955 while (output == AUDIO_IO_HANDLE_NONE) {
2956 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2957 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2958 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2959
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002960 for (audio_io_handle_t output : outputs) {
2961 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002962 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002963 continue;
2964 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002965 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2966 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002967 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002968 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002969 }
2970 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002971 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002972 }
2973 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002974 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002975 }
2976 }
2977 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2978 output = outputOffloaded;
2979 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2980 output = outputDeepBuffer;
2981 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2982 output = outputPrimary;
2983 } else {
2984 output = outputs[0];
2985 }
2986 activeOnly = false;
2987 }
2988
2989 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002990 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002991 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2992 mMusicEffectOutput = output;
2993 }
2994
2995 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002996 return output;
2997}
2998
Eric Laurent36829f92017-04-07 19:04:42 -07002999audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3000{
3001 return selectOutputForMusicEffects();
3002}
3003
Eric Laurente0720872014-03-11 09:30:41 -07003004status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003005 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003006 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003007 int session,
3008 int id)
3009{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003010 if (session != AUDIO_SESSION_DEVICE) {
3011 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003012 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003013 index = mInputs.indexOfKey(io);
3014 if (index < 0) {
3015 ALOGW("registerEffect() unknown io %d", io);
3016 return INVALID_OPERATION;
3017 }
Eric Laurente552edb2014-03-10 17:42:56 -07003018 }
3019 }
François Gaffiec005e562018-11-06 15:04:49 +01003020 return mEffects.registerEffect(desc, io, session, id,
3021 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3022 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003023}
3024
Eric Laurentc241b0d2018-11-28 09:08:49 -08003025status_t AudioPolicyManager::unregisterEffect(int id)
3026{
3027 if (mEffects.getEffect(id) == nullptr) {
3028 return INVALID_OPERATION;
3029 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003030 if (mEffects.isEffectEnabled(id)) {
3031 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3032 setEffectEnabled(id, false);
3033 }
3034 return mEffects.unregisterEffect(id);
3035}
3036
3037status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3038{
3039 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3040 if (effect == nullptr) {
3041 return INVALID_OPERATION;
3042 }
3043
3044 status_t status = mEffects.setEffectEnabled(id, enabled);
3045 if (status == NO_ERROR) {
3046 mInputs.trackEffectEnabled(effect, enabled);
3047 }
3048 return status;
3049}
3050
Eric Laurent6c796322019-04-09 14:13:17 -07003051
3052status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3053{
3054 mEffects.moveEffects(ids, io);
3055 return NO_ERROR;
3056}
3057
Eric Laurentc75307b2015-03-17 15:29:32 -07003058bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3059{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003060 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003061}
3062
3063bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3064{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003065 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003066}
3067
Eric Laurente0720872014-03-11 09:30:41 -07003068bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003069{
3070 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003071 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003072 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003073 return true;
3074 }
3075 }
3076 return false;
3077}
3078
Eric Laurent275e8e92014-11-30 15:14:47 -08003079// Register a list of custom mixes with their attributes and format.
3080// When a mix is registered, corresponding input and output profiles are
3081// added to the remote submix hw module. The profile contains only the
3082// parameters (sampling rate, format...) specified by the mix.
3083// The corresponding input remote submix device is also connected.
3084//
3085// When a remote submix device is connected, the address is checked to select the
3086// appropriate profile and the corresponding input or output stream is opened.
3087//
3088// When capture starts, getInputForAttr() will:
3089// - 1 look for a mix matching the address passed in attribtutes tags if any
3090// - 2 if none found, getDeviceForInputSource() will:
3091// - 2.1 look for a mix matching the attributes source
3092// - 2.2 if none found, default to device selection by policy rules
3093// At this time, the corresponding output remote submix device is also connected
3094// and active playback use cases can be transferred to this mix if needed when reconnecting
3095// after AudioTracks are invalidated
3096//
3097// When playback starts, getOutputForAttr() will:
3098// - 1 look for a mix matching the address passed in attribtutes tags if any
3099// - 2 if none found, look for a mix matching the attributes usage
3100// - 3 if none found, default to device and output selection by policy rules.
3101
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003102status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003103{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003104 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3105 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003106 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003107 sp<HwModule> rSubmixModule;
3108 // examine each mix's route type
3109 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003110 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003111 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3112 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3113 ALOGE("Unsupported Policy Mix %zu of %zu: "
3114 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3115 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003116 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003117 break;
3118 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003119 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3120 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003121 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003122 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3123 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003124 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003125 rSubmixModule = mHwModules.getModuleFromName(
3126 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3127 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003128 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003129 i);
3130 res = INVALID_OPERATION;
3131 break;
3132 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003133 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003134
Eric Laurent97ac8712018-07-27 18:59:02 -07003135 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003136 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003137 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003138 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003139 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3140 } else {
3141 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3142 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003143 }
François Gaffie036e1e92015-03-19 10:16:24 +01003144
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003145 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003146 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003147 res = INVALID_OPERATION;
3148 break;
3149 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003150 audio_config_t outputConfig = mix.mFormat;
3151 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003152 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3153 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003154 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3155 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003156 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003157 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003158 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003159 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003160
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003161 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003162 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3163 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3164 ALOGE("Failed to set remote submix device available, type %u, address %s",
3165 mix.mDeviceType, address.string());
3166 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003167 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003168 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3169 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003170 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003171 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003172 i, mixes.size(), type, address.string());
3173
3174 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3175 mix.mDeviceType, mix.mDeviceAddress,
3176 String8(), AUDIO_FORMAT_DEFAULT);
3177 if (device == nullptr) {
3178 res = INVALID_OPERATION;
3179 break;
3180 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003181
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003182 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003183 // First try to find an already opened output supporting the device
3184 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003185 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003186
Eric Laurentc529cf62020-04-17 18:19:10 -07003187 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003188 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003189 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3190 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003191 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003192 } else {
3193 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003194 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003195 }
3196 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003197 // If no output found, try to find a direct output profile supporting the device
3198 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3199 sp<HwModule> module = mHwModules[i];
3200 for (size_t j = 0;
3201 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3202 j++) {
3203 sp<IOProfile> profile = module->getOutputProfiles()[j];
3204 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3205 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3206 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3207 address.string());
3208 res = INVALID_OPERATION;
3209 } else {
3210 foundOutput = true;
3211 }
3212 }
3213 }
3214 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003215 if (res != NO_ERROR) {
3216 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003217 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003218 res = INVALID_OPERATION;
3219 break;
3220 } else if (!foundOutput) {
3221 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003222 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003223 res = INVALID_OPERATION;
3224 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003225 } else {
3226 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003227 }
Eric Laurentc722f302014-12-10 11:21:49 -08003228 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003229 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003230 if (res != NO_ERROR) {
3231 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003232 } else if (checkOutputs) {
3233 checkForDeviceAndOutputChanges();
3234 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003235 }
3236 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003237}
3238
3239status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3240{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003241 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003242 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003243 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003244 sp<HwModule> rSubmixModule;
3245 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003246 for (const auto& mix : mixes) {
3247 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003248
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003249 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003250 rSubmixModule = mHwModules.getModuleFromName(
3251 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3252 if (rSubmixModule == 0) {
3253 res = INVALID_OPERATION;
3254 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003255 }
3256 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003257
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003258 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003259
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003260 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003261 res = INVALID_OPERATION;
3262 continue;
3263 }
3264
Kevin Rocard04ed0462019-05-02 17:53:24 -07003265 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3266 if (getDeviceConnectionState(device, address.string()) ==
3267 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3268 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3269 address.string(), "remote-submix",
3270 AUDIO_FORMAT_DEFAULT);
3271 if (res != OK) {
3272 ALOGE("Error making RemoteSubmix device unavailable for mix "
3273 "with type %d, address %s", device, address.string());
3274 }
3275 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003276 }
jiabin5740f082019-08-19 15:08:30 -07003277 rSubmixModule->removeOutputProfile(address.c_str());
3278 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003279
Kevin Rocard153f92d2018-12-18 18:33:28 -08003280 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003281 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003282 res = INVALID_OPERATION;
3283 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003284 } else {
3285 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003286 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003287 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003288 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003289 if (res == NO_ERROR && checkOutputs) {
3290 checkForDeviceAndOutputChanges();
3291 updateCallAndOutputRouting();
3292 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003293 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003294}
3295
Mikhail Naganov100f0122018-11-29 11:22:16 -08003296void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3297{
3298 size_t i = 0;
3299 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3300 for (const auto& fmt : mManualSurroundFormats) {
3301 if (i++ != 0) dst->append(", ");
3302 std::string sfmt;
3303 FormatConverter::toString(fmt, sfmt);
3304 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3305 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3306 }
3307}
3308
Eric Laurentc529cf62020-04-17 18:19:10 -07003309// Returns true if all devices types match the predicate and are supported by one HW module
3310bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003311 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003312 std::function<bool(audio_devices_t)> predicate,
3313 const char *context) {
3314 for (size_t i = 0; i < devices.size(); i++) {
3315 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003316 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003317 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003318 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003319 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003320 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003321 return false;
3322 }
3323 }
3324 return true;
3325}
3326
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003327status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003328 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003329 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003330 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3331 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003332 }
3333 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003334 if (res != NO_ERROR) {
3335 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3336 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003337 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003338
3339 checkForDeviceAndOutputChanges();
3340 updateCallAndOutputRouting();
3341
3342 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003343}
3344
3345status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3346 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003347 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3348 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003349 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003350 __FUNCTION__, uid);
3351 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003352 }
3353
Eric Laurentc529cf62020-04-17 18:19:10 -07003354 checkForDeviceAndOutputChanges();
3355 updateCallAndOutputRouting();
3356
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003357 return res;
3358}
3359
Eric Laurent2517af32020-11-25 15:31:27 +01003360
jiabin0a488932020-08-07 17:32:40 -07003361status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3362 device_role_t role,
3363 const AudioDeviceTypeAddrVector &devices) {
3364 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3365 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003366
Eric Laurentc529cf62020-04-17 18:19:10 -07003367 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003368 return BAD_VALUE;
3369 }
jiabin0a488932020-08-07 17:32:40 -07003370 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003371 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003372 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3373 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003374 return status;
3375 }
3376
3377 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003378
3379 bool forceVolumeReeval = false;
3380 // FIXME: workaround for truncated touch sounds
3381 // to be removed when the problem is handled by system UI
3382 uint32_t delayMs = 0;
3383 if (strategy == mCommunnicationStrategy) {
3384 forceVolumeReeval = true;
3385 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3386 updateInputRouting();
3387 }
3388 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003389
3390 return NO_ERROR;
3391}
3392
3393void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3394{
3395 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003396 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003397 // Only apply special touch sound delay once
3398 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003399 }
3400 for (size_t i = 0; i < mOutputs.size(); i++) {
3401 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3402 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3403 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3404 // As done in setDeviceConnectionState, we could also fix default device issue by
3405 // preventing the force re-routing in case of default dev that distinguishes on address.
3406 // Let's give back to engine full device choice decision however.
3407 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003408 // Only apply special touch sound delay once
3409 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003410 }
3411 if (forceVolumeReeval && !newDevices.isEmpty()) {
3412 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3413 }
3414 }
3415}
3416
Eric Laurent2517af32020-11-25 15:31:27 +01003417void AudioPolicyManager::updateInputRouting() {
3418 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303419 // Skip for hotword recording as the input device switch
3420 // is handled within sound trigger HAL
3421 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3422 continue;
3423 }
Eric Laurent2517af32020-11-25 15:31:27 +01003424 auto newDevice = getNewInputDevice(activeDesc);
3425 // Force new input selection if the new device can not be reached via current input
3426 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3427 setInputDevice(activeDesc->mIoHandle, newDevice);
3428 } else {
3429 closeInput(activeDesc->mIoHandle);
3430 }
3431 }
3432}
3433
jiabin0a488932020-08-07 17:32:40 -07003434status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3435 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003436{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003437 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003438
jiabin0a488932020-08-07 17:32:40 -07003439 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003440 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003441 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3442 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003443 return status;
3444 }
3445
3446 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003447
3448 bool forceVolumeReeval = false;
3449 // FIXME: workaround for truncated touch sounds
3450 // to be removed when the problem is handled by system UI
3451 uint32_t delayMs = 0;
3452 if (strategy == mCommunnicationStrategy) {
3453 forceVolumeReeval = true;
3454 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3455 updateInputRouting();
3456 }
3457 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003458
3459 return NO_ERROR;
3460}
3461
jiabin0a488932020-08-07 17:32:40 -07003462status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3463 device_role_t role,
3464 AudioDeviceTypeAddrVector &devices) {
3465 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003466}
3467
Jiabin Huang3b98d322020-09-03 17:54:16 +00003468status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3469 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3470 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3471 dumpAudioDeviceTypeAddrVector(devices).c_str());
3472
Mikhail Naganov55773032020-10-01 15:08:13 -07003473 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003474 return BAD_VALUE;
3475 }
3476 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3477 ALOGW_IF(status != NO_ERROR,
3478 "Engine could not set preferred devices %s for audio source %d role %d",
3479 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3480
3481 return status;
3482}
3483
3484status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3485 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3486 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3487 dumpAudioDeviceTypeAddrVector(devices).c_str());
3488
Mikhail Naganov55773032020-10-01 15:08:13 -07003489 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003490 return BAD_VALUE;
3491 }
3492 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3493 ALOGW_IF(status != NO_ERROR,
3494 "Engine could not add preferred devices %s for audio source %d role %d",
3495 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3496
Eric Laurent2517af32020-11-25 15:31:27 +01003497 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003498 return status;
3499}
3500
3501status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3502 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3503{
3504 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3505 dumpAudioDeviceTypeAddrVector(devices).c_str());
3506
Mikhail Naganov55773032020-10-01 15:08:13 -07003507 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003508 return BAD_VALUE;
3509 }
3510
3511 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3512 audioSource, role, devices);
3513 ALOGW_IF(status != NO_ERROR,
3514 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3515
Eric Laurent2517af32020-11-25 15:31:27 +01003516 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003517 return status;
3518}
3519
3520status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3521 device_role_t role) {
3522 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3523
3524 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3525 ALOGW_IF(status != NO_ERROR,
3526 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3527
Eric Laurent2517af32020-11-25 15:31:27 +01003528 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003529 return status;
3530}
3531
3532status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3533 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3534 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3535}
3536
Oscar Azucena90e77632019-11-27 17:12:28 -08003537status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003538 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003539 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003540 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3541 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003542 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003543 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3544 if (status != NO_ERROR) {
3545 ALOGE("%s() could not set device affinity for userId %d",
3546 __FUNCTION__, userId);
3547 return status;
3548 }
3549
3550 // reevaluate outputs for all devices
3551 checkForDeviceAndOutputChanges();
3552 updateCallAndOutputRouting();
3553
3554 return NO_ERROR;
3555}
3556
3557status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003558 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003559 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3560 if (status != NO_ERROR) {
3561 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3562 __FUNCTION__, userId);
3563 return status;
3564 }
3565
3566 // reevaluate outputs for all devices
3567 checkForDeviceAndOutputChanges();
3568 updateCallAndOutputRouting();
3569
3570 return NO_ERROR;
3571}
3572
Andy Hungc29d82b2018-10-05 12:23:17 -07003573void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003574{
Andy Hungc29d82b2018-10-05 12:23:17 -07003575 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3576 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003577 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003578 std::string stateLiteral;
3579 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003580 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003581 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3582 "communications", "media", "record", "dock", "system",
3583 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3584 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3585 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003586 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3587 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3588 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3589 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3590 dst->append(" (MANUAL: ");
3591 dumpManualSurroundFormats(dst);
3592 dst->append(")");
3593 }
3594 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003595 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003596 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3597 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003598 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003599 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003600
Andy Hungc29d82b2018-10-05 12:23:17 -07003601 mAvailableOutputDevices.dump(dst, String8("Available output"));
3602 mAvailableInputDevices.dump(dst, String8("Available input"));
3603 mHwModulesAll.dump(dst);
3604 mOutputs.dump(dst);
3605 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003606 mEffects.dump(dst);
3607 mAudioPatches.dump(dst);
3608 mPolicyMixes.dump(dst);
3609 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003610
Kevin Rocardb99cc752019-03-21 20:52:24 -07003611 dst->appendFormat(" AllowedCapturePolicies:\n");
3612 for (auto& policy : mAllowedCapturePolicies) {
3613 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3614 }
3615
François Gaffiec005e562018-11-06 15:04:49 +01003616 dst->appendFormat("\nPolicy Engine dump:\n");
3617 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003618}
3619
3620status_t AudioPolicyManager::dump(int fd)
3621{
3622 String8 result;
3623 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003624 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003625 return NO_ERROR;
3626}
3627
Kevin Rocardb99cc752019-03-21 20:52:24 -07003628status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3629{
3630 mAllowedCapturePolicies[uid] = capturePolicy;
3631 return NO_ERROR;
3632}
3633
Eric Laurente552edb2014-03-10 17:42:56 -07003634// This function checks for the parameters which can be offloaded.
3635// This can be enhanced depending on the capability of the DSP and policy
3636// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003637audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003638{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003639 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003640 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003641 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003642 offloadInfo.format,
3643 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3644 offloadInfo.has_video);
3645
Andy Hung2ddee192015-12-18 17:34:44 -08003646 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003647 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003648 }
3649
Eric Laurente552edb2014-03-10 17:42:56 -07003650 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003651 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003652 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3653 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003654 }
3655
3656 // Check if stream type is music, then only allow offload as of now.
3657 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3658 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003659 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3660 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003661 }
3662
3663 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003664 const bool allowOffloadWithVideo =
3665 property_get_bool("audio.offload.video", false /* default_value */);
3666 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003667 ALOGV("%s: has_video == true, returning false", __func__);
3668 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003669 }
3670
3671 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003672 const int min_duration_secs = property_get_int32(
3673 "audio.offload.min.duration.secs", -1 /* default_value */);
3674 if (min_duration_secs >= 0) {
3675 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003676 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3677 __func__, min_duration_secs);
3678 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003679 }
3680 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003681 ALOGV("%s: Offload denied by duration < default min(=%u)",
3682 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3683 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003684 }
3685
3686 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3687 // creating an offloaded track and tearing it down immediately after start when audioflinger
3688 // detects there is an active non offloadable effect.
3689 // FIXME: We should check the audio session here but we do not have it in this context.
3690 // This may prevent offloading in rare situations where effects are left active by apps
3691 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003692 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003693 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003694 }
3695
3696 // See if there is a profile to support this.
3697 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003698 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003699 offloadInfo.sample_rate,
3700 offloadInfo.format,
3701 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003702 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3703 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003704 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3705 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3706 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003707 if (profile == nullptr) {
3708 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3709 }
3710 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3711 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3712 }
3713 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003714}
3715
Michael Chana94fbb22018-04-24 14:31:19 +10003716bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3717 const audio_attributes_t& attributes) {
3718 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003719 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003720 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003721 config.sample_rate,
3722 config.format,
3723 config.channel_mask,
3724 output_flags,
3725 true /* directOnly */);
3726 ALOGV("%s() profile %sfound with name: %s, "
3727 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3728 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003729 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003730 config.sample_rate, config.format, config.channel_mask, output_flags);
3731 return (profile != 0);
3732}
3733
Eric Laurent6a94d692014-05-20 11:18:06 -07003734status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3735 audio_port_type_t type,
3736 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003737 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003738 unsigned int *generation)
3739{
jiabin19cdba52020-11-24 11:28:58 -08003740 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3741 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003742 return BAD_VALUE;
3743 }
3744 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003745 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003746 *num_ports = 0;
3747 }
3748
3749 size_t portsWritten = 0;
3750 size_t portsMax = *num_ports;
3751 *num_ports = 0;
3752 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003753 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3754 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003755 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003756 for (const auto& dev : mAvailableOutputDevices) {
3757 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003758 continue;
3759 }
3760 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003761 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003762 }
3763 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003764 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003765 }
3766 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003767 for (const auto& dev : mAvailableInputDevices) {
3768 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003769 continue;
3770 }
3771 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003772 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003773 }
3774 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003775 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003776 }
3777 }
3778 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3779 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3780 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3781 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3782 }
3783 *num_ports += mInputs.size();
3784 }
3785 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003786 size_t numOutputs = 0;
3787 for (size_t i = 0; i < mOutputs.size(); i++) {
3788 if (!mOutputs[i]->isDuplicated()) {
3789 numOutputs++;
3790 if (portsWritten < portsMax) {
3791 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3792 }
3793 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003794 }
Eric Laurent84c70242014-06-23 08:46:27 -07003795 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003796 }
3797 }
3798 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003799 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003800 return NO_ERROR;
3801}
3802
jiabin19cdba52020-11-24 11:28:58 -08003803status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003804{
Eric Laurent99fcae42018-05-17 16:59:18 -07003805 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3806 return BAD_VALUE;
3807 }
3808 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3809 if (dev != 0) {
3810 dev->toAudioPort(port);
3811 return NO_ERROR;
3812 }
3813 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3814 if (dev != 0) {
3815 dev->toAudioPort(port);
3816 return NO_ERROR;
3817 }
3818 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3819 if (out != 0) {
3820 out->toAudioPort(port);
3821 return NO_ERROR;
3822 }
3823 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3824 if (in != 0) {
3825 in->toAudioPort(port);
3826 return NO_ERROR;
3827 }
3828 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003829}
3830
François Gaffieafd4cea2019-11-18 15:50:22 +01003831status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3832 audio_patch_handle_t *handle,
3833 uid_t uid, uint32_t delayMs,
3834 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003835{
François Gaffieafd4cea2019-11-18 15:50:22 +01003836 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003837 if (handle == NULL || patch == NULL) {
3838 return BAD_VALUE;
3839 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003840 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003841
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003842 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003843 return BAD_VALUE;
3844 }
3845 // only one source per audio patch supported for now
3846 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003847 return INVALID_OPERATION;
3848 }
Eric Laurent874c42872014-08-08 15:13:39 -07003849
3850 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003851 return INVALID_OPERATION;
3852 }
Eric Laurent874c42872014-08-08 15:13:39 -07003853 for (size_t i = 0; i < patch->num_sinks; i++) {
3854 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3855 return INVALID_OPERATION;
3856 }
3857 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003858
3859 sp<AudioPatch> patchDesc;
3860 ssize_t index = mAudioPatches.indexOfKey(*handle);
3861
François Gaffieafd4cea2019-11-18 15:50:22 +01003862 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3863 patch->sources[0].role,
3864 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003865#if LOG_NDEBUG == 0
3866 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003867 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3868 patch->sinks[i].role,
3869 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003870 }
3871#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003872
3873 if (index >= 0) {
3874 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003875 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3876 __func__, mUidCached, patchDesc->getUid(), uid);
3877 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003878 return INVALID_OPERATION;
3879 }
3880 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003881 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003882 }
3883
3884 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003885 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003886 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003887 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003888 return BAD_VALUE;
3889 }
Eric Laurent84c70242014-06-23 08:46:27 -07003890 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3891 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003892 if (patchDesc != 0) {
3893 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003894 ALOGV("%s source id differs for patch current id %d new id %d",
3895 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003896 return BAD_VALUE;
3897 }
3898 }
Eric Laurent874c42872014-08-08 15:13:39 -07003899 DeviceVector devices;
3900 for (size_t i = 0; i < patch->num_sinks; i++) {
3901 // Only support mix to devices connection
3902 // TODO add support for mix to mix connection
3903 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003904 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003905 return INVALID_OPERATION;
3906 }
3907 sp<DeviceDescriptor> devDesc =
3908 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3909 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003910 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003911 return BAD_VALUE;
3912 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003913
François Gaffie11d30102018-11-02 16:09:09 +01003914 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003915 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003916 NULL, // updatedSamplingRate
3917 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003918 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003919 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003920 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003921 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003922 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003923 return INVALID_OPERATION;
3924 }
3925 devices.add(devDesc);
3926 }
3927 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003928 return INVALID_OPERATION;
3929 }
Eric Laurent874c42872014-08-08 15:13:39 -07003930
Eric Laurent6a94d692014-05-20 11:18:06 -07003931 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003932 ALOGV("%s setting device %s on output %d",
3933 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003934 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003935 index = mAudioPatches.indexOfKey(*handle);
3936 if (index >= 0) {
3937 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003938 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003939 }
3940 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003941 patchDesc->setUid(uid);
3942 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003943 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003944 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003945 return INVALID_OPERATION;
3946 }
3947 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3948 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3949 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003950 // only one sink supported when connecting an input device to a mix
3951 if (patch->num_sinks > 1) {
3952 return INVALID_OPERATION;
3953 }
François Gaffie53615e22015-03-19 09:24:12 +01003954 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003955 if (inputDesc == NULL) {
3956 return BAD_VALUE;
3957 }
3958 if (patchDesc != 0) {
3959 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3960 return BAD_VALUE;
3961 }
3962 }
François Gaffie11d30102018-11-02 16:09:09 +01003963 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003964 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003965 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003966 return BAD_VALUE;
3967 }
3968
François Gaffie11d30102018-11-02 16:09:09 +01003969 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003970 patch->sinks[0].sample_rate,
3971 NULL, /*updatedSampleRate*/
3972 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003973 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003974 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003975 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003976 // FIXME for the parameter type,
3977 // and the NONE
3978 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003979 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 return INVALID_OPERATION;
3981 }
3982 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003983 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003984 device->toString().c_str(), inputDesc->mIoHandle);
3985 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003986 index = mAudioPatches.indexOfKey(*handle);
3987 if (index >= 0) {
3988 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003989 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 }
3991 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003992 patchDesc->setUid(uid);
3993 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003994 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003995 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003996 return INVALID_OPERATION;
3997 }
3998 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3999 // device to device connection
4000 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004001 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004002 return BAD_VALUE;
4003 }
4004 }
François Gaffie11d30102018-11-02 16:09:09 +01004005 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004006 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004007 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004008 return BAD_VALUE;
4009 }
Eric Laurent874c42872014-08-08 15:13:39 -07004010
Eric Laurent6a94d692014-05-20 11:18:06 -07004011 //update source and sink with our own data as the data passed in the patch may
4012 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004013 PatchBuilder patchBuilder;
4014 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004015
4016 // if first sink is to MSD, establish single MSD patch
4017 if (getMsdAudioOutDevices().contains(
4018 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4019 ALOGV("%s patching to MSD", __FUNCTION__);
4020 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4021 goto installPatch;
4022 }
4023
François Gaffieafd4cea2019-11-18 15:50:22 +01004024 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4025 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004026
Eric Laurent874c42872014-08-08 15:13:39 -07004027 for (size_t i = 0; i < patch->num_sinks; i++) {
4028 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004029 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004030 return INVALID_OPERATION;
4031 }
François Gaffie11d30102018-11-02 16:09:09 +01004032 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004033 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004034 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004035 return BAD_VALUE;
4036 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004037 audio_port_config sinkPortConfig = {};
4038 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4039 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004040
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004041 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4042 // volume management purpose (tracking activity)
4043 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4044 // in config XML to reach the sink so that is can be declared as available.
4045 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4046 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4047 if (sourceDesc != nullptr) {
4048 // take care of dynamic routing for SwOutput selection,
4049 audio_attributes_t attributes = sourceDesc->attributes();
4050 audio_stream_type_t stream = sourceDesc->stream();
4051 audio_attributes_t resultAttr;
4052 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4053 config.sample_rate = sourceDesc->config().sample_rate;
4054 config.channel_mask = sourceDesc->config().channel_mask;
4055 config.format = sourceDesc->config().format;
4056 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4057 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4058 bool isRequestedDeviceForExclusiveUse = false;
4059 output_type_t outputType;
4060 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4061 &stream, sourceDesc->uid(), &config, &flags,
4062 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4063 nullptr, &outputType);
4064 if (output == AUDIO_IO_HANDLE_NONE) {
4065 ALOGV("%s no output for device %s",
4066 __FUNCTION__, sinkDevice->toString().c_str());
4067 return INVALID_OPERATION;
4068 }
4069 outputDesc = mOutputs.valueFor(output);
4070 if (outputDesc->isDuplicated()) {
4071 ALOGE("%s output is duplicated", __func__);
4072 return INVALID_OPERATION;
4073 }
4074 sourceDesc->setSwOutput(outputDesc);
4075 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004076 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004077 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004078 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004079 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004080 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4081 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004082 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4083 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004084 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4085 (sourceDesc != nullptr &&
4086 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004087 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004088 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004089 return INVALID_OPERATION;
4090 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004091 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004092 SortedVector<audio_io_handle_t> outputs =
4093 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4094 // if the sink device is reachable via an opened output stream, request to
4095 // go via this output stream by adding a second source to the patch
4096 // description
4097 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004098 if (output != AUDIO_IO_HANDLE_NONE) {
4099 outputDesc = mOutputs.valueFor(output);
4100 if (outputDesc->isDuplicated()) {
4101 ALOGV("%s output for device %s is duplicated",
4102 __FUNCTION__, sinkDevice->toString().c_str());
4103 return INVALID_OPERATION;
4104 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004105 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004106 }
4107 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004108 audio_port_config srcMixPortConfig = {};
4109 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004110 // for volume control, we may need a valid stream
4111 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4112 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4113 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004114 }
Eric Laurent83b88082014-06-20 18:31:16 -07004115 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004116 }
4117 // TODO: check from routing capabilities in config file and other conflicting patches
4118
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004119installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004120 status_t status = installPatch(
4121 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004122 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004123 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004124 return INVALID_OPERATION;
4125 }
4126 } else {
4127 return BAD_VALUE;
4128 }
4129 } else {
4130 return BAD_VALUE;
4131 }
4132 return NO_ERROR;
4133}
4134
4135status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4136 uid_t uid)
4137{
4138 ALOGV("releaseAudioPatch() patch %d", handle);
4139
4140 ssize_t index = mAudioPatches.indexOfKey(handle);
4141
4142 if (index < 0) {
4143 return BAD_VALUE;
4144 }
4145 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004146 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4147 __func__, mUidCached, patchDesc->getUid(), uid);
4148 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004149 return INVALID_OPERATION;
4150 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004151 return releaseAudioPatchInternal(handle);
4152}
Eric Laurent6a94d692014-05-20 11:18:06 -07004153
François Gaffieafd4cea2019-11-18 15:50:22 +01004154status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4155 uint32_t delayMs)
4156{
4157 ALOGV("%s patch %d", __func__, handle);
4158 if (mAudioPatches.indexOfKey(handle) < 0) {
4159 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4160 return BAD_VALUE;
4161 }
4162 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004163 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004164 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004165 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004166 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004168 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004169 return BAD_VALUE;
4170 }
4171
François Gaffie11d30102018-11-02 16:09:09 +01004172 setOutputDevices(outputDesc,
4173 getNewOutputDevices(outputDesc, true /*fromCache*/),
4174 true,
4175 0,
4176 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004177 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4178 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004179 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004180 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004181 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004182 return BAD_VALUE;
4183 }
4184 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004185 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004186 true,
4187 NULL);
4188 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004189 status_t status =
4190 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4191 ALOGV("%s patch panel returned %d patchHandle %d",
4192 __func__, status, patchDesc->getAfHandle());
4193 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004194 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004195 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004196 // SW Bridge
4197 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4198 sp<SwAudioOutputDescriptor> outputDesc =
4199 mOutputs.getOutputFromId(patch->sources[1].id);
4200 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004201 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4202 // releaseOutput has already called closeOuput in case of direct output
4203 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004204 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004205 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4206 // force SwOutput patch removal as AF counter part patch has already gone.
4207 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4208 removeAudioPatch(outputDesc->getPatchHandle());
4209 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004210 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4211 setOutputDevices(outputDesc,
4212 getNewOutputDevices(outputDesc, true /*fromCache*/),
4213 true, /*force*/
4214 0,
4215 NULL);
4216 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004217 } else {
4218 return BAD_VALUE;
4219 }
4220 } else {
4221 return BAD_VALUE;
4222 }
4223 return NO_ERROR;
4224}
4225
4226status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4227 struct audio_patch *patches,
4228 unsigned int *generation)
4229{
François Gaffie53615e22015-03-19 09:24:12 +01004230 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004231 return BAD_VALUE;
4232 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004233 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004234 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004235}
4236
Eric Laurente1715a42014-05-20 11:30:42 -07004237status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004238{
Eric Laurente1715a42014-05-20 11:30:42 -07004239 ALOGV("setAudioPortConfig()");
4240
4241 if (config == NULL) {
4242 return BAD_VALUE;
4243 }
4244 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4245 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004246 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4247 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004248 }
4249
Eric Laurenta121f902014-06-03 13:32:54 -07004250 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004251 if (config->type == AUDIO_PORT_TYPE_MIX) {
4252 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004253 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004254 if (outputDesc == NULL) {
4255 return BAD_VALUE;
4256 }
Eric Laurent84c70242014-06-23 08:46:27 -07004257 ALOG_ASSERT(!outputDesc->isDuplicated(),
4258 "setAudioPortConfig() called on duplicated output %d",
4259 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004260 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004261 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004262 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004263 if (inputDesc == NULL) {
4264 return BAD_VALUE;
4265 }
Eric Laurenta121f902014-06-03 13:32:54 -07004266 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004267 } else {
4268 return BAD_VALUE;
4269 }
4270 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4271 sp<DeviceDescriptor> deviceDesc;
4272 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4273 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4274 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4275 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4276 } else {
4277 return BAD_VALUE;
4278 }
4279 if (deviceDesc == NULL) {
4280 return BAD_VALUE;
4281 }
Eric Laurenta121f902014-06-03 13:32:54 -07004282 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004283 } else {
4284 return BAD_VALUE;
4285 }
4286
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004287 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004288 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4289 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004290 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004291 audioPortConfig->toAudioPortConfig(&newConfig, config);
4292 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004293 }
Eric Laurenta121f902014-06-03 13:32:54 -07004294 if (status != NO_ERROR) {
4295 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004296 }
Eric Laurente1715a42014-05-20 11:30:42 -07004297
4298 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004299}
4300
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004301void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4302{
Eric Laurentd60560a2015-04-10 11:31:20 -07004303 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004304 clearAudioPatches(uid);
4305 clearSessionRoutes(uid);
4306}
4307
Eric Laurent6a94d692014-05-20 11:18:06 -07004308void AudioPolicyManager::clearAudioPatches(uid_t uid)
4309{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004310 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004311 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004312 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004313 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004314 }
4315 }
4316}
4317
François Gaffiec005e562018-11-06 15:04:49 +01004318void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004319{
François Gaffiec005e562018-11-06 15:04:49 +01004320 // Take the first attributes following the product strategy as it is used to retrieve the routed
4321 // device. All attributes wihin a strategy follows the same "routing strategy"
4322 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4323 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004324 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004325 for (size_t j = 0; j < mOutputs.size(); j++) {
4326 if (mOutputs.keyAt(j) == ouptutToSkip) {
4327 continue;
4328 }
4329 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004330 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004331 continue;
4332 }
4333 // If the default device for this strategy is on another output mix,
4334 // invalidate all tracks in this strategy to force re connection.
4335 // Otherwise select new device on the output mix.
4336 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004337 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4338 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004339 }
4340 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004341 setOutputDevices(
4342 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004343 }
4344 }
4345}
4346
4347void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4348{
4349 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004350 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004351 for (size_t i = 0; i < mOutputs.size(); i++) {
4352 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004353 for (const auto& client : outputDesc->getClientIterable()) {
4354 if (client->hasPreferredDevice() && client->uid() == uid) {
4355 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004356 auto clientStrategy = client->strategy();
4357 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4358 end(affectedStrategies)) {
4359 continue;
4360 }
4361 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004362 }
4363 }
4364 }
4365 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004366 for (const auto& strategy : affectedStrategies) {
4367 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004368 }
4369
4370 // remove input routes associated with this uid
4371 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004372 for (size_t i = 0; i < mInputs.size(); i++) {
4373 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004374 for (const auto& client : inputDesc->getClientIterable()) {
4375 if (client->hasPreferredDevice() && client->uid() == uid) {
4376 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4377 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004378 }
4379 }
4380 }
4381 // reroute inputs if necessary
4382 SortedVector<audio_io_handle_t> inputsToClose;
4383 for (size_t i = 0; i < mInputs.size(); i++) {
4384 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004385 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004386 inputsToClose.add(inputDesc->mIoHandle);
4387 }
4388 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004389 for (const auto& input : inputsToClose) {
4390 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004391 }
4392}
4393
Eric Laurentd60560a2015-04-10 11:31:20 -07004394void AudioPolicyManager::clearAudioSources(uid_t uid)
4395{
4396 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004397 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4398 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004399 stopAudioSource(mAudioSources.keyAt(i));
4400 }
4401 }
4402}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004403
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004404status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4405 audio_io_handle_t *ioHandle,
4406 audio_devices_t *device)
4407{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004408 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4409 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004410 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004411 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004412
François Gaffiedf372692015-03-19 10:43:27 +01004413 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004414}
4415
Eric Laurentd60560a2015-04-10 11:31:20 -07004416status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004417 const audio_attributes_t *attributes,
4418 audio_port_handle_t *portId,
4419 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004420{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004421 ALOGV("%s", __FUNCTION__);
4422 *portId = AUDIO_PORT_HANDLE_NONE;
4423
4424 if (source == NULL || attributes == NULL || portId == NULL) {
4425 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4426 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004427 return BAD_VALUE;
4428 }
4429
Eric Laurentd60560a2015-04-10 11:31:20 -07004430 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4431 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004432 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4433 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004434 return INVALID_OPERATION;
4435 }
4436
François Gaffie11d30102018-11-02 16:09:09 +01004437 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004438 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004439 String8(source->ext.device.address),
4440 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004441 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004442 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004443 return BAD_VALUE;
4444 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004445
jiabin4ef93452019-09-10 14:29:54 -07004446 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004447
François Gaffieaaac0fd2018-11-22 17:56:39 +01004448 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004449 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004450 mEngine->getStreamTypeForAttributes(*attributes),
4451 mEngine->getProductStrategyForAttributes(*attributes),
4452 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004453
4454 status_t status = connectAudioSource(sourceDesc);
4455 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004456 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004457 }
4458 return status;
4459}
4460
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004461status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004462{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004463 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004464
4465 // make sure we only have one patch per source.
4466 disconnectAudioSource(sourceDesc);
4467
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004468 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004469 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4470 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4471 sourceDesc->srcDevice()->type(),
4472 String8(sourceDesc->srcDevice()->address().c_str()),
4473 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004474 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004475 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004476 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004477 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004478 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4479 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4480 return INVALID_OPERATION;
4481 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004482 PatchBuilder patchBuilder;
4483 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4484 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4485 status_t status =
4486 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4487 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4488 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4489 return INVALID_OPERATION;
4490 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004491 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4493 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4494 if (swOutput != 0) {
4495 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004496 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004497 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004498 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004499 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004500 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004501 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004502 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004503 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004504 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004505 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004506 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004507 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4508 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004509 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004510 if (delayMs != 0) {
4511 usleep(delayMs * 1000);
4512 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004513 } else {
4514 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4515 if (hwOutputDesc != 0) {
4516 // create Hwoutput and add to mHwOutputs
4517 } else {
4518 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4519 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004520 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004521 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004522
4523FailureSourceActive:
4524 swOutput->stop();
4525 releaseOutput(sourceDesc->portId());
4526FailureSourceAdded:
4527 sourceDesc->setSwOutput(nullptr);
4528FailureReleasePatch:
4529 releaseAudioPatchInternal(handle);
4530 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004531}
4532
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004533status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004534{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004535 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4536 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004537 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004538 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004539 return BAD_VALUE;
4540 }
4541 status_t status = disconnectAudioSource(sourceDesc);
4542
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004543 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004544 return status;
4545}
4546
Andy Hung2ddee192015-12-18 17:34:44 -08004547status_t AudioPolicyManager::setMasterMono(bool mono)
4548{
4549 if (mMasterMono == mono) {
4550 return NO_ERROR;
4551 }
4552 mMasterMono = mono;
4553 // if enabling mono we close all offloaded devices, which will invalidate the
4554 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4555 // for recreating the new AudioTrack as non-offloaded PCM.
4556 //
4557 // If disabling mono, we leave all tracks as is: we don't know which clients
4558 // and tracks are able to be recreated as offloaded. The next "song" should
4559 // play back offloaded.
4560 if (mMasterMono) {
4561 Vector<audio_io_handle_t> offloaded;
4562 for (size_t i = 0; i < mOutputs.size(); ++i) {
4563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4564 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4565 offloaded.push(desc->mIoHandle);
4566 }
4567 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004568 for (const auto& handle : offloaded) {
4569 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004570 }
4571 }
4572 // update master mono for all remaining outputs
4573 for (size_t i = 0; i < mOutputs.size(); ++i) {
4574 updateMono(mOutputs.keyAt(i));
4575 }
4576 return NO_ERROR;
4577}
4578
4579status_t AudioPolicyManager::getMasterMono(bool *mono)
4580{
4581 *mono = mMasterMono;
4582 return NO_ERROR;
4583}
4584
Eric Laurentac9cef52017-06-09 15:46:26 -07004585float AudioPolicyManager::getStreamVolumeDB(
4586 audio_stream_type_t stream, int index, audio_devices_t device)
4587{
jiabin9a3361e2019-10-01 09:38:30 -07004588 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004589}
4590
jiabin81772902018-04-02 17:52:27 -07004591status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4592 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004593 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004594{
Kriti Dang6537def2021-03-02 13:46:59 +01004595 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4596 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004597 return BAD_VALUE;
4598 }
Kriti Dang6537def2021-03-02 13:46:59 +01004599 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4600 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004601
4602 size_t formatsWritten = 0;
4603 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004604
Kriti Dang6537def2021-03-02 13:46:59 +01004605 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004606 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4607 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004608 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004609 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004610 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004611 bool formatEnabled = true;
4612 switch (forceUse) {
4613 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004614 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004615 break;
4616 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4617 formatEnabled = false;
4618 break;
4619 default: // AUTO or ALWAYS => true
4620 break;
jiabin81772902018-04-02 17:52:27 -07004621 }
4622 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4623 }
jiabin81772902018-04-02 17:52:27 -07004624 }
4625 return NO_ERROR;
4626}
4627
Kriti Dang6537def2021-03-02 13:46:59 +01004628status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4629 audio_format_t *surroundFormats) {
4630 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4631 return BAD_VALUE;
4632 }
4633 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4634 __func__, *numSurroundFormats, surroundFormats);
4635
4636 size_t formatsWritten = 0;
4637 size_t formatsMax = *numSurroundFormats;
4638 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4639
4640 // Return formats from all device profiles that have already been resolved by
4641 // checkOutputsForDevice().
4642 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4643 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4644 audio_devices_t deviceType = device->type();
4645 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4646 // returns formats reported by HDMI devices.
4647 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4648 continue;
4649 }
4650 // Formats reported by sink devices
4651 std::unordered_set<audio_format_t> formatset;
4652 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4653 formatset.insert(it->second.begin(), it->second.end());
4654 }
4655
4656 // Formats hard-coded in the in policy configuration file (if any).
4657 FormatVector encodedFormats = device->encodedFormats();
4658 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4659 // Filter the formats which are supported by the vendor hardware.
4660 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4661 if (mConfig.getSurroundFormats().count(*it) != 0) {
4662 formats.insert(*it);
4663 } else {
4664 for (const auto& pair : mConfig.getSurroundFormats()) {
4665 if (pair.second.count(*it) != 0) {
4666 formats.insert(pair.first);
4667 break;
4668 }
4669 }
4670 }
4671 }
4672 }
4673 *numSurroundFormats = formats.size();
4674 for (const auto& format: formats) {
4675 if (formatsWritten < formatsMax) {
4676 surroundFormats[formatsWritten++] = format;
4677 }
4678 }
4679 return NO_ERROR;
4680}
4681
jiabin81772902018-04-02 17:52:27 -07004682status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4683{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004684 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004685 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4686 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004687 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004688 return BAD_VALUE;
4689 }
4690
Mikhail Naganov100f0122018-11-29 11:22:16 -08004691 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4692 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004693 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004694 return INVALID_OPERATION;
4695 }
4696
Mikhail Naganov100f0122018-11-29 11:22:16 -08004697 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004698 return NO_ERROR;
4699 }
4700
Mikhail Naganov100f0122018-11-29 11:22:16 -08004701 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004702 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004703 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004704 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004705 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004706 }
4707 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004708 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004709 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004710 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004711 }
4712 }
4713
4714 sp<SwAudioOutputDescriptor> outputDesc;
4715 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004716 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4717 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004718 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4719 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004720 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004721 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004722 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4723 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4724 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004725 name.c_str(),
4726 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004727 if (status != NO_ERROR) {
4728 continue;
4729 }
4730 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4731 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4732 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004733 name.c_str(),
4734 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004735 profileUpdated |= (status == NO_ERROR);
4736 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004737 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004738 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004739 AUDIO_DEVICE_IN_HDMI);
4740 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4741 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004742 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004743 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004744 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4745 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4746 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004747 name.c_str(),
4748 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004749 if (status != NO_ERROR) {
4750 continue;
4751 }
4752 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4753 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4754 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004755 name.c_str(),
4756 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004757 profileUpdated |= (status == NO_ERROR);
4758 }
4759
jiabin81772902018-04-02 17:52:27 -07004760 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004761 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004762 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004763 }
4764
4765 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4766}
4767
Eric Laurent5ada82e2019-08-29 17:53:54 -07004768void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004769{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004770 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004771 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004772 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004773 }
4774}
4775
jiabin6012f912018-11-02 17:06:30 -07004776bool AudioPolicyManager::isHapticPlaybackSupported()
4777{
4778 for (const auto& hwModule : mHwModules) {
4779 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4780 for (const auto &outProfile : outputProfiles) {
4781 struct audio_port audioPort;
4782 outProfile->toAudioPort(&audioPort);
4783 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4784 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4785 return true;
4786 }
4787 }
4788 }
4789 }
4790 return false;
4791}
4792
Eric Laurent8340e672019-11-06 11:01:08 -08004793bool AudioPolicyManager::isCallScreenModeSupported()
4794{
4795 return getConfig().isCallScreenModeSupported();
4796}
4797
4798
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004799status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004800{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004801 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004802 if (!sourceDesc->isConnected()) {
4803 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4804 return NO_ERROR;
4805 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004806 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4807 if (swOutput != 0) {
4808 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004809 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004810 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004811 }
jiabinbce0c1d2020-10-05 11:20:18 -07004812 if (releaseOutput(sourceDesc->portId())) {
4813 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4814 // no need to release audio patch here but just return NO_ERROR.
4815 return NO_ERROR;
4816 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004817 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004818 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004819 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004820 // close Hwoutput and remove from mHwOutputs
4821 } else {
4822 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4823 }
4824 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004825 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4826 sourceDesc->disconnect();
4827 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004828}
4829
François Gaffiec005e562018-11-06 15:04:49 +01004830sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4831 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004832{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004833 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004834 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004835 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004836 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004837 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4838 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004839 source = sourceDesc;
4840 break;
4841 }
4842 }
4843 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004844}
4845
Eric Laurentfa0f6742021-08-17 18:39:44 +02004846bool AudioPolicyManager::canBeSpatialized(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004847 const audio_config_t *config,
4848 const AudioDeviceTypeAddrVector &devices) const
4849{
4850 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
4851 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004852 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004853 // and game usages.
4854 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER &&
4855 attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
4856 return false;
4857 }
4858
4859 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02004860 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
4861 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004862 // to the specified devices must exist.
4863 sp<IOProfile> profile =
Eric Laurentfa0f6742021-08-17 18:39:44 +02004864 getSpatializerOutputProfile(config, devices, false /*forOpening*/);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004865 if (profile == nullptr) {
4866 return false;
4867 }
4868
4869 // The caller can have the audio config criteria ignored by either passing a null ptr or
4870 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004871 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004872 // 5.1, 7.1and 7.1.4 audio.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004873 // If the spatializer output is already opened, only channel masks included in the
4874 // spatializer output mixer channel mask are allowed.
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004875 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
4876 if (config->channel_mask != AUDIO_CHANNEL_OUT_5POINT1
4877 && config->channel_mask != AUDIO_CHANNEL_OUT_7POINT1
4878 && config->channel_mask != AUDIO_CHANNEL_OUT_7POINT1POINT4) {
4879 return false;
4880 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004881 if (mSpatializerOutput != nullptr) {
4882 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004883 != config->channel_mask) {
4884 return false;
4885 }
4886 }
4887 }
4888
4889 return true;
4890}
4891
4892void AudioPolicyManager::checkVirtualizerClientRoutes() {
4893 std::set<audio_stream_type_t> streamsToInvalidate;
4894 for (size_t i = 0; i < mOutputs.size(); i++) {
4895 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
4896 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
4897 audio_attributes_t attr = client->attributes();
4898 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
4899 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4900 audio_config_base_t clientConfig = client->config();
4901 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurentfa0f6742021-08-17 18:39:44 +02004902 if (canBeSpatialized(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004903 streamsToInvalidate.insert(client->stream());
4904 }
4905 }
4906 }
4907
4908 for (audio_stream_type_t stream : streamsToInvalidate) {
4909 mpClientInterface->invalidateStream(stream);
4910 }
4911}
4912
Eric Laurentfa0f6742021-08-17 18:39:44 +02004913status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004914 const audio_attributes_t *attr,
4915 audio_io_handle_t *output) {
4916 *output = AUDIO_IO_HANDLE_NONE;
4917
Eric Laurentfa0f6742021-08-17 18:39:44 +02004918 if (mSpatializerOutput != nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004919 return INVALID_OPERATION;
4920 }
4921
4922 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
4923 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4924 audio_config_t *configPtr = nullptr;
4925 audio_config_t config;
4926 if (mixerConfig != nullptr) {
4927 config = audio_config_initializer(mixerConfig);
4928 configPtr = &config;
4929 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004930 if (!canBeSpatialized(attr, configPtr, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004931 return BAD_VALUE;
4932 }
4933
4934 sp<IOProfile> profile =
Eric Laurentfa0f6742021-08-17 18:39:44 +02004935 getSpatializerOutputProfile(configPtr, devicesTypeAddress, true /*forOpening*/);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004936 if (profile == nullptr) {
4937 return BAD_VALUE;
4938 }
4939
Eric Laurentfa0f6742021-08-17 18:39:44 +02004940 mSpatializerOutput = new SwAudioOutputDescriptor(profile, mpClientInterface);
4941 status_t status = mSpatializerOutput->open(nullptr, mixerConfig, devices,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004942 mEngine->getStreamTypeForAttributes(*attr),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02004943 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004944 if (status != NO_ERROR) {
4945 ALOGV("%s failed opening output: status %d, output %d", __func__, status, *output);
4946 if (*output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02004947 mSpatializerOutput->close();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004948 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004949 mSpatializerOutput.clear();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004950 *output = AUDIO_IO_HANDLE_NONE;
4951 return status;
4952 }
4953
4954 checkVirtualizerClientRoutes();
4955
Eric Laurentfa0f6742021-08-17 18:39:44 +02004956 addOutput(*output, mSpatializerOutput);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004957 mPreviousOutputs = mOutputs;
4958 mpClientInterface->onAudioPortListUpdate();
4959
Eric Laurentfa0f6742021-08-17 18:39:44 +02004960 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004961 return NO_ERROR;
4962}
4963
Eric Laurentfa0f6742021-08-17 18:39:44 +02004964status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
4965 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004966 return INVALID_OPERATION;
4967 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004968 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004969 return BAD_VALUE;
4970 }
4971 closeOutput(output);
Eric Laurentfa0f6742021-08-17 18:39:44 +02004972 mSpatializerOutput.clear();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004973 return NO_ERROR;
4974}
4975
Eric Laurente552edb2014-03-10 17:42:56 -07004976// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004977// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004978// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004979uint32_t AudioPolicyManager::nextAudioPortGeneration()
4980{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004981 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004982}
4983
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004984static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004985 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4986 !audioPolicyXmlConfigFile.empty()) {
4987 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4988 if (ret == NO_ERROR) {
4989 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004990 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004991 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004992 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004993 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004994}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004995
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004996AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4997 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004998 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004999 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005000 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005001 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005002 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005003 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005004 mAudioPortGeneration(1),
5005 mBeaconMuteRefCount(0),
5006 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005007 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005008 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005009 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005010 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005011{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005012}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005013
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005014AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5015 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5016{
5017 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005018}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005019
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005020void AudioPolicyManager::loadConfig() {
5021 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005022 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005023 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005024 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005025 //TODO: b/193496180 use spatializer flag at audio HAL when available
5026 getConfig().convertSpatializerFlag();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005027}
5028
5029status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005030 {
5031 auto engLib = EngineLibrary::load(
5032 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5033 if (!engLib) {
5034 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5035 return NO_INIT;
5036 }
5037 mEngine = engLib->createEngine();
5038 if (mEngine == nullptr) {
5039 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5040 return NO_INIT;
5041 }
François Gaffie2110e042015-03-24 08:41:51 +01005042 }
5043 mEngine->setObserver(this);
5044 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005045 if (status != NO_ERROR) {
5046 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5047 return status;
5048 }
François Gaffie2110e042015-03-24 08:41:51 +01005049
Eric Laurent1d69c872021-01-11 18:53:01 +01005050 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5051 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5052
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005053 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005054 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005055 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005056
Eric Laurent3a4311c2014-03-17 12:00:47 -07005057 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005058 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5059 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5060 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005061 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005062 }
jiabin9ff780e2018-03-19 18:19:52 -07005063 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005064 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005065 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005066 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005067 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005068 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005069 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005070 }
5071 }
5072 }
Eric Laurente552edb2014-03-10 17:42:56 -07005073
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005074 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005075
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005076 // Silence ALOGV statements
5077 property_set("log.tag." LOG_TAG, "D");
5078
Eric Laurente552edb2014-03-10 17:42:56 -07005079 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005080 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005081}
5082
Eric Laurente0720872014-03-11 09:30:41 -07005083AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005084{
Eric Laurente552edb2014-03-10 17:42:56 -07005085 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005086 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005087 }
5088 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005089 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005090 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005091 mAvailableOutputDevices.clear();
5092 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005093 mOutputs.clear();
5094 mInputs.clear();
5095 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005096 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005097 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005098}
5099
Eric Laurente0720872014-03-11 09:30:41 -07005100status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005101{
Eric Laurent87ffa392015-05-22 10:32:38 -07005102 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005103}
5104
Eric Laurente552edb2014-03-10 17:42:56 -07005105// ---
5106
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005107void AudioPolicyManager::onNewAudioModulesAvailable()
5108{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005109 DeviceVector newDevices;
5110 onNewAudioModulesAvailableInt(&newDevices);
5111 if (!newDevices.empty()) {
5112 nextAudioPortGeneration();
5113 mpClientInterface->onAudioPortListUpdate();
5114 }
5115}
5116
5117void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5118{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005119 for (const auto& hwModule : mHwModulesAll) {
5120 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5121 continue;
5122 }
5123 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5124 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5125 ALOGW("could not open HW module %s", hwModule->getName());
5126 continue;
5127 }
5128 mHwModules.push_back(hwModule);
5129 // open all output streams needed to access attached devices
5130 // except for direct output streams that are only opened when they are actually
5131 // required by an app.
5132 // This also validates mAvailableOutputDevices list
5133 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5134 if (!outProfile->canOpenNewIo()) {
5135 ALOGE("Invalid Output profile max open count %u for profile %s",
5136 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5137 continue;
5138 }
5139 if (!outProfile->hasSupportedDevices()) {
5140 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5141 continue;
5142 }
5143 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
5144 mTtsOutputAvailable = true;
5145 }
5146
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005147 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5148 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5149 sp<DeviceDescriptor> supportedDevice = 0;
5150 if (supportedDevices.contains(mDefaultOutputDevice)) {
5151 supportedDevice = mDefaultOutputDevice;
5152 } else {
5153 // choose first device present in profile's SupportedDevices also part of
5154 // mAvailableOutputDevices.
5155 if (availProfileDevices.isEmpty()) {
5156 continue;
5157 }
5158 supportedDevice = availProfileDevices.itemAt(0);
5159 }
5160 if (!mOutputDevicesAll.contains(supportedDevice)) {
5161 continue;
5162 }
5163 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5164 mpClientInterface);
5165 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005166 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5167 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005168 AUDIO_STREAM_DEFAULT,
5169 AUDIO_OUTPUT_FLAG_NONE, &output);
5170 if (status != NO_ERROR) {
5171 ALOGW("Cannot open output stream for devices %s on hw module %s",
5172 supportedDevice->toString().c_str(), hwModule->getName());
5173 continue;
5174 }
5175 for (const auto &device : availProfileDevices) {
5176 // give a valid ID to an attached device once confirmed it is reachable
5177 if (!device->isAttached()) {
5178 device->attach(hwModule);
5179 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005180 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005181 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005182 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5183 }
5184 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005185 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005186 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5187 mPrimaryOutput = outputDesc;
5188 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005189 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0
Eric Laurent1c5e2e32021-08-18 18:50:28 +02005190 || (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0 ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005191 outputDesc->close();
5192 } else {
5193 addOutput(output, outputDesc);
5194 setOutputDevices(outputDesc,
5195 DeviceVector(supportedDevice),
5196 true,
5197 0,
5198 NULL);
5199 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005200 }
5201 // open input streams needed to access attached devices to validate
5202 // mAvailableInputDevices list
5203 for (const auto& inProfile : hwModule->getInputProfiles()) {
5204 if (!inProfile->canOpenNewIo()) {
5205 ALOGE("Invalid Input profile max open count %u for profile %s",
5206 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5207 continue;
5208 }
5209 if (!inProfile->hasSupportedDevices()) {
5210 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5211 continue;
5212 }
5213 // chose first device present in profile's SupportedDevices also part of
5214 // available input devices
5215 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5216 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5217 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005218 ALOGV("%s: Input device list is empty! for profile %s",
5219 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005220 continue;
5221 }
5222 sp<AudioInputDescriptor> inputDesc =
5223 new AudioInputDescriptor(inProfile, mpClientInterface);
5224
5225 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5226 status_t status = inputDesc->open(nullptr,
5227 availProfileDevices.itemAt(0),
5228 AUDIO_SOURCE_MIC,
5229 AUDIO_INPUT_FLAG_NONE,
5230 &input);
5231 if (status != NO_ERROR) {
5232 ALOGW("Cannot open input stream for device %s on hw module %s",
5233 availProfileDevices.toString().c_str(),
5234 hwModule->getName());
5235 continue;
5236 }
5237 for (const auto &device : availProfileDevices) {
5238 // give a valid ID to an attached device once confirmed it is reachable
5239 if (!device->isAttached()) {
5240 device->attach(hwModule);
5241 device->importAudioPortAndPickAudioProfile(inProfile, true);
5242 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005243 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005244 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5245 }
5246 }
5247 inputDesc->close();
5248 }
5249 }
5250}
5251
Eric Laurent98e38192018-02-15 18:31:53 -08005252void AudioPolicyManager::addOutput(audio_io_handle_t output,
5253 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005254{
Eric Laurent1c333e22014-05-20 10:48:17 -07005255 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005256 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005257 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005258 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005260}
5261
François Gaffie53615e22015-03-19 09:24:12 +01005262void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5263{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005264 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5265 ALOGV("%s: removing primary output", __func__);
5266 mPrimaryOutput = nullptr;
5267 }
François Gaffie53615e22015-03-19 09:24:12 +01005268 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005269 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005270}
5271
Eric Laurent98e38192018-02-15 18:31:53 -08005272void AudioPolicyManager::addInput(audio_io_handle_t input,
5273 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005274{
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005277}
Eric Laurente552edb2014-03-10 17:42:56 -07005278
François Gaffie11d30102018-11-02 16:09:09 +01005279status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005280 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005281 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
François Gaffie11d30102018-11-02 16:09:09 +01005283 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005284 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005285 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005286
François Gaffie11d30102018-11-02 16:09:09 +01005287 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005288 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005289 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005290 }
Eric Laurente552edb2014-03-10 17:42:56 -07005291
Eric Laurent3b73df72014-03-11 09:06:29 -07005292 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005293 // first call getAudioPort to get the supported attributes from the HAL
5294 struct audio_port_v7 port = {};
5295 device->toAudioPort(&port);
5296 status_t status = mpClientInterface->getAudioPort(&port);
5297 if (status == NO_ERROR) {
5298 device->importAudioPort(port);
5299 }
5300
5301 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005302 for (size_t i = 0; i < mOutputs.size(); i++) {
5303 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005304 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005305 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005306 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5307 mOutputs.keyAt(i), device->toString().c_str());
5308 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005309 }
5310 }
5311 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005312 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005313 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005314 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5315 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005316 if (profile->supportsDevice(device)) {
5317 profiles.add(profile);
5318 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5319 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005320 }
5321 }
5322 }
5323
Eric Laurent7b279bb2015-12-14 10:18:23 -08005324 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005325
Eric Laurente552edb2014-03-10 17:42:56 -07005326 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005327 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005328 return BAD_VALUE;
5329 }
5330
5331 // open outputs for matching profiles if needed. Direct outputs are also opened to
5332 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5333 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005334 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005335
5336 // nothing to do if one output is already opened for this profile
5337 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005338 for (j = 0; j < outputs.size(); j++) {
5339 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005340 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005341 // matching profile: save the sample rates, format and channel masks supported
5342 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005343 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005344 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005345 }
Eric Laurente552edb2014-03-10 17:42:56 -07005346 break;
5347 }
5348 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005349 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005350 continue;
5351 }
5352
Eric Laurent3974e3b2017-12-07 17:58:43 -08005353 if (!profile->canOpenNewIo()) {
5354 ALOGW("Max Output number %u already opened for this profile %s",
5355 profile->maxOpenCount, profile->getTagName().c_str());
5356 continue;
5357 }
5358
Eric Laurent83efe1c2017-07-09 16:51:08 -07005359 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005360 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005361 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5362 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005363 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005364 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005365 profiles.removeAt(profile_index);
5366 profile_index--;
5367 } else {
5368 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005369 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005370 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005371 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5372 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005373 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005374 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005375
François Gaffie11d30102018-11-02 16:09:09 +01005376 if (device_distinguishes_on_address(deviceType)) {
5377 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5378 device->toString().c_str());
5379 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5380 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005381 }
Eric Laurente552edb2014-03-10 17:42:56 -07005382 ALOGV("checkOutputsForDevice(): adding output %d", output);
5383 }
5384 }
5385
5386 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005387 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005388 return BAD_VALUE;
5389 }
Eric Laurentd4692962014-05-05 18:13:44 -07005390 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005391 // check if one opened output is not needed any more after disconnecting one device
5392 for (size_t i = 0; i < mOutputs.size(); i++) {
5393 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005394 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005395 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005396 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005397 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005398 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005399 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005400 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5401 mOutputs.keyAt(i));
5402 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005403 }
Eric Laurente552edb2014-03-10 17:42:56 -07005404 }
5405 }
Eric Laurentd4692962014-05-05 18:13:44 -07005406 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005407 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005408 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5409 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005410 if (!profile->supportsDevice(device)) {
5411 continue;
5412 }
5413 ALOGV("checkOutputsForDevice(): "
5414 "clearing direct output profile %zu on module %s",
5415 j, hwModule->getName());
5416 profile->clearAudioProfiles();
5417 if (!profile->hasDynamicAudioProfile()) {
5418 continue;
5419 }
5420 // When a device is disconnected, if there is an IOProfile that contains dynamic
5421 // profiles and supports the disconnected device, call getAudioPort to repopulate
5422 // the capabilities of the devices that is supported by the IOProfile.
5423 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5424 if (supportedDevice == device ||
5425 !mAvailableOutputDevices.contains(supportedDevice)) {
5426 continue;
5427 }
5428 struct audio_port_v7 port;
5429 supportedDevice->toAudioPort(&port);
5430 status_t status = mpClientInterface->getAudioPort(&port);
5431 if (status == NO_ERROR) {
5432 supportedDevice->importAudioPort(port);
5433 }
Eric Laurente552edb2014-03-10 17:42:56 -07005434 }
5435 }
5436 }
5437 }
5438 return NO_ERROR;
5439}
5440
François Gaffie11d30102018-11-02 16:09:09 +01005441status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005442 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005443{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005444 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005445
François Gaffie11d30102018-11-02 16:09:09 +01005446 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005447 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005448 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005449 }
5450
Eric Laurentd4692962014-05-05 18:13:44 -07005451 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005452 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005453 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005454 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005455 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005456 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005457 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005458 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005459
François Gaffie11d30102018-11-02 16:09:09 +01005460 if (profile->supportsDevice(device)) {
5461 profiles.add(profile);
5462 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5463 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005464 }
5465 }
5466 }
5467
Eric Laurent0dd51852019-04-19 18:18:58 -07005468 if (profiles.isEmpty()) {
5469 ALOGW("%s: No input profile available for device %s",
5470 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005471 return BAD_VALUE;
5472 }
5473
5474 // open inputs for matching profiles if needed. Direct inputs are also opened to
5475 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5476 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5477
Eric Laurent1c333e22014-05-20 10:48:17 -07005478 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005479
Eric Laurentd4692962014-05-05 18:13:44 -07005480 // nothing to do if one input is already opened for this profile
5481 size_t input_index;
5482 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5483 desc = mInputs.valueAt(input_index);
5484 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005485 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005486 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005487 }
Eric Laurentd4692962014-05-05 18:13:44 -07005488 break;
5489 }
5490 }
5491 if (input_index != mInputs.size()) {
5492 continue;
5493 }
5494
Eric Laurent3974e3b2017-12-07 17:58:43 -08005495 if (!profile->canOpenNewIo()) {
5496 ALOGW("Max Input number %u already opened for this profile %s",
5497 profile->maxOpenCount, profile->getTagName().c_str());
5498 continue;
5499 }
5500
Eric Laurentfe231122017-11-17 17:48:06 -08005501 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005502 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005503 status_t status = desc->open(nullptr,
5504 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005505 AUDIO_SOURCE_MIC,
5506 AUDIO_INPUT_FLAG_NONE,
5507 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005508
Eric Laurentcf2c0212014-07-25 16:20:43 -07005509 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005510 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005511 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005512 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005513 mpClientInterface->setParameters(input, String8(param));
5514 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005515 }
François Gaffie11d30102018-11-02 16:09:09 +01005516 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005517 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005518 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005519 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005520 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005521 }
5522
Eric Laurent0dd51852019-04-19 18:18:58 -07005523 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005524 addInput(input, desc);
5525 }
5526 } // endif input != 0
5527
Eric Laurentcf2c0212014-07-25 16:20:43 -07005528 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005529 ALOGW("%s could not open input for device %s", __func__,
5530 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005531 profiles.removeAt(profile_index);
5532 profile_index--;
5533 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005534 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005535 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005536 }
Eric Laurentd4692962014-05-05 18:13:44 -07005537 ALOGV("checkInputsForDevice(): adding input %d", input);
5538 }
5539 } // end scan profiles
5540
5541 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005542 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005543 return BAD_VALUE;
5544 }
5545 } else {
5546 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005547 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005548 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005549 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005550 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005551 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005552 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005553 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005554 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5555 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005556 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005557 }
5558 }
5559 }
5560 } // end disconnect
5561
5562 return NO_ERROR;
5563}
5564
5565
Eric Laurente0720872014-03-11 09:30:41 -07005566void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005567{
5568 ALOGV("closeOutput(%d)", output);
5569
François Gaffie1c878552018-11-22 16:53:21 +01005570 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5571 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005572 ALOGW("closeOutput() unknown output %d", output);
5573 return;
5574 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005575 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005576 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005577
Eric Laurente552edb2014-03-10 17:42:56 -07005578 // look for duplicated outputs connected to the output being removed.
5579 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005580 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5581 if (dupOutput->isDuplicated() &&
5582 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5583 sp<SwAudioOutputDescriptor> remainingOutput =
5584 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005585 // As all active tracks on duplicated output will be deleted,
5586 // and as they were also referenced on the other output, the reference
5587 // count for their stream type must be adjusted accordingly on
5588 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005589 const bool wasActive = remainingOutput->isActive();
5590 // Note: no-op on the closing output where all clients has already been set inactive
5591 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005592 // stop() will be a no op if the output is still active but is needed in case all
5593 // active streams refcounts where cleared above
5594 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005595 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005596 }
Eric Laurente552edb2014-03-10 17:42:56 -07005597 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5598 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5599
5600 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005601 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005602 }
5603 }
5604
Eric Laurent05b90f82014-08-27 15:32:29 -07005605 nextAudioPortGeneration();
5606
François Gaffie1c878552018-11-22 16:53:21 +01005607 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005608 if (index >= 0) {
5609 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005610 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5611 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005612 mAudioPatches.removeItemsAt(index);
5613 mpClientInterface->onAudioPatchListUpdate();
5614 }
5615
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005616 if (closingOutputWasActive) {
5617 closingOutput->stop();
5618 }
François Gaffie1c878552018-11-22 16:53:21 +01005619 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005620
François Gaffie53615e22015-03-19 09:24:12 +01005621 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005622 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005623
5624 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5625 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005626 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005627 bool directOutputOpen = false;
5628 for (size_t i = 0; i < mOutputs.size(); i++) {
5629 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5630 directOutputOpen = true;
5631 break;
5632 }
5633 }
5634 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005635 ALOGV("no direct outputs open, reset MSD patches");
5636 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5637 // how output devices for patching are resolved. Avoid by caching and reusing the
5638 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5639 // devices to patch to. This may be complicated by the fact that devices may become
5640 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005641 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005642 }
5643 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005644}
5645
5646void AudioPolicyManager::closeInput(audio_io_handle_t input)
5647{
5648 ALOGV("closeInput(%d)", input);
5649
5650 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5651 if (inputDesc == NULL) {
5652 ALOGW("closeInput() unknown input %d", input);
5653 return;
5654 }
5655
Eric Laurent6a94d692014-05-20 11:18:06 -07005656 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005657
François Gaffie11d30102018-11-02 16:09:09 +01005658 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005659 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005660 if (index >= 0) {
5661 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005662 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5663 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005664 mAudioPatches.removeItemsAt(index);
5665 mpClientInterface->onAudioPatchListUpdate();
5666 }
5667
Eric Laurentfe231122017-11-17 17:48:06 -08005668 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005669 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005670
François Gaffie11d30102018-11-02 16:09:09 +01005671 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5672 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005673 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005674 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005675 }
Eric Laurente552edb2014-03-10 17:42:56 -07005676}
5677
François Gaffie11d30102018-11-02 16:09:09 +01005678SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5679 const DeviceVector &devices,
5680 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005681{
5682 SortedVector<audio_io_handle_t> outputs;
5683
François Gaffie11d30102018-11-02 16:09:09 +01005684 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005685 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005686 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005687 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005688 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005689 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005690 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005691 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005692 outputs.add(openOutputs.keyAt(i));
5693 }
5694 }
5695 return outputs;
5696}
5697
Mikhail Naganov37977152018-07-11 15:54:44 -07005698void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5699{
5700 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5701 // output is suspended before any tracks are moved to it
5702 checkA2dpSuspend();
5703 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005704 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005705 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005706 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005707 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005708 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5709 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5710 // configuration changes will ultimately be rerouted correctly. We can still avoid
5711 // unnecessary rerouting by caching and reusing the arguments to
5712 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5713 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005714 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005715 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005716 // an event that changed routing likely occurred, inform upper layers
5717 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005718}
5719
François Gaffiec005e562018-11-06 15:04:49 +01005720bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5721 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005722{
François Gaffiec005e562018-11-06 15:04:49 +01005723 return mEngine->getProductStrategyForAttributes(lAttr) ==
5724 mEngine->getProductStrategyForAttributes(rAttr);
5725}
5726
Francois Gaffieff1eb522020-05-06 18:37:04 +02005727void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5728{
5729 for (size_t i = 0; i < mAudioSources.size(); i++) {
5730 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5731 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005732 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5733 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005734 connectAudioSource(sourceDesc);
5735 }
5736 }
5737}
5738
5739void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5740{
5741 for (size_t i = 0; i < mAudioSources.size(); i++) {
5742 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5743 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5744 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5745 disconnectAudioSource(sourceDesc);
5746 }
5747 }
5748}
5749
François Gaffiec005e562018-11-06 15:04:49 +01005750void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5751{
5752 auto psId = mEngine->getProductStrategyForAttributes(attr);
5753
5754 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5755 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005756
François Gaffie11d30102018-11-02 16:09:09 +01005757 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5758 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005759
Eric Laurentc209fe42020-06-05 18:11:23 -07005760 uint32_t maxLatency = 0;
5761 bool invalidate = false;
5762 // take into account dynamic audio policies related changes: if a client is now associated
5763 // to a different policy mix than at creation time, invalidate corresponding stream
5764 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5765 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5766 if (desc->isDuplicated()) {
5767 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005768 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005769 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5770 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5771 continue;
5772 }
5773 sp<AudioPolicyMix> primaryMix;
5774 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5775 client->flags(), primaryMix, nullptr);
5776 if (status != OK) {
5777 continue;
5778 }
yucliuf4de36d2020-09-14 14:57:56 -07005779 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005780 invalidate = true;
5781 if (desc->isStrategyActive(psId)) {
5782 maxLatency = desc->latency();
5783 }
5784 break;
5785 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005786 }
5787 }
5788
Eric Laurentc209fe42020-06-05 18:11:23 -07005789 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005790 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5791 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005792 for (audio_io_handle_t srcOut : srcOutputs) {
5793 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005794 if (desc == nullptr) continue;
5795
5796 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005797 maxLatency = desc->latency();
5798 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005799
5800 if (invalidate) continue;
5801
5802 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005803 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005804 // a client on a non direct outputs has necessarily a linear PCM format
5805 // so we can call selectOutput() safely
5806 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5807 client->flags(),
5808 client->config().format,
5809 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005810 client->config().sample_rate,
5811 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005812 if (newOutput != srcOut) {
5813 invalidate = true;
5814 break;
5815 }
5816 } else {
5817 sp<IOProfile> profile = getProfileForOutput(newDevices,
5818 client->config().sample_rate,
5819 client->config().format,
5820 client->config().channel_mask,
5821 client->flags(),
5822 true /* directOnly */);
5823 if (profile != desc->mProfile) {
5824 invalidate = true;
5825 break;
5826 }
5827 }
5828 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005829 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005830
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005831 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005832 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005833 std::to_string(srcOutputs[0]).c_str(),
5834 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005835 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005836 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005837 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005838 if (desc == nullptr) continue;
5839
5840 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005841 setStrategyMute(psId, true, desc);
5842 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005843 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005844 }
François Gaffiec005e562018-11-06 15:04:49 +01005845 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005846 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005847 connectAudioSource(source);
5848 }
Eric Laurente552edb2014-03-10 17:42:56 -07005849 }
5850
François Gaffiec005e562018-11-06 15:04:49 +01005851 // Move effects associated to this stream from previous output to new output
5852 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005853 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005854 }
François Gaffiec005e562018-11-06 15:04:49 +01005855 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005856 if (invalidate) {
5857 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5858 mpClientInterface->invalidateStream(stream);
5859 }
Eric Laurente552edb2014-03-10 17:42:56 -07005860 }
5861 }
5862}
5863
Eric Laurente0720872014-03-11 09:30:41 -07005864void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005865{
François Gaffiec005e562018-11-06 15:04:49 +01005866 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5867 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5868 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005869 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005870 }
Eric Laurente552edb2014-03-10 17:42:56 -07005871}
5872
Kevin Rocard153f92d2018-12-18 18:33:28 -08005873void AudioPolicyManager::checkSecondaryOutputs() {
5874 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005875 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005876 for (size_t i = 0; i < mOutputs.size(); i++) {
5877 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5878 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005879 sp<AudioPolicyMix> primaryMix;
5880 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005881 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005882 client->flags(), primaryMix, &secondaryMixes);
5883 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5884 for (auto &secondaryMix : secondaryMixes) {
5885 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5886 if (outputDesc != nullptr &&
5887 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5888 secondaryDescs.push_back(outputDesc);
5889 }
5890 }
5891
jiabinf042b9b2021-05-07 23:46:28 +00005892 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005893 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005894 } else if (!std::equal(
5895 client->getSecondaryOutputs().begin(),
5896 client->getSecondaryOutputs().end(),
5897 secondaryDescs.begin(), secondaryDescs.end())) {
5898 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5899 std::vector<audio_io_handle_t> secondaryOutputIds;
5900 for (const auto& secondaryDesc : secondaryDescs) {
5901 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5902 weakSecondaryDescs.push_back(secondaryDesc);
5903 }
5904 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5905 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005906 }
5907 }
5908 }
jiabinf042b9b2021-05-07 23:46:28 +00005909 if (!trackSecondaryOutputs.empty()) {
5910 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5911 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005912 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00005913 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005914 mpClientInterface->invalidateStream(stream);
5915 }
5916}
5917
Eric Laurent2517af32020-11-25 15:31:27 +01005918bool AudioPolicyManager::isScoRequestedForComm() const {
5919 AudioDeviceTypeAddrVector devices;
5920 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5921 for (const auto &device : devices) {
5922 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5923 return true;
5924 }
5925 }
5926 return false;
5927}
5928
Eric Laurente0720872014-03-11 09:30:41 -07005929void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005930{
François Gaffie53615e22015-03-19 09:24:12 +01005931 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005932 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005933 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005934 return;
5935 }
5936
Eric Laurent3a4311c2014-03-17 12:00:47 -07005937 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005938 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5939 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005940 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005941
5942 // if suspended, restore A2DP output if:
5943 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005944 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005945 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005946 //
Eric Laurentf732e072016-08-03 19:30:28 -07005947 // if not suspended, suspend A2DP output if:
5948 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005949 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005950 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005951 //
5952 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005953 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005954 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005955 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005956 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005957
5958 mpClientInterface->restoreOutput(a2dpOutput);
5959 mA2dpSuspended = false;
5960 }
5961 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005962 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005963 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005964 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005965 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005966
5967 mpClientInterface->suspendOutput(a2dpOutput);
5968 mA2dpSuspended = true;
5969 }
5970 }
5971}
5972
François Gaffie11d30102018-11-02 16:09:09 +01005973DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5974 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005975{
François Gaffie11d30102018-11-02 16:09:09 +01005976 DeviceVector devices;
5977
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005978 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005979 if (index >= 0) {
5980 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005981 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005982 ALOGV("%s device %s forced by patch %d", __func__,
5983 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5984 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005985 }
5986 }
5987
Dean Wheatley514b4312020-06-17 21:45:00 +10005988 // Do not retrieve engine device for outputs through MSD
5989 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5990 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5991 return outputDesc->devices();
5992 }
5993
Eric Laurent97ac8712018-07-27 18:59:02 -07005994 // Honor explicit routing requests only if no client using default routing is active on this
5995 // input: a specific app can not force routing for other apps by setting a preferred device.
5996 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005997 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005998 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005999 if (device != nullptr) {
6000 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006001 }
6002
François Gaffiea807ef92018-11-05 10:44:33 +01006003 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6004 // of setForceUse / Default Bus device here
6005 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6006 if (device != nullptr) {
6007 return DeviceVector(device);
6008 }
6009
François Gaffiec005e562018-11-06 15:04:49 +01006010 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6011 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6012 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306013 auto hasStreamActive = [&](auto stream) {
6014 return hasStream(streams, stream) && isStreamActive(stream, 0);
6015 };
Eric Laurent484e9272018-06-07 17:29:23 -07006016
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306017 auto doGetOutputDevicesForVoice = [&]() {
6018 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
6019 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
6020 (isInCall() ||
6021 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
6022 };
6023
6024 // With low-latency playing on speaker, music on WFD, when the first low-latency
6025 // output is stopped, getNewOutputDevices checks for a product strategy
6026 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006027 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306028 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6029 // stream is associated to the output descriptor.
6030 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6031 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6032 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6033 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006034 // Retrieval of devices for voice DL is done on primary output profile, cannot
6035 // check the route (would force modifying configuration file for this profile)
6036 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6037 break;
6038 }
Eric Laurente552edb2014-03-10 17:42:56 -07006039 }
François Gaffiec005e562018-11-06 15:04:49 +01006040 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006041 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006042}
6043
François Gaffie11d30102018-11-02 16:09:09 +01006044sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6045 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006046{
François Gaffie11d30102018-11-02 16:09:09 +01006047 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006048
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006049 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006050 if (index >= 0) {
6051 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006052 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006053 ALOGV("getNewInputDevice() device %s forced by patch %d",
6054 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6055 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006056 }
6057 }
6058
Eric Laurent97ac8712018-07-27 18:59:02 -07006059 // Honor explicit routing requests only if no client using default routing is active on this
6060 // input: a specific app can not force routing for other apps by setting a preferred device.
6061 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006062 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6063 if (device != nullptr) {
6064 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006065 }
6066
Eric Laurentdc95a252018-04-12 12:46:56 -07006067 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006068 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006069 audio_attributes_t attributes;
6070 uid_t uid;
6071 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6072 if (topClient != nullptr) {
6073 attributes = topClient->attributes();
6074 uid = topClient->uid();
6075 } else {
6076 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6077 uid = 0;
6078 }
6079
Francois Gaffie716e1432019-01-14 16:58:59 +01006080 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6081 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006082 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006083 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006084 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006085 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006086
Eric Laurente552edb2014-03-10 17:42:56 -07006087 return device;
6088}
6089
Eric Laurent794fde22016-03-11 09:50:45 -08006090bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6091 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006092 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006093}
6094
Eric Laurente0720872014-03-11 09:30:41 -07006095audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006096 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006097 // getOutputDevicesForStream's behavior for invalid streams.
6098 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6099 // device for music stream), but we want to return the empty set.
6100 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07006101 return AUDIO_DEVICE_NONE;
6102 }
François Gaffie11d30102018-11-02 16:09:09 +01006103 DeviceVector activeDevices;
6104 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006105 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6106 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006107 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006108 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006109 }
François Gaffiec005e562018-11-06 15:04:49 +01006110 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006111 devices.merge(curDevices);
6112 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006113 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07006114 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01006115 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006116 }
6117 }
Eric Laurente552edb2014-03-10 17:42:56 -07006118 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006119
Eric Laurentb0688d62018-08-14 15:49:18 -07006120 // Favor devices selected on active streams if any to report correct device in case of
6121 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006122 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006123 devices = activeDevices;
6124 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006125 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6126 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006127 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006128 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006129 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006130 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006131 }
jiabin9a3361e2019-10-01 09:38:30 -07006132 // FIXME: use DeviceTypeSet when Java layer is ready for it.
6133 return deviceTypesToBitMask(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