blob: 0c3541a2b3a3bf55153b877d29fb7a561f6d649b [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>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080035#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080036#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110037#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070038
39#include <Serializer.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070040#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070042#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070043#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070044#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070046#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070047#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070048#include <utils/Log.h>
49
Eric Laurentd4692962014-05-05 18:13:44 -070050#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010051#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070052
Eric Laurent3b73df72014-03-11 09:06:29 -070053namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurentdc462862016-07-19 12:29:53 -070055//FIXME: workaround for truncated touch sounds
56// to be removed when the problem is handled by system UI
57#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070058
59// Largest difference in dB on earpiece in call between the voice volume and another
60// media / notification / system volume.
61constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
62
Mikhail Naganov15be9d22017-11-08 14:18:13 +110063// Compressed formats for MSD module, ordered from most preferred to least preferred.
64static const std::vector<audio_format_t> compressedFormatsOrder = {{
65 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
66 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
67// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
68static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
69 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
70 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
71 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
72
jiabin06e4bab2019-07-29 10:13:34 -070073template <typename T>
74bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
75{
76 if (left.size() != right.size()) {
77 return false;
78 }
79 for (size_t index = 0; index < right.size(); index++) {
80 if (left[index] != right[index]) {
81 return false;
82 }
83 }
84 return true;
85}
86
87template <typename T>
88bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
89{
90 return !(left == right);
91}
92
Eric Laurente552edb2014-03-10 17:42:56 -070093// ----------------------------------------------------------------------------
94// AudioPolicyInterface implementation
95// ----------------------------------------------------------------------------
96
Eric Laurente0720872014-03-11 09:30:41 -070097status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080098 audio_policy_dev_state_t state,
99 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800100 const char *device_name,
101 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700102{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800103 status_t status = setDeviceConnectionStateInt(device, state, device_address,
104 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800105 nextAudioPortGeneration();
106 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800107}
108
François Gaffie11d30102018-11-02 16:09:09 +0100109void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
110 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200111{
jiabince9f20e2019-09-12 16:29:15 -0700112 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200113 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700114 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100115 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200116 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
117}
118
François Gaffie11d30102018-11-02 16:09:09 +0100119status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800120 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800121 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800122 const char *device_name,
123 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800124{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800125 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
126 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700127
128 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100129 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700130
François Gaffie11d30102018-11-02 16:09:09 +0100131 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800132 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100133 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700134 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
135}
Paul McLeane743a472015-01-28 11:07:31 -0800136
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700137status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
138 audio_policy_dev_state_t state)
139{
Eric Laurente552edb2014-03-10 17:42:56 -0700140 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700141 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700142 SortedVector <audio_io_handle_t> outputs;
143
François Gaffie11d30102018-11-02 16:09:09 +0100144 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145
Eric Laurente552edb2014-03-10 17:42:56 -0700146 // save a copy of the opened output descriptors before any output is opened or closed
147 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
148 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700149 switch (state)
150 {
151 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800152 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700153 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100154 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700155 return INVALID_OPERATION;
156 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800157 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700158 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700159
Eric Laurente552edb2014-03-10 17:42:56 -0700160 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200161 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700163 }
164
François Gaffie44481e72016-04-20 07:49:57 +0200165 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
166 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100167 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200168
François Gaffie11d30102018-11-02 16:09:09 +0100169 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
170 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200171
Francois Gaffie716e1432019-01-14 16:58:59 +0100172 mHwModules.cleanUpForDevice(device);
173
François Gaffie11d30102018-11-02 16:09:09 +0100174 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700175 return INVALID_OPERATION;
176 }
François Gaffie2110e042015-03-24 08:41:51 +0100177
jiabin1c4794b2020-05-05 10:08:05 -0700178 // Populate encapsulation information when a output device is connected.
179 device->setEncapsulationInfoFromHal(mpClientInterface);
180
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700181 // outputs should never be empty here
182 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
183 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100184 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800185
Eric Laurent3ae5f312015-02-03 17:12:08 -0800186 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700188 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100190 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700191 return INVALID_OPERATION;
192 }
193
François Gaffie11d30102018-11-02 16:09:09 +0100194 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700195
Paul McLeane743a472015-01-28 11:07:31 -0800196 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100197 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100200 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100202 mOutputs.clearSessionRoutesForDevice(device);
203
François Gaffie11d30102018-11-02 16:09:09 +0100204 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100205
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 // Reset active device codec
207 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
208
Kriti Dangef6be8f2020-11-05 11:58:19 +0100209 // remove device from mReportedFormatsMap cache
210 mReportedFormatsMap.erase(device);
211
Eric Laurente552edb2014-03-10 17:42:56 -0700212 } break;
213
214 default:
François Gaffie11d30102018-11-02 16:09:09 +0100215 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700216 return BAD_VALUE;
217 }
218
Eric Laurent736a1022019-03-27 18:28:46 -0700219 // Propagate device availability to Engine
220 setEngineDeviceConnectionState(device, state);
221
Eric Laurentae970022019-01-29 14:25:04 -0800222 // No need to evaluate playback routing when connecting a remote submix
223 // output device used by a dynamic policy of type recorder as no
224 // playback use case is affected.
225 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700226 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800227 for (audio_io_handle_t output : outputs) {
228 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800229 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
230 if (policyMix != nullptr
231 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700232 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800233 doCheckForDeviceAndOutputChanges = false;
234 break;
235 }
236 }
237 }
238
239 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700240 // outputs must be closed after checkOutputForAllStrategies() is executed
241 if (!outputs.isEmpty()) {
242 for (audio_io_handle_t output : outputs) {
243 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100244 // close unused outputs after device disconnection or direct outputs that have
245 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700246 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
247 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800248 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200249 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700250 closeOutput(output);
251 }
Eric Laurente552edb2014-03-10 17:42:56 -0700252 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700253 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
254 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700256 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800257 };
258
259 if (doCheckForDeviceAndOutputChanges) {
260 checkForDeviceAndOutputChanges(checkCloseOutputs);
261 } else {
262 checkCloseOutputs();
263 }
Eric Laurente552edb2014-03-10 17:42:56 -0700264
Eric Laurent87ffa392015-05-22 10:32:38 -0700265 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100266 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
267 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700268 }
jiabinbce0c1d2020-10-05 11:20:18 -0700269 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100270 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700271 const DeviceVector activeMediaDevices =
272 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700273 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700274 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
275 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100276 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700277 // do not force device change on duplicated output because if device is 0, it will
278 // also force a device 0 for the two outputs it is duplicated to which may override
279 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100280 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100281 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700283 // always force when disconnecting (a non-duplicated device)
284 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100285 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700286 }
jiabinbce0c1d2020-10-05 11:20:18 -0700287 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
288 desc->devices() != activeMediaDevices &&
289 desc->supportsDevicesForPlayback(activeMediaDevices)) {
290 // Reopen the output to query the dynamic profiles when there is not active
291 // clients or all active clients will be rerouted. Otherwise, set the flag
292 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
293 // can be reopened to query dynamic profiles when all clients are inactive.
294 if (areAllActiveTracksRerouted(desc)) {
295 outputsToReopen.push_back(mOutputs.keyAt(i));
296 } else {
297 desc->mPendingReopenToQueryProfiles = true;
298 }
299 }
300 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
301 // Clear the flag that previously set for re-querying profiles.
302 desc->mPendingReopenToQueryProfiles = false;
303 }
304 }
305 for (const auto& output : outputsToReopen) {
306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
307 closeOutput(output);
308 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
310
Eric Laurentd60560a2015-04-10 11:31:20 -0700311 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100312 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700313 }
314
Eric Laurent72aa32f2014-05-30 18:51:48 -0700315 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700316 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700317 } // end if is output device
318
Eric Laurente552edb2014-03-10 17:42:56 -0700319 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700320 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700322 switch (state)
323 {
324 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700325 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return INVALID_OPERATION;
329 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700330
331 if (mAvailableInputDevices.add(device) < 0) {
332 return NO_MEMORY;
333 }
334
François Gaffie44481e72016-04-20 07:49:57 +0200335 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
336 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100337 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200338
Eric Laurent0dd51852019-04-19 18:18:58 -0700339 if (checkInputsForDevice(device, state) != NO_ERROR) {
340 mAvailableInputDevices.remove(device);
341
François Gaffie11d30102018-11-02 16:09:09 +0100342 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100343
344 mHwModules.cleanUpForDevice(device);
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 return INVALID_OPERATION;
347 }
348
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700352 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100354 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700355 return INVALID_OPERATION;
356 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700357
François Gaffie11d30102018-11-02 16:09:09 +0100358 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700359
360 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100361 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700362
François Gaffie11d30102018-11-02 16:09:09 +0100363 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700364
365 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100366
367 // remove device from mReportedFormatsMap cache
368 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700369 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700370
371 default:
François Gaffie11d30102018-11-02 16:09:09 +0100372 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700373 return BAD_VALUE;
374 }
375
Eric Laurent736a1022019-03-27 18:28:46 -0700376 // Propagate device availability to Engine
377 setEngineDeviceConnectionState(device, state);
378
Eric Laurent0dd51852019-04-19 18:18:58 -0700379 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700380 // As the input device list can impact the output device selection, update
381 // getDeviceForStrategy() cache
382 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700383
Eric Laurent87ffa392015-05-22 10:32:38 -0700384 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100385 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
386 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700387 }
388
Eric Laurentd60560a2015-04-10 11:31:20 -0700389 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700391 }
392
Eric Laurentb52c1522014-05-20 11:27:36 -0700393 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700394 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700395 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700396
François Gaffie11d30102018-11-02 16:09:09 +0100397 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700398 return BAD_VALUE;
399}
400
Eric Laurent736a1022019-03-27 18:28:46 -0700401void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
402 audio_policy_dev_state_t state) {
403
404 // the Engine does not have to know about remote submix devices used by dynamic audio policies
405 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
406 return;
407 }
408 mEngine->setDeviceConnectionState(device, state);
409}
410
411
Eric Laurente0720872014-03-11 09:30:41 -0700412audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100413 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700414{
Eric Laurent634b7142016-04-20 13:48:02 -0700415 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800416 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
417 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700418 (strlen(device_address) != 0)/*matchAddress*/);
419
420 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100421 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700422 device, device_address);
423 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
424 }
François Gaffie53615e22015-03-19 09:24:12 +0100425
Eric Laurent3a4311c2014-03-17 12:00:47 -0700426 DeviceVector *deviceVector;
427
Eric Laurente552edb2014-03-10 17:42:56 -0700428 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700429 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700430 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700431 deviceVector = &mAvailableInputDevices;
432 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100433 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700435 }
Eric Laurent634b7142016-04-20 13:48:02 -0700436
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800437 return (deviceVector->getDevice(
438 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700439 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800440}
441
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800442status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
443 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800444 const char *device_name,
445 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800446{
447 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700448 String8 reply;
449 AudioParameter param;
450 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800451
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800452 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
453 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800454
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800455 // connect/disconnect only 1 device at a time
456 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
457
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800458 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700459 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800460 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800461 // Nothing to do: device is not connected
462 return NO_ERROR;
463 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800464 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800465
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700466 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800467 // configure codecs.
468 // Handle two specific cases by sending a set parameter to
469 // configure A2DP codecs. No need to toggle device state.
470 // Case 1: A2DP active device switches from primary to primary
471 // module
472 // Case 2: A2DP device config changes on primary module.
jiabin9a3361e2019-10-01 09:38:30 -0700473 if (audio_is_a2dp_out_device(device)) {
474 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800475 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
476 if (availablePrimaryOutputDevices().contains(devDesc) &&
477 (module != 0 && module->getHandle() == primaryHandle)) {
478 reply = mpClientInterface->getParameters(
479 AUDIO_IO_HANDLE_NONE,
480 String8(AudioParameter::keyReconfigA2dpSupported));
481 AudioParameter repliedParameters(reply);
482 repliedParameters.getInt(
483 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
484 if (isReconfigA2dpSupported) {
485 const String8 key(AudioParameter::keyReconfigA2dp);
486 param.add(key, String8("true"));
487 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
488 devDesc->setEncodedFormat(encodedFormat);
489 return NO_ERROR;
490 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700491 }
492 }
cnx421bd2dcc42020-07-11 14:58:44 +0800493 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
494 for (size_t i = 0; i < mOutputs.size(); i++) {
495 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
496 // mute media strategies and delay device switch by the largest
497 // This avoid sending the music tail into the earpiece or headset.
498 setStrategyMute(musicStrategy, true, desc);
499 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
500 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
501 nullptr, true /*fromCache*/).types());
502 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800503 // Toggle the device state: UNAVAILABLE -> AVAILABLE
504 // This will force reading again the device configuration
505 status = setDeviceConnectionState(device,
506 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800507 device_address, device_name,
508 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509 if (status != NO_ERROR) {
510 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
511 status);
512 return status;
513 }
514
515 status = setDeviceConnectionState(device,
516 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518 if (status != NO_ERROR) {
519 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
520 status);
521 return status;
522 }
523
524 return NO_ERROR;
525}
526
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800527status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
528 std::vector<audio_format_t> *formats)
529{
530 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800531 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800532 std::unordered_set<audio_format_t> formatSet;
533 sp<HwModule> primaryModule =
534 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700535 if (primaryModule == nullptr) {
536 ALOGE("%s() unable to get primary module", __func__);
537 return NO_INIT;
538 }
jiabin9a3361e2019-10-01 09:38:30 -0700539 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
540 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800541 for (const auto& device : declaredDevices) {
542 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800543 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800544 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800545 return status;
546}
547
François Gaffie11d30102018-11-02 16:09:09 +0100548uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700549{
550 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100551 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700552 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700553
jiabin9a3361e2019-10-01 09:38:30 -0700554 if(!hasPrimaryOutput() ||
555 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700556 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700557 }
François Gaffie11d30102018-11-02 16:09:09 +0100558 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
559
Francois Gaffie716e1432019-01-14 16:58:59 +0100560 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100561 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100562 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100563
564 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100565 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700566
567 // release existing RX patch if any
568 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100569 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700570 mCallRxPatch.clear();
571 }
572 // release TX patch if any
573 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100574 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700575 mCallTxPatch.clear();
576 }
577
François Gaffie9eb18552018-11-05 10:33:26 +0100578 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700579 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100580 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700581 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100582 // retrieve Rx Source and Tx Sink device descriptors
583 sp<DeviceDescriptor> rxSourceDevice =
584 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
585 String8(),
586 AUDIO_FORMAT_DEFAULT);
587 sp<DeviceDescriptor> txSinkDevice =
588 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
589 String8(),
590 AUDIO_FORMAT_DEFAULT);
591
592 // RX and TX Telephony device are declared by Primary Audio HAL
593 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
594 (telephonyRxModule->getHalVersionMajor() >= 3)) {
595 if (rxSourceDevice == 0 || txSinkDevice == 0) {
596 // RX / TX Telephony device(s) is(are) not currently available
597 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
598 return muteWaitMs;
599 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100600 // createAudioPatchInternal now supports both HW / SW bridging
601 createRxPatch = true;
602 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100603 } else {
604 // If the RX device is on the primary HW module, then use legacy routing method for
605 // voice calls via setOutputDevice() on primary output.
606 // Otherwise, create two audio patches for TX and RX path.
607 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
608 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 // If the TX device is also on the primary HW module, setOutputDevice() will take care
610 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100611 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
612 (txSinkDevice != 0);
613 }
614 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
615 // Otherwise, create two audio patches for TX and RX path.
616 if (!createRxPatch) {
617 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700618 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100619 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800620
621 // If the TX device is on the primary HW module but RX device is
622 // on other HW module, SinkMetaData of telephony input should handle it
623 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700624 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700625 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100626 // terminate active capture if on the same HW module as the call TX source device
627 // FIXME: would be better to refine to only inputs whose profile connects to the
628 // call TX device but this information is not in the audio patch and logic here must be
629 // symmetric to the one in startInput()
630 for (const auto& activeDesc : mInputs.getActiveInputs()) {
631 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
632 closeActiveClients(activeDesc);
633 }
634 }
François Gaffie9eb18552018-11-05 10:33:26 +0100635 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800636 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700637
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800638 return muteWaitMs;
639}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700640
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800641sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100642 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700643 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700644
François Gaffie11d30102018-11-02 16:09:09 +0100645 if (device == nullptr) {
646 return nullptr;
647 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100648
649 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800650 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100651 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800652 addSource(mAvailableInputDevices.getDevice(
653 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800654 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100655 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800656 addSink(mAvailableOutputDevices.getDevice(
657 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800658 }
659
François Gaffieafd4cea2019-11-18 15:50:22 +0100660 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
661 status_t status =
662 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
663 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
664 if (status != NO_ERROR || index < 0) {
665 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
666 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800667 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100668 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800669}
670
Mikhail Naganov100f0122018-11-29 11:22:16 -0800671bool AudioPolicyManager::isDeviceOfModule(
672 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
673 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
674 if (module != 0) {
675 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
676 .indexOf(devDesc) != NAME_NOT_FOUND
677 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
678 .indexOf(devDesc) != NAME_NOT_FOUND;
679 }
680 return false;
681}
682
Eric Laurente0720872014-03-11 09:30:41 -0700683void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700684{
685 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100686 // store previous phone state for management of sonification strategy below
687 int oldState = mEngine->getPhoneState();
688
689 if (mEngine->setPhoneState(state) != NO_ERROR) {
690 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700691 return;
692 }
François Gaffie2110e042015-03-24 08:41:51 +0100693 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700694 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700695 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700696 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800697 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700698 }
699
François Gaffie2110e042015-03-24 08:41:51 +0100700 /**
701 * Switching to or from incall state or switching between telephony and VoIP lead to force
702 * routing command.
703 */
Eric Laurent74b71512019-11-06 17:21:57 -0800704 bool force = ((isStateInCall(oldState) != isStateInCall(state))
705 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700706
707 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700708 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700709
Eric Laurente552edb2014-03-10 17:42:56 -0700710 int delayMs = 0;
711 if (isStateInCall(state)) {
712 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100713 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
714 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700715 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700716 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700717 // mute media and sonification strategies and delay device switch by the largest
718 // latency of any output where either strategy is active.
719 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100720 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
721 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
722 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700723 (delayMs < (int)desc->latency()*2)) {
724 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700725 }
François Gaffiec005e562018-11-06 15:04:49 +0100726 setStrategyMute(musicStrategy, true, desc);
727 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
728 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
729 nullptr, true /*fromCache*/).types());
730 setStrategyMute(sonificationStrategy, true, desc);
731 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
732 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
733 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700734 }
735 }
736
Eric Laurent87ffa392015-05-22 10:32:38 -0700737 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100738 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700739 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100740 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700741 // force routing command to audio hardware when ending call
742 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100743 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
744 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700745 }
Eric Laurente552edb2014-03-10 17:42:56 -0700746
Eric Laurent87ffa392015-05-22 10:32:38 -0700747 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100748 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700749 } else if (oldState == AUDIO_MODE_IN_CALL) {
750 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100751 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700752 mCallRxPatch.clear();
753 }
754 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100755 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700756 mCallTxPatch.clear();
757 }
François Gaffie11d30102018-11-02 16:09:09 +0100758 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700759 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100760 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700761 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700762 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700763
764 // reevaluate routing on all outputs in case tracks have been started during the call
765 for (size_t i = 0; i < mOutputs.size(); i++) {
766 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100767 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700768 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100769 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700770 }
771 }
772
Eric Laurente552edb2014-03-10 17:42:56 -0700773 if (isStateInCall(state)) {
774 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700775 // force reevaluating accessibility routing when call starts
776 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700777 }
778
779 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100780 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
781 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700782}
783
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700784audio_mode_t AudioPolicyManager::getPhoneState() {
785 return mEngine->getPhoneState();
786}
787
Eric Laurente0720872014-03-11 09:30:41 -0700788void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100789 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700790{
François Gaffie2110e042015-03-24 08:41:51 +0100791 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700792 if (config == mEngine->getForceUse(usage)) {
793 return;
794 }
Eric Laurente552edb2014-03-10 17:42:56 -0700795
François Gaffie2110e042015-03-24 08:41:51 +0100796 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
797 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
798 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700799 }
François Gaffie2110e042015-03-24 08:41:51 +0100800 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
801 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
802 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700803
804 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700805 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800806
Eric Laurent22fcda22019-05-17 16:28:47 -0700807 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
808 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
809 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
810 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
811 }
812
Eric Laurentdc462862016-07-19 12:29:53 -0700813 //FIXME: workaround for truncated touch sounds
814 // to be removed when the problem is handled by system UI
815 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700816 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
817 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
818 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700819
820 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100821 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700822}
823
Eric Laurente0720872014-03-11 09:30:41 -0700824void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700825{
826 ALOGV("setSystemProperty() property %s, value %s", property, value);
827}
828
Michael Chana94fbb22018-04-24 14:31:19 +1000829// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
830// search to profiles for direct outputs.
831sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100832 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000833 uint32_t samplingRate,
834 audio_format_t format,
835 audio_channel_mask_t channelMask,
836 audio_output_flags_t flags,
837 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700838{
Michael Chana94fbb22018-04-24 14:31:19 +1000839 if (directOnly) {
840 // only retain flags that will drive the direct output profile selection
841 // if explicitly requested
842 static const uint32_t kRelevantFlags =
843 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700844 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000845 flags =
846 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
847 }
Eric Laurent861a6282015-05-18 15:40:16 -0700848
849 sp<IOProfile> profile;
850
Mikhail Naganovd4120142017-12-06 15:49:22 -0800851 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800852 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100853 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700854 samplingRate, NULL /*updatedSamplingRate*/,
855 format, NULL /*updatedFormat*/,
856 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700857 flags)) {
858 continue;
859 }
860 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100861 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700862 continue;
863 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800864 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700865 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800866 continue;
867 }
Michael Chana94fbb22018-04-24 14:31:19 +1000868 if (!directOnly) return curProfile;
869 // when searching for direct outputs, if several profiles are compatible, give priority
870 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100871 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700872 continue;
873 }
874 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100875 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700876 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700877 }
Eric Laurente552edb2014-03-10 17:42:56 -0700878 }
879 }
Eric Laurent861a6282015-05-18 15:40:16 -0700880 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700881}
882
Eric Laurentf4e63452017-11-06 19:31:46 +0000883audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700884{
François Gaffiec005e562018-11-06 15:04:49 +0100885 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800886
887 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
888 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
889 // format, flags, etc. This may result in some discrepancy for functions that utilize
890 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
891 // and AudioSystem::getOutputSamplingRate().
892
François Gaffie11d30102018-11-02 16:09:09 +0100893 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700894 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700895
François Gaffie11d30102018-11-02 16:09:09 +0100896 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
897 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000898 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700899}
900
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700901status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
902 const audio_attributes_t *srcAttr,
903 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700905 if (srcAttr != NULL) {
906 if (!isValidAttributes(srcAttr)) {
907 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
908 __func__,
909 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
910 srcAttr->tags);
911 return BAD_VALUE;
912 }
913 *dstAttr = *srcAttr;
914 } else {
915 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
916 ALOGE("%s: invalid stream type", __func__);
917 return BAD_VALUE;
918 }
François Gaffiec005e562018-11-06 15:04:49 +0100919 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700920 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700921
922 // Only honor audibility enforced when required. The client will be
923 // forced to reconnect if the forced usage changes.
924 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700925 dstAttr->flags = static_cast<audio_flags_mask_t>(
926 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700927 }
928
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700929 return NO_ERROR;
930}
931
Kevin Rocard153f92d2018-12-18 18:33:28 -0800932status_t AudioPolicyManager::getOutputForAttrInt(
933 audio_attributes_t *resultAttr,
934 audio_io_handle_t *output,
935 audio_session_t session,
936 const audio_attributes_t *attr,
937 audio_stream_type_t *stream,
938 uid_t uid,
939 const audio_config_t *config,
940 audio_output_flags_t *flags,
941 audio_port_handle_t *selectedDeviceId,
942 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700943 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800944 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700945{
François Gaffiec005e562018-11-06 15:04:49 +0100946 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100947 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100948 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100949 const sp<DeviceDescriptor> requestedDevice =
950 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
951
Eric Laurent8a1095a2019-11-08 14:44:16 -0800952 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700953 status_t status = getAudioAttributes(resultAttr, attr, *stream);
954 if (status != NO_ERROR) {
955 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700956 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700957 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700958 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700959 }
François Gaffiec005e562018-11-06 15:04:49 +0100960 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700961
François Gaffiec005e562018-11-06 15:04:49 +0100962 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
963 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700964
Kevin Rocard153f92d2018-12-18 18:33:28 -0800965 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
966 // otherwise, fallback to the dynamic policies, if none match, query the engine.
967 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700968 sp<AudioPolicyMix> primaryMix;
969 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700970 if (status != OK) {
971 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800972 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700973
Kevin Rocard153f92d2018-12-18 18:33:28 -0800974 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700975 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800976
977 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700978 if ((usePrimaryOutputFromPolicyMixes
979 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800980 && !audio_is_linear_pcm(config->format)) {
981 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800982 return BAD_VALUE;
983 }
984 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700985 sp<DeviceDescriptor> deviceDesc =
986 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
987 primaryMix->mDeviceAddress,
988 AUDIO_FORMAT_DEFAULT);
989 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -0700990 if (deviceDesc != nullptr
991 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700992 audio_io_handle_t newOutput;
993 status = openDirectOutput(
994 *stream, session, config,
995 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
996 DeviceVector(deviceDesc), &newOutput);
997 if (status != NO_ERROR) {
998 policyDesc = nullptr;
999 } else {
1000 policyDesc = mOutputs.valueFor(newOutput);
1001 primaryMix->setOutput(policyDesc);
1002 }
1003 }
1004 if (policyDesc != nullptr) {
1005 policyDesc->mPolicyMix = primaryMix;
1006 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001007 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001008
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001009 ALOGV("getOutputForAttr() returns output %d", *output);
1010 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1011 *outputType = API_OUT_MIX_PLAYBACK;
1012 } else {
1013 *outputType = API_OUTPUT_LEGACY;
1014 }
1015 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001016 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001017 }
François Gaffiec005e562018-11-06 15:04:49 +01001018 // Virtual sources must always be dynamicaly or explicitly routed
1019 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1020 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1021 return BAD_VALUE;
1022 }
1023 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1024 // in order to let the choice of the order to future vendor engine
1025 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001026
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001027 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001028 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001029 }
1030
Nadav Barb2f18162018-07-18 13:01:53 +03001031 // Set incall music only if device was explicitly set, and fallback to the device which is
1032 // chosen by the engine if not.
1033 // FIXME: provide a more generic approach which is not device specific and move this back
1034 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001035 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001036 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001037 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001038 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001039 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001040 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001041 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001042 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001043 }
1044 }
1045
François Gaffiec005e562018-11-06 15:04:49 +01001046 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1047 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1048 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001049
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001050 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001051 if (!msdDevices.isEmpty()) {
1052 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001053 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1054 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1055 ALOGV("%s() Using MSD devices %s instead of devices %s",
1056 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001057 } else {
1058 *output = AUDIO_IO_HANDLE_NONE;
1059 }
1060 }
1061 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001062 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001063 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001064 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001065 if (*output == AUDIO_IO_HANDLE_NONE) {
1066 return INVALID_OPERATION;
1067 }
Paul McLeanaa981192015-03-21 09:55:15 -07001068
François Gaffiec005e562018-11-06 15:04:49 +01001069 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001070
Eric Laurent8a1095a2019-11-08 14:44:16 -08001071 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1072 *outputType = API_OUTPUT_TELEPHONY_TX;
1073 } else {
1074 *outputType = API_OUTPUT_LEGACY;
1075 }
1076
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001077 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1078
1079 return NO_ERROR;
1080}
1081
1082status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1083 audio_io_handle_t *output,
1084 audio_session_t session,
1085 audio_stream_type_t *stream,
1086 uid_t uid,
1087 const audio_config_t *config,
1088 audio_output_flags_t *flags,
1089 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001090 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001091 std::vector<audio_io_handle_t> *secondaryOutputs,
1092 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001093{
1094 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1095 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1096 return INVALID_OPERATION;
1097 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001098 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001099 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001100 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001101 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001102 const sp<DeviceDescriptor> requestedDevice =
1103 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1104
1105 // Prevent from storing invalid requested device id in clients
1106 const audio_port_handle_t sanitizedRequestedPortId =
1107 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1108 *selectedDeviceId = sanitizedRequestedPortId;
1109
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001111 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001112 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113 if (status != NO_ERROR) {
1114 return status;
1115 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001116 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001117 if (secondaryOutputs != nullptr) {
1118 for (auto &secondaryMix : secondaryMixes) {
1119 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1120 if (outputDesc != nullptr &&
1121 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1122 secondaryOutputs->push_back(outputDesc->mIoHandle);
1123 weakSecondaryOutputDescs.push_back(outputDesc);
1124 }
1125 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001126 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001127
Eric Laurent8fc147b2018-07-22 19:13:55 -07001128 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001129 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001130 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001131 };
jiabin4ef93452019-09-10 14:29:54 -07001132 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001133
Eric Laurentc209fe42020-06-05 18:11:23 -07001134 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001135 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001136 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001137 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001138 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001139 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001140 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001141 std::move(weakSecondaryOutputDescs),
1142 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001143 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001144
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001145 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1146 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001147
Eric Laurente83b55d2014-11-14 10:06:21 -08001148 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001149}
1150
Eric Laurentc529cf62020-04-17 18:19:10 -07001151status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1152 audio_session_t session,
1153 const audio_config_t *config,
1154 audio_output_flags_t flags,
1155 const DeviceVector &devices,
1156 audio_io_handle_t *output) {
1157
1158 *output = AUDIO_IO_HANDLE_NONE;
1159
1160 // skip direct output selection if the request can obviously be attached to a mixed output
1161 // and not explicitly requested
1162 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1163 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1164 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1165 return NAME_NOT_FOUND;
1166 }
1167
1168 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1169 // This prevents creating an offloaded track and tearing it down immediately after start
1170 // when audioflinger detects there is an active non offloadable effect.
1171 // FIXME: We should check the audio session here but we do not have it in this context.
1172 // This may prevent offloading in rare situations where effects are left active by apps
1173 // in the background.
1174 sp<IOProfile> profile;
1175 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1176 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1177 profile = getProfileForOutput(
1178 devices, config->sample_rate, config->format, config->channel_mask,
1179 flags, true /* directOnly */);
1180 }
1181
1182 if (profile == nullptr) {
1183 return NAME_NOT_FOUND;
1184 }
1185
1186 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1187 for (size_t i = 0; i < mOutputs.size(); i++) {
1188 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1189 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1190 // reuse direct output if currently open by the same client
1191 // and configured with same parameters
1192 if ((config->sample_rate == desc->getSamplingRate()) &&
1193 (config->format == desc->getFormat()) &&
1194 (config->channel_mask == desc->getChannelMask()) &&
1195 (session == desc->mDirectClientSession)) {
1196 desc->mDirectOpenCount++;
1197 ALOGI("%s reusing direct output %d for session %d", __func__,
1198 mOutputs.keyAt(i), session);
1199 *output = mOutputs.keyAt(i);
1200 return NO_ERROR;
1201 }
1202 }
1203 }
1204
1205 if (!profile->canOpenNewIo()) {
1206 return NAME_NOT_FOUND;
1207 }
1208
1209 sp<SwAudioOutputDescriptor> outputDesc =
1210 new SwAudioOutputDescriptor(profile, mpClientInterface);
1211
1212 String8 address = getFirstDeviceAddress(devices);
1213
1214 // MSD patch may be using the only output stream that can service this request. Release
1215 // MSD patch to prioritize this request over any active output on MSD.
1216 AudioPatchCollection msdPatches = getMsdPatches();
1217 for (size_t i = 0; i < msdPatches.size(); i++) {
1218 const auto& patch = msdPatches[i];
1219 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1220 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1221 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1222 devices.containsDeviceWithType(sink->ext.device.type) &&
1223 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1224 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1225 releaseAudioPatch(patch->getHandle(), mUidCached);
1226 break;
1227 }
1228 }
1229 }
1230
1231 status_t status = outputDesc->open(config, devices, stream, flags, output);
1232
1233 // only accept an output with the requested parameters
1234 if (status != NO_ERROR ||
1235 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1236 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1237 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1238 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1239 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1240 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1241 config->channel_mask, outputDesc->getChannelMask());
1242 if (*output != AUDIO_IO_HANDLE_NONE) {
1243 outputDesc->close();
1244 }
1245 // fall back to mixer output if possible when the direct output could not be open
1246 if (audio_is_linear_pcm(config->format) &&
1247 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1248 return NAME_NOT_FOUND;
1249 }
1250 *output = AUDIO_IO_HANDLE_NONE;
1251 return BAD_VALUE;
1252 }
1253 outputDesc->mDirectOpenCount = 1;
1254 outputDesc->mDirectClientSession = session;
1255
1256 addOutput(*output, outputDesc);
1257 mPreviousOutputs = mOutputs;
1258 ALOGV("%s returns new direct output %d", __func__, *output);
1259 mpClientInterface->onAudioPortListUpdate();
1260 return NO_ERROR;
1261}
1262
François Gaffie11d30102018-11-02 16:09:09 +01001263audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1264 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001265 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001266 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001267 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001268 audio_output_flags_t *flags,
1269 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001270{
Andy Hungc88b0642018-04-27 15:42:35 -07001271 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001272
jiabine375d412019-02-26 12:54:53 -08001273 // Discard haptic channel mask when forcing muting haptic channels.
1274 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001275 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1276 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001277
Eric Laurente552edb2014-03-10 17:42:56 -07001278 // open a direct output if required by specified parameters
1279 //force direct flag if offload flag is set: offloading implies a direct output stream
1280 // and all common behaviors are driven by checking only the direct flag
1281 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001282 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1283 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001284 }
Nadav Bar766fb022018-01-07 12:18:03 +02001285 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1286 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001287 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001288 // only allow deep buffering for music stream type
1289 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001290 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001291 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001292 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001293 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1294 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001295 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001296 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001297 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001298 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001299 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001300 audio_is_linear_pcm(config->format) &&
1301 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001302 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001303 AUDIO_OUTPUT_FLAG_DIRECT);
1304 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001305 }
Eric Laurente552edb2014-03-10 17:42:56 -07001306
Eric Laurentc529cf62020-04-17 18:19:10 -07001307 audio_config_t directConfig = *config;
1308 directConfig.channel_mask = channelMask;
1309 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1310 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001311 return output;
1312 }
1313
Eric Laurent14cbfca2016-03-17 09:42:16 -07001314 // A request for HW A/V sync cannot fallback to a mixed output because time
1315 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001316 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001317 return AUDIO_IO_HANDLE_NONE;
1318 }
1319
Eric Laurente552edb2014-03-10 17:42:56 -07001320 // ignoring channel mask due to downmix capability in mixer
1321
1322 // open a non direct output
1323
1324 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001325 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001326 // get which output is suitable for the specified stream. The actual
1327 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001328 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001329
Eric Laurent8838a382014-09-08 16:44:28 -07001330 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001331 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001332 output = selectOutput(
1333 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001334 }
François Gaffie11d30102018-11-02 16:09:09 +01001335 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001336 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001337 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001338
Eric Laurente552edb2014-03-10 17:42:56 -07001339 return output;
1340}
1341
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001342sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001343 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1344 mAvailableInputDevices);
1345 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1346}
1347
1348DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1349 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1350 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001351}
1352
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001353const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1354 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001355 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1356 if (msdModule != 0) {
1357 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1358 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1359 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1360 const struct audio_port_config *source = &patch->mPatch.sources[j];
1361 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1362 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001363 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001364 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 }
1366 }
1367 }
1368 return msdPatches;
1369}
1370
François Gaffie11d30102018-11-02 16:09:09 +01001371status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001372 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1373{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001374 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001375 if (msdModule == nullptr) {
1376 ALOGE("%s() unable to get MSD module", __func__);
1377 return NO_INIT;
1378 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001379 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001380 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001381 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001382 return NO_INIT;
1383 }
1384 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1385 if (inputProfiles.isEmpty()) {
1386 ALOGE("%s() no input profiles for MSD module", __func__);
1387 return NO_INIT;
1388 }
1389 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1390 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001391 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001392 return NO_INIT;
1393 }
1394 AudioProfileVector msdProfiles;
1395 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1396 for (const auto &inProfile : inputProfiles) {
1397 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001398 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001399 }
1400 }
1401 AudioProfileVector deviceProfiles;
1402 for (const auto &outProfile : outputProfiles) {
1403 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001404 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001405 }
1406 }
1407 struct audio_config_base bestSinkConfig;
jiabin3e277cc2019-09-10 14:27:34 -07001408 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001409 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabin3e277cc2019-09-10 14:27:34 -07001410 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001411 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001412 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1413 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001414 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001415 }
1416 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1417 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1418 sinkConfig->format = bestSinkConfig.format;
1419 // For encoded streams force direct flag to prevent downstream mixing.
1420 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1421 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001422 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1423 // For formats compatible with IEC61937 encapsulation, assume that
1424 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1425 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1426 // raw and IEC61937 framed streams.
1427 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1428 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1429 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001430 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1431 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1432 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1433 sourceConfig->format = bestSinkConfig.format;
1434 // Copy input stream directly without any processing (e.g. resampling).
1435 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1436 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1437 if (hwAvSync) {
1438 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1439 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1440 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1441 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1442 }
1443 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1444 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1445 sinkConfig->config_mask |= config_mask;
1446 sourceConfig->config_mask |= config_mask;
1447 return NO_ERROR;
1448}
1449
François Gaffie11d30102018-11-02 16:09:09 +01001450PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001451{
1452 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001453 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001454 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1455 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1456 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1457 // For now, we just forcefully try with HwAvSync first.
1458 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1459 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1460 getBestMsdAudioProfileFor(
1461 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1462 if (res == NO_ERROR) {
1463 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1464 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1465 }
1466 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1467 " supporting PCM format conversion.", __func__);
1468 return patchBuilder;
1469}
1470
François Gaffie11d30102018-11-02 16:09:09 +01001471status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1472 sp<DeviceDescriptor> device = outputDevice;
1473 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001474 // Use media strategy for unspecified output device. This should only
1475 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1476 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001477 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1478 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001479 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1480 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001481 }
François Gaffie11d30102018-11-02 16:09:09 +01001482 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1483 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001484 const struct audio_patch* patch = patchBuilder.patch();
1485 const AudioPatchCollection msdPatches = getMsdPatches();
1486 if (!msdPatches.isEmpty()) {
1487 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1488 "The current MSD prototype only supports one output patch");
1489 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1490 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1491 return NO_ERROR;
1492 }
François Gaffieafd4cea2019-11-18 15:50:22 +01001493 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001494 }
1495 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1496 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1497 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1498 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001499 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1500 device->toString().c_str(), patch->sources[0].format,
1501 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001502 return status;
1503}
1504
Eric Laurente0720872014-03-11 09:30:41 -07001505audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001506 audio_output_flags_t flags,
1507 audio_format_t format,
1508 audio_channel_mask_t channelMask,
1509 uint32_t samplingRate,
1510 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001511{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001512 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1513 "%s called with format %#x", __func__, format);
1514
jiabinebb6af42020-06-09 17:31:17 -07001515 // Return the output that haptic-generating attached to when 1) session id is specified,
1516 // 2) haptic-generating effect exists for given session id and 3) the output that
1517 // haptic-generating effect attached to is in given outputs.
1518 if (sessionId != AUDIO_SESSION_NONE) {
1519 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1520 sessionId, FX_IID_HAPTICGENERATOR);
1521 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1522 return hapticGeneratingOutput;
1523 }
1524 }
1525
Eric Laurent16c66dd2019-05-01 17:54:10 -07001526 // Flags disqualifying an output: the match must happen before calling selectOutput()
1527 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1528 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1529
1530 // Flags expressing a functional request: must be honored in priority over
1531 // other criteria
1532 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1533 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1534 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1535 // Flags expressing a performance request: have lower priority than serving
1536 // requested sampling rate or channel mask
1537 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1538 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1539 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1540
1541 const audio_output_flags_t functionalFlags =
1542 (audio_output_flags_t)(flags & kFunctionalFlags);
1543 const audio_output_flags_t performanceFlags =
1544 (audio_output_flags_t)(flags & kPerformanceFlags);
1545
1546 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1547
Eric Laurente552edb2014-03-10 17:42:56 -07001548 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001549 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001550 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001551 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001552 // 2: the output with the highest number of requested functional flags
1553 // 3: the output supporting the exact channel mask
1554 // 4: the output with a higher channel count than requested
1555 // 5: the output with a higher sampling rate than requested
1556 // 6: the output with the highest number of requested performance flags
1557 // 7: the output with the bit depth the closest to the requested one
1558 // 8: the primary output
1559 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001560
Eric Laurent16c66dd2019-05-01 17:54:10 -07001561 // matching criteria values in priority order for best matching output so far
1562 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001563
Eric Laurent16c66dd2019-05-01 17:54:10 -07001564 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1565 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1566 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001567
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001568 for (audio_io_handle_t output : outputs) {
1569 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001570 // matching criteria values in priority order for current output
1571 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001572
Eric Laurent16c66dd2019-05-01 17:54:10 -07001573 if (outputDesc->isDuplicated()) {
1574 continue;
1575 }
1576 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1577 continue;
1578 }
Eric Laurent8838a382014-09-08 16:44:28 -07001579
Eric Laurent16c66dd2019-05-01 17:54:10 -07001580 // If haptic channel is specified, use the haptic output if present.
1581 // When using haptic output, same audio format and sample rate are required.
1582 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001583 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001584 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1585 continue;
1586 }
1587 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001588 && format == outputDesc->getFormat()
1589 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001590 currentMatchCriteria[0] = outputHapticChannelCount;
1591 }
1592
1593 // functional flags match
1594 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1595
1596 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001597 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1598 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001599 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1600 channelCount <= outputChannelCount) {
1601 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001602 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1603 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001604 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001605 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001606 currentMatchCriteria[3] = outputChannelCount;
1607 }
1608
1609 // sampling rate match
1610 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001611 samplingRate <= outputDesc->getSamplingRate()) {
1612 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001613 }
1614
1615 // performance flags match
1616 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1617
1618 // format match
1619 if (format != AUDIO_FORMAT_INVALID) {
1620 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001621 PolicyAudioPort::kFormatDistanceMax -
1622 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001623 }
1624
1625 // primary output match
1626 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1627
1628 // compare match criteria by priority then value
1629 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1630 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1631 bestMatchCriteria = currentMatchCriteria;
1632 bestOutput = output;
1633
1634 std::stringstream result;
1635 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1636 std::ostream_iterator<int>(result, " "));
1637 ALOGV("%s new bestOutput %d criteria %s",
1638 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001639 }
1640 }
1641
Eric Laurent16c66dd2019-05-01 17:54:10 -07001642 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001643}
1644
Eric Laurent8fc147b2018-07-22 19:13:55 -07001645status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001646{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001647 ALOGV("%s portId %d", __FUNCTION__, portId);
1648
1649 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1650 if (outputDesc == 0) {
1651 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001652 return BAD_VALUE;
1653 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001654 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001655
Eric Laurent8fc147b2018-07-22 19:13:55 -07001656 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001657 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001658
Eric Laurent733ce942017-12-07 12:18:25 -08001659 status_t status = outputDesc->start();
1660 if (status != NO_ERROR) {
1661 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001662 }
1663
Eric Laurent97ac8712018-07-27 18:59:02 -07001664 uint32_t delayMs;
1665 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001666
1667 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001668 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001669 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001670 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001671 if (delayMs != 0) {
1672 usleep(delayMs * 1000);
1673 }
1674
1675 return status;
1676}
1677
Eric Laurent97ac8712018-07-27 18:59:02 -07001678status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1679 const sp<TrackClientDescriptor>& client,
1680 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001681{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001682 // cannot start playback of STREAM_TTS if any other output is being used
1683 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001684
1685 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001686 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001687 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001688 auto clientStrategy = client->strategy();
1689 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001690 if (stream == AUDIO_STREAM_TTS) {
1691 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001692 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001693 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001694 return INVALID_OPERATION;
1695 } else {
1696 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1697 }
1698 } else {
1699 // some playback other than beacon starts
1700 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1701 }
1702
Eric Laurent77305a62016-07-25 16:39:22 -07001703 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001704 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001705 bool force = !outputDesc->isActive() &&
1706 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001707
François Gaffie11d30102018-11-02 16:09:09 +01001708 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001709 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001710 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001711 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001712 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001713 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001714 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001715 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001716 } else {
1717 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001718 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001719 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1720 AUDIO_FORMAT_DEFAULT);
1721 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1722 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001723 }
1724
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001725 // requiresMuteCheck is false when we can bypass mute strategy.
1726 // It covers a common case when there is no materially active audio
1727 // and muting would result in unnecessary delay and dropped audio.
1728 const uint32_t outputLatencyMs = outputDesc->latency();
1729 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1730
Eric Laurente552edb2014-03-10 17:42:56 -07001731 // increment usage count for this stream on the requested output:
1732 // NOTE that the usage count is the same for duplicated output and hardware output which is
1733 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001734 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001735
1736 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001737 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1738 client->isPreferredDeviceForExclusiveUse()) {
1739 // Preferred device may be exclusive, use only if no other active clients on this output
1740 devices = DeviceVector(
1741 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1742 } else {
1743 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1744 }
François Gaffie11d30102018-11-02 16:09:09 +01001745 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001746 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001747 }
1748 }
Eric Laurente552edb2014-03-10 17:42:56 -07001749
François Gaffiec005e562018-11-06 15:04:49 +01001750 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001751 selectOutputForMusicEffects();
1752 }
1753
François Gaffie1c878552018-11-22 16:53:21 +01001754 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001755 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001756 if (devices.isEmpty()) {
1757 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001758 }
François Gaffiec005e562018-11-06 15:04:49 +01001759 bool shouldWait =
1760 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1761 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1762 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001763 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001764 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001765 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001766 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001767 // An output has a shared device if
1768 // - managed by the same hw module
1769 // - supports the currently selected device
1770 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001771 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001772
Eric Laurent77305a62016-07-25 16:39:22 -07001773 // force a device change if any other output is:
1774 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001775 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001776 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001777 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001778 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001779 // change the device currently selected by the other output.
1780 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001781 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001782 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001783 force = true;
1784 }
1785 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001786 // a notification so that audio focus effect can propagate, or that a mute/unmute
1787 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001788 const uint32_t latencyMs = desc->latency();
1789 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1790
1791 if (shouldWait && isActive && (waitMs < latencyMs)) {
1792 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001793 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001794
1795 // Require mute check if another output is on a shared device
1796 // and currently active to have proper drain and avoid pops.
1797 // Note restoring AudioTracks onto this output needs to invoke
1798 // a volume ramp if there is no mute.
1799 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001800 }
1801 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001802
1803 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001804 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001805
Eric Laurente552edb2014-03-10 17:42:56 -07001806 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001807 auto &curves = getVolumeCurves(client->attributes());
1808 checkAndSetVolume(curves, client->volumeSource(),
1809 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001810 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001811 outputDesc->devices().types(), 0 /*delay*/,
1812 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001813
1814 // update the outputs if starting an output with a stream that can affect notification
1815 // routing
1816 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001817
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001818 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001819 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001820 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1821 }
Eric Laurentdc462862016-07-19 12:29:53 -07001822
1823 if (waitMs > muteWaitMs) {
1824 *delayMs = waitMs - muteWaitMs;
1825 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001826
1827 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1828 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1829 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1830 // change occurs after the MixerThread starts and causes a stream volume
1831 // glitch.
1832 //
1833 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001834 }
Eric Laurentdc462862016-07-19 12:29:53 -07001835
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001836 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001837 mEngine->getForceUse(
1838 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001839 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001840 }
1841
Eric Laurent97ac8712018-07-27 18:59:02 -07001842 // Automatically enable the remote submix input when output is started on a re routing mix
1843 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001844 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1845 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001846 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1847 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1848 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001849 "remote-submix",
1850 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001851 }
1852
Eric Laurente552edb2014-03-10 17:42:56 -07001853 return NO_ERROR;
1854}
1855
Eric Laurent8fc147b2018-07-22 19:13:55 -07001856status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001857{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001858 ALOGV("%s portId %d", __FUNCTION__, portId);
1859
1860 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1861 if (outputDesc == 0) {
1862 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001863 return BAD_VALUE;
1864 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001865 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001866
Eric Laurent97ac8712018-07-27 18:59:02 -07001867 ALOGV("stopOutput() output %d, stream %d, session %d",
1868 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001869
Eric Laurent97ac8712018-07-27 18:59:02 -07001870 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001871
Eric Laurent733ce942017-12-07 12:18:25 -08001872 if (status == NO_ERROR ) {
1873 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001874 }
1875 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001876}
1877
Eric Laurent97ac8712018-07-27 18:59:02 -07001878status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1879 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001880{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001881 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001882 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001883 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001884
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001885 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1886
François Gaffie1c878552018-11-22 16:53:21 +01001887 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1888 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001889 // Automatically disable the remote submix input when output is stopped on a
1890 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001891 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001892 if (isSingleDeviceType(
1893 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001894 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001895 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001896 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1897 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001898 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001899 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001900 }
1901 }
1902 bool forceDeviceUpdate = false;
1903 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001904 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001905 forceDeviceUpdate = true;
1906 }
1907
Eric Laurente552edb2014-03-10 17:42:56 -07001908 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001909 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001910
Eric Laurente552edb2014-03-10 17:42:56 -07001911 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001912 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001913 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001914 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001915 // delay the device switch by twice the latency because stopOutput() is executed when
1916 // the track stop() command is received and at that time the audio track buffer can
1917 // still contain data that needs to be drained. The latency only covers the audio HAL
1918 // and kernel buffers. Also the latency does not always include additional delay in the
1919 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001920 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001921
1922 // force restoring the device selection on other active outputs if it differs from the
1923 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001924 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001925 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001926 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001927 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001928 desc->isActive() &&
1929 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001930 (newDevices != desc->devices())) {
1931 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1932 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001933
François Gaffie11d30102018-11-02 16:09:09 +01001934 setOutputDevices(desc, newDevices2, force, delayMs);
1935
Eric Laurent57de36c2016-09-28 16:59:11 -07001936 // re-apply device specific volume if not done by setOutputDevice()
1937 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001938 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001939 }
Eric Laurente552edb2014-03-10 17:42:56 -07001940 }
1941 }
1942 // update the outputs if stopping one with a stream that can affect notification routing
1943 handleNotificationRoutingForStream(stream);
1944 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001945
1946 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1947 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001948 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001949 }
1950
François Gaffiec005e562018-11-06 15:04:49 +01001951 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001952 selectOutputForMusicEffects();
1953 }
Eric Laurente552edb2014-03-10 17:42:56 -07001954 return NO_ERROR;
1955 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001956 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001957 return INVALID_OPERATION;
1958 }
1959}
1960
jiabinbce0c1d2020-10-05 11:20:18 -07001961bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001962{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001963 ALOGV("%s portId %d", __FUNCTION__, portId);
1964
1965 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1966 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001967 // If an output descriptor is closed due to a device routing change,
1968 // then there are race conditions with releaseOutput from tracks
1969 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1970 // destroyed shortly thereafter.
1971 //
1972 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001973 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07001974 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07001975 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001976
1977 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001978
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05301979 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
1980 if (outputDesc->isClientActive(client)) {
1981 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
1982 stopOutput(portId);
1983 }
1984
Eric Laurent8fc147b2018-07-22 19:13:55 -07001985 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1986 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001987 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001988 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07001989 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07001990 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001991 if (--outputDesc->mDirectOpenCount == 0) {
1992 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001993 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001994 }
1995 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05301996
Andy Hung39efb7a2018-09-26 15:39:28 -07001997 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07001998 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
1999 // The output is pending reopened to query dynamic profiles and
2000 // there is no active clients
2001 closeOutput(outputDesc->mIoHandle);
2002 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2003 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2004 if (newOutputDesc == nullptr) {
2005 ALOGE("%s failed to open output", __func__);
2006 }
2007 return true;
2008 }
2009 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002010}
2011
Eric Laurentcaf7f482014-11-25 17:50:47 -08002012status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2013 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002014 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002015 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002016 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002017 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002018 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002019 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002020 input_type_t *inputType,
2021 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002022{
François Gaffiec005e562018-11-06 15:04:49 +01002023 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2024 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2025 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002026
Eric Laurentad2e7b92017-09-14 20:06:42 -07002027 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002028 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002029 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002030 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002031 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002032 sp<AudioInputDescriptor> inputDesc;
2033 sp<RecordClientDescriptor> clientDesc;
2034 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002036
2037 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2038 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2039 return INVALID_OPERATION;
2040 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002041
Francois Gaffie716e1432019-01-14 16:58:59 +01002042 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2043 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002044 }
2045
Paul McLean466dc8e2015-04-17 13:15:36 -06002046 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002047 sp<DeviceDescriptor> explicitRoutingDevice =
2048 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002049
Eric Laurentad2e7b92017-09-14 20:06:42 -07002050 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2051 // possible
2052 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2053 *input != AUDIO_IO_HANDLE_NONE) {
2054 ssize_t index = mInputs.indexOfKey(*input);
2055 if (index < 0) {
2056 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2057 status = BAD_VALUE;
2058 goto error;
2059 }
2060 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002061 RecordClientVector clients = inputDesc->getClientsForSession(session);
2062 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002063 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2064 status = BAD_VALUE;
2065 goto error;
2066 }
2067 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2068 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002069 // corresponds to a new client and is only permitted from the same UID.
2070 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002071 if (clients.size() > 1) {
2072 for (const auto& client : clients) {
2073 // The client map is ordered by key values (portId) and portIds are allocated
2074 // incrementaly. So the first client in this list is the one opened by audio flinger
2075 // when the mmap stream is created and should be ignored as it does not correspond
2076 // to an actual client
2077 if (client == *clients.cbegin()) {
2078 continue;
2079 }
2080 if (uid != client->uid() && !client->isSilenced()) {
2081 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2082 uid, client->portId(), client->uid());
2083 status = INVALID_OPERATION;
2084 goto error;
2085 }
Eric Laurent331679c2018-04-16 17:03:16 -07002086 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002087 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002088 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002089 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002090
Eric Laurent8f42ea12018-08-08 09:08:25 -07002091 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002092 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002093 }
2094
2095 *input = AUDIO_IO_HANDLE_NONE;
2096 *inputType = API_INPUT_INVALID;
2097
Francois Gaffie716e1432019-01-14 16:58:59 +01002098 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002099
Francois Gaffie716e1432019-01-14 16:58:59 +01002100 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2101 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2102 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002103 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002104 ALOGW("%s could not find input mix for attr %s",
2105 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002106 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002107 }
jiabinc1de2df2019-05-07 14:26:40 -07002108 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2109 String8(attr->tags + strlen("addr=")),
2110 AUDIO_FORMAT_DEFAULT);
2111 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002112 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002113 __func__, attributes.source, attributes.tags);
2114 status = BAD_VALUE;
2115 goto error;
2116 }
2117
Kevin Rocard25f9b052019-02-27 15:08:54 -08002118 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2119 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2120 } else {
2121 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2122 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002123 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002124 if (explicitRoutingDevice != nullptr) {
2125 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002126 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002127 // Prevent from storing invalid requested device id in clients
2128 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002129 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002130 }
François Gaffie11d30102018-11-02 16:09:09 +01002131 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002132 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002133 status = BAD_VALUE;
2134 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002135 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002136 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002137 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2138 // there is an external policy, but this input is attached to a mix of recorders,
2139 // meaning it receives audio injected into the framework, so the recorder doesn't
2140 // know about it and is therefore considered "legacy"
2141 *inputType = API_INPUT_LEGACY;
2142 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002143 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002144 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002145 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002146 } else {
2147 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002148 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002149
Eric Laurent599c7582015-12-07 18:05:55 -08002150 }
2151
François Gaffiec005e562018-11-06 15:04:49 +01002152 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002153 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002154 status = INVALID_OPERATION;
2155 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002156 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002157
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158exit:
2159
François Gaffiec005e562018-11-06 15:04:49 +01002160 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2161 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002162
Francois Gaffie716e1432019-01-14 16:58:59 +01002163 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002164 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002165 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166
Mikhail Naganov2996f672019-04-18 12:29:59 -07002167 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002168 requestedDeviceId, attributes.source, flags,
2169 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002170 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002171 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002172
2173 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2174 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002175
Eric Laurent599c7582015-12-07 18:05:55 -08002176 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002177
2178error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002179 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002180}
2181
2182
François Gaffie11d30102018-11-02 16:09:09 +01002183audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002184 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002185 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002186 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002187 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002188 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002189{
2190 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002191 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002192 bool isSoundTrigger = false;
2193
François Gaffiec005e562018-11-06 15:04:49 +01002194 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002195 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2196 if (index >= 0) {
2197 input = mSoundTriggerSessions.valueFor(session);
2198 isSoundTrigger = true;
2199 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2200 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2201 } else {
2202 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002203 }
François Gaffiec005e562018-11-06 15:04:49 +01002204 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002205 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002206 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002207 }
2208
Andy Hungf129b032015-04-07 13:45:50 -07002209 // find a compatible input profile (not necessarily identical in parameters)
2210 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002211 // sampling rate and flags may be updated by getInputProfile
2212 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2213 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002214 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002215 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002216 audio_input_flags_t profileFlags = flags;
2217 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002218 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002219 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002220 profileFlags);
2221 if (profile != 0) {
2222 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002223 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2224 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002225 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2226 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2227 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002228 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2229 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2230 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002231 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002232 }
Eric Laurente552edb2014-03-10 17:42:56 -07002233 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002234 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002235 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002236 if (samplingRate == 0) {
2237 samplingRate = profileSamplingRate;
2238 }
Eric Laurente552edb2014-03-10 17:42:56 -07002239
Eric Laurent322b4d22015-04-03 15:57:54 -07002240 if (profile->getModuleHandle() == 0) {
2241 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002242 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002243 }
2244
Eric Laurent3974e3b2017-12-07 17:58:43 -08002245 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002246 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002247 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002248 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002249 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002250 continue;
2251 }
2252 // if sound trigger, reuse input if used by other sound trigger on same session
2253 // else
2254 // reuse input if active client app is not in IDLE state
2255 //
2256 RecordClientVector clients = desc->clientsList();
2257 bool doClose = false;
2258 for (const auto& client : clients) {
2259 if (isSoundTrigger != client->isSoundTrigger()) {
2260 continue;
2261 }
2262 if (client->isSoundTrigger()) {
2263 if (session == client->session()) {
2264 return desc->mIoHandle;
2265 }
2266 continue;
2267 }
2268 if (client->active() && client->appState() != APP_STATE_IDLE) {
2269 return desc->mIoHandle;
2270 }
2271 doClose = true;
2272 }
2273 if (doClose) {
2274 closeInput(desc->mIoHandle);
2275 } else {
2276 i++;
2277 }
2278 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002279 }
2280
Eric Laurentfe231122017-11-17 17:48:06 -08002281 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002282
Eric Laurentfe231122017-11-17 17:48:06 -08002283 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2284 lConfig.sample_rate = profileSamplingRate;
2285 lConfig.channel_mask = profileChannelMask;
2286 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002287
François Gaffie11d30102018-11-02 16:09:09 +01002288 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002289
2290 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002291 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002292 (profileSamplingRate != lConfig.sample_rate) ||
2293 !audio_formats_match(profileFormat, lConfig.format) ||
2294 (profileChannelMask != lConfig.channel_mask)) {
2295 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002296 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002297 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002298 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002299 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002300 }
Eric Laurent599c7582015-12-07 18:05:55 -08002301 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002302 }
2303
Eric Laurentc722f302014-12-10 11:21:49 -08002304 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002305
Eric Laurent599c7582015-12-07 18:05:55 -08002306 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002307 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002308
Eric Laurent599c7582015-12-07 18:05:55 -08002309 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002310}
2311
Eric Laurent4eb58f12018-12-07 16:41:02 -08002312status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002313{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002314 ALOGV("%s portId %d", __FUNCTION__, portId);
2315
2316 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2317 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002318 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002319 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002320 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002321 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002322 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002323 if (client->active()) {
2324 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2325 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002326 }
2327
Eric Laurent8f42ea12018-08-08 09:08:25 -07002328 audio_session_t session = client->session();
2329
Eric Laurent4eb58f12018-12-07 16:41:02 -08002330 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002331
Eric Laurent4eb58f12018-12-07 16:41:02 -08002332 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002333
Eric Laurent4eb58f12018-12-07 16:41:02 -08002334 status_t status = inputDesc->start();
2335 if (status != NO_ERROR) {
2336 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002337 }
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002339 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002340 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002341 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002342
Eric Laurent8f42ea12018-08-08 09:08:25 -07002343 // indicate active capture to sound trigger service if starting capture from a mic on
2344 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002345 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002346 if (device != nullptr) {
2347 status = setInputDevice(input, device, true /* force */);
2348 } else {
2349 ALOGW("%s no new input device can be found for descriptor %d",
2350 __FUNCTION__, inputDesc->getId());
2351 status = BAD_VALUE;
2352 }
Eric Laurente552edb2014-03-10 17:42:56 -07002353
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002354 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002355 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002356 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002357 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002358 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2359 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002360 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002361 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002362
François Gaffie11d30102018-11-02 16:09:09 +01002363 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2364 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002365 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002366 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002367 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002368
Eric Laurent8f42ea12018-08-08 09:08:25 -07002369 // automatically enable the remote submix output when input is started if not
2370 // used by a policy mix of type MIX_TYPE_RECORDERS
2371 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002372 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002373 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002374 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002375 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002376 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2377 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002378 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002379 if (address != "") {
2380 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2381 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002382 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002383 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002384 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002385 } else if (status != NO_ERROR) {
2386 // Restore client activity state.
2387 inputDesc->setClientActive(client, false);
2388 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002389 }
2390
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002391 ALOGV("%s input %d source = %d status = %d exit",
2392 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002393
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002394 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002395}
2396
Eric Laurent8fc147b2018-07-22 19:13:55 -07002397status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002398{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002399 ALOGV("%s portId %d", __FUNCTION__, portId);
2400
2401 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2402 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002403 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002404 return BAD_VALUE;
2405 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002406 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002407 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002408 if (!client->active()) {
2409 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002410 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002411 }
2412
Eric Laurent8f42ea12018-08-08 09:08:25 -07002413 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002414
Eric Laurent8f42ea12018-08-08 09:08:25 -07002415 inputDesc->stop();
2416 if (inputDesc->isActive()) {
2417 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2418 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002419 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002420 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002421 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002422 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2423 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002424 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002425 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002426
2427 // automatically disable the remote submix output when input is stopped if not
2428 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002429 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002430 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002431 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002432 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002433 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2434 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002435 }
2436 if (address != "") {
2437 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2438 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002439 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002440 }
2441 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002442 resetInputDevice(input);
2443
2444 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2445 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002446 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2447 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002448 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002449 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002450 }
2451 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002452 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002453 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002454}
2455
Eric Laurent8fc147b2018-07-22 19:13:55 -07002456void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002457{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002458 ALOGV("%s portId %d", __FUNCTION__, portId);
2459
2460 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2461 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002462 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002463 return;
2464 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002465 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002466 audio_io_handle_t input = inputDesc->mIoHandle;
2467
Eric Laurent8f42ea12018-08-08 09:08:25 -07002468 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002469
Andy Hung39efb7a2018-09-26 15:39:28 -07002470 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002471
Andy Hung39efb7a2018-09-26 15:39:28 -07002472 if (inputDesc->getClientCount() > 0) {
2473 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002474 return;
2475 }
2476
Eric Laurent05b90f82014-08-27 15:32:29 -07002477 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002478 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002479 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002480}
2481
Eric Laurent8f42ea12018-08-08 09:08:25 -07002482void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002483{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002484 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002485
2486 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002487 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002488 }
2489}
2490
Eric Laurent8f42ea12018-08-08 09:08:25 -07002491void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2492{
2493 stopInput(portId);
2494 releaseInput(portId);
2495}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002496
Eric Laurent0dd51852019-04-19 18:18:58 -07002497void AudioPolicyManager::checkCloseInputs() {
2498 // After connecting or disconnecting an input device, close input if:
2499 // - it has no client (was just opened to check profile) OR
2500 // - none of its supported devices are connected anymore OR
2501 // - one of its clients cannot be routed to one of its supported
2502 // devices anymore. Otherwise update device selection
2503 std::vector<audio_io_handle_t> inputsToClose;
2504 for (size_t i = 0; i < mInputs.size(); i++) {
2505 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2506 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002507 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002508 inputsToClose.push_back(mInputs.keyAt(i));
2509 } else {
2510 bool close = false;
2511 for (const auto& client : input->clientsList()) {
2512 sp<DeviceDescriptor> device =
2513 mEngine->getInputDeviceForAttributes(client->attributes());
2514 if (!input->supportedDevices().contains(device)) {
2515 close = true;
2516 break;
2517 }
2518 }
2519 if (close) {
2520 inputsToClose.push_back(mInputs.keyAt(i));
2521 } else {
2522 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2523 }
2524 }
2525 }
2526
2527 for (const audio_io_handle_t handle : inputsToClose) {
2528 ALOGV("%s closing input %d", __func__, handle);
2529 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002530 }
Eric Laurentd4692962014-05-05 18:13:44 -07002531}
2532
François Gaffie251c7f02018-11-07 10:41:08 +01002533void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002534{
2535 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002536 if (indexMin < 0 || indexMax < 0) {
2537 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2538 return;
2539 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002540 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002541
2542 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002543 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2544 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002545 continue;
2546 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002547 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002548 }
Eric Laurente552edb2014-03-10 17:42:56 -07002549}
2550
Eric Laurente0720872014-03-11 09:30:41 -07002551status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002552 int index,
2553 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002554{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002555 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002556 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2557 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2558 return NO_ERROR;
2559 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002560 ALOGV("%s: stream %s attributes=%s", __func__,
2561 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002562 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002563}
2564
Eric Laurente0720872014-03-11 09:30:41 -07002565status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002566 int *index,
2567 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002568{
François Gaffiec005e562018-11-06 15:04:49 +01002569 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2570 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002571 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002572 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002573 deviceTypes = mEngine->getOutputDevicesForStream(
2574 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002575 }
jiabin9a3361e2019-10-01 09:38:30 -07002576 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002577}
2578
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002579status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002580 int index,
2581 audio_devices_t device)
2582{
2583 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002584 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2585 if (group == VOLUME_GROUP_NONE) {
2586 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002587 return BAD_VALUE;
2588 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002589 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002590 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002591 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002592 VolumeSource vs = toVolumeSource(group);
2593 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2594
2595 status = setVolumeCurveIndex(index, device, curves);
2596 if (status != NO_ERROR) {
2597 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2598 return status;
2599 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002600
jiabin9a3361e2019-10-01 09:38:30 -07002601 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002602 auto curCurvAttrs = curves.getAttributes();
2603 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2604 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002605 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002606 } else if (!curves.getStreamTypes().empty()) {
2607 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002608 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002609 } else {
2610 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2611 return BAD_VALUE;
2612 }
jiabin9a3361e2019-10-01 09:38:30 -07002613 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2614 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002615
François Gaffiecfe17322018-11-07 13:41:29 +01002616 // update volume on all outputs and streams matching the following:
2617 // - The requested stream (or a stream matching for volume control) is active on the output
2618 // - The device (or devices) selected by the engine for this stream includes
2619 // the requested device
2620 // - For non default requested device, currently selected device on the output is either the
2621 // requested device or one of the devices selected by the engine for this stream
2622 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2623 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002624 for (size_t i = 0; i < mOutputs.size(); i++) {
2625 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002626 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002627
jiabin9a3361e2019-10-01 09:38:30 -07002628 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2629 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002630 }
François Gaffieed91f582020-01-31 10:35:37 +01002631 if (!(desc->isActive(vs) || isInCall())) {
2632 continue;
2633 }
2634 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2635 curDevices.find(device) == curDevices.end()) {
2636 continue;
2637 }
2638 bool applyVolume = false;
2639 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2640 curSrcDevices.insert(device);
2641 applyVolume = (curSrcDevices.find(
2642 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2643 } else {
2644 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2645 }
2646 if (!applyVolume) {
2647 continue; // next output
2648 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002649 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2650 // If a higher priority strategy is active, and the output is routed to a device with a
2651 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002652 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002653 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002654 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2655 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2656 false /*preferredDevice*/);
2657 if (activeClients.empty()) {
2658 continue;
2659 }
2660 bool isPreempted = false;
2661 bool isHigherPriority = productStrategy < strategy;
2662 for (const auto &client : activeClients) {
2663 if (isHigherPriority && (client->volumeSource() != vs)) {
2664 ALOGV("%s: Strategy=%d (\nrequester:\n"
2665 " group %d, volumeGroup=%d attributes=%s)\n"
2666 " higher priority source active:\n"
2667 " volumeGroup=%d attributes=%s) \n"
2668 " on output %zu, bailing out", __func__, productStrategy,
2669 group, group, toString(attributes).c_str(),
2670 client->volumeSource(), toString(client->attributes()).c_str(), i);
2671 applyVolume = false;
2672 isPreempted = true;
2673 break;
2674 }
2675 // However, continue for loop to ensure no higher prio clients running on output
2676 if (client->volumeSource() == vs) {
2677 applyVolume = true;
2678 }
2679 }
2680 if (isPreempted || applyVolume) {
2681 break;
2682 }
2683 }
2684 if (!applyVolume) {
2685 continue; // next output
2686 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002687 }
François Gaffieed91f582020-01-31 10:35:37 +01002688 //FIXME: workaround for truncated touch sounds
2689 // delayed volume change for system stream to be removed when the problem is
2690 // handled by system UI
2691 status_t volStatus = checkAndSetVolume(
2692 curves, vs, index, desc, curDevices,
2693 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2694 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2695 if (volStatus != NO_ERROR) {
2696 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002697 }
2698 }
François Gaffiecfe17322018-11-07 13:41:29 +01002699 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2700 return status;
2701}
2702
François Gaffieaaac0fd2018-11-22 17:56:39 +01002703status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002704 audio_devices_t device,
2705 IVolumeCurves &volumeCurves)
2706{
2707 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2708 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002709 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2710 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002711 (index > volumeCurves.getVolumeIndexMax())) {
2712 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2713 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2714 return BAD_VALUE;
2715 }
2716 if (!audio_is_output_device(device)) {
2717 return BAD_VALUE;
2718 }
2719
2720 // Force max volume if stream cannot be muted
2721 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2722
François Gaffieaaac0fd2018-11-22 17:56:39 +01002723 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002724 volumeCurves.addCurrentVolumeIndex(device, index);
2725 return NO_ERROR;
2726}
2727
2728status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2729 int &index,
2730 audio_devices_t device)
2731{
2732 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2733 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002734 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002735 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002736 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2737 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002738 }
jiabin9a3361e2019-10-01 09:38:30 -07002739 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002740}
2741
2742status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2743 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002744 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002745{
jiabin9a3361e2019-10-01 09:38:30 -07002746 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002747 return BAD_VALUE;
2748 }
jiabin9a3361e2019-10-01 09:38:30 -07002749 index = curves.getVolumeIndex(deviceTypes);
2750 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002751 return NO_ERROR;
2752}
2753
2754status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2755 int &index)
2756{
2757 index = getVolumeCurves(attr).getVolumeIndexMin();
2758 return NO_ERROR;
2759}
2760
2761status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2762 int &index)
2763{
2764 index = getVolumeCurves(attr).getVolumeIndexMax();
2765 return NO_ERROR;
2766}
2767
Eric Laurent36829f92017-04-07 19:04:42 -07002768audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002769{
2770 // select one output among several suitable for global effects.
2771 // The priority is as follows:
2772 // 1: An offloaded output. If the effect ends up not being offloadable,
2773 // AudioFlinger will invalidate the track and the offloaded output
2774 // will be closed causing the effect to be moved to a PCM output.
2775 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002776 // 3: The primary output
2777 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002778
François Gaffiec005e562018-11-06 15:04:49 +01002779 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2780 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002781 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002782
Eric Laurent36829f92017-04-07 19:04:42 -07002783 if (outputs.size() == 0) {
2784 return AUDIO_IO_HANDLE_NONE;
2785 }
Eric Laurente552edb2014-03-10 17:42:56 -07002786
Eric Laurent36829f92017-04-07 19:04:42 -07002787 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2788 bool activeOnly = true;
2789
2790 while (output == AUDIO_IO_HANDLE_NONE) {
2791 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2792 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2793 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2794
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002795 for (audio_io_handle_t output : outputs) {
2796 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002797 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002798 continue;
2799 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002800 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2801 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002802 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002803 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002804 }
2805 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002806 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002807 }
2808 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002809 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002810 }
2811 }
2812 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2813 output = outputOffloaded;
2814 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2815 output = outputDeepBuffer;
2816 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2817 output = outputPrimary;
2818 } else {
2819 output = outputs[0];
2820 }
2821 activeOnly = false;
2822 }
2823
2824 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002825 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002826 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2827 mMusicEffectOutput = output;
2828 }
2829
2830 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002831 return output;
2832}
2833
Eric Laurent36829f92017-04-07 19:04:42 -07002834audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2835{
2836 return selectOutputForMusicEffects();
2837}
2838
Eric Laurente0720872014-03-11 09:30:41 -07002839status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002840 audio_io_handle_t io,
2841 uint32_t strategy,
2842 int session,
2843 int id)
2844{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002845 if (session != AUDIO_SESSION_DEVICE) {
2846 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002847 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002848 index = mInputs.indexOfKey(io);
2849 if (index < 0) {
2850 ALOGW("registerEffect() unknown io %d", io);
2851 return INVALID_OPERATION;
2852 }
Eric Laurente552edb2014-03-10 17:42:56 -07002853 }
2854 }
François Gaffiec005e562018-11-06 15:04:49 +01002855 return mEffects.registerEffect(desc, io, session, id,
2856 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2857 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002858}
2859
Eric Laurentc241b0d2018-11-28 09:08:49 -08002860status_t AudioPolicyManager::unregisterEffect(int id)
2861{
2862 if (mEffects.getEffect(id) == nullptr) {
2863 return INVALID_OPERATION;
2864 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002865 if (mEffects.isEffectEnabled(id)) {
2866 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2867 setEffectEnabled(id, false);
2868 }
2869 return mEffects.unregisterEffect(id);
2870}
2871
2872status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2873{
2874 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2875 if (effect == nullptr) {
2876 return INVALID_OPERATION;
2877 }
2878
2879 status_t status = mEffects.setEffectEnabled(id, enabled);
2880 if (status == NO_ERROR) {
2881 mInputs.trackEffectEnabled(effect, enabled);
2882 }
2883 return status;
2884}
2885
Eric Laurent6c796322019-04-09 14:13:17 -07002886
2887status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2888{
2889 mEffects.moveEffects(ids, io);
2890 return NO_ERROR;
2891}
2892
Eric Laurentc75307b2015-03-17 15:29:32 -07002893bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2894{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002895 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002896}
2897
2898bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2899{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002900 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002901}
2902
Eric Laurente0720872014-03-11 09:30:41 -07002903bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002904{
2905 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002906 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002907 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002908 return true;
2909 }
2910 }
2911 return false;
2912}
2913
Eric Laurent275e8e92014-11-30 15:14:47 -08002914// Register a list of custom mixes with their attributes and format.
2915// When a mix is registered, corresponding input and output profiles are
2916// added to the remote submix hw module. The profile contains only the
2917// parameters (sampling rate, format...) specified by the mix.
2918// The corresponding input remote submix device is also connected.
2919//
2920// When a remote submix device is connected, the address is checked to select the
2921// appropriate profile and the corresponding input or output stream is opened.
2922//
2923// When capture starts, getInputForAttr() will:
2924// - 1 look for a mix matching the address passed in attribtutes tags if any
2925// - 2 if none found, getDeviceForInputSource() will:
2926// - 2.1 look for a mix matching the attributes source
2927// - 2.2 if none found, default to device selection by policy rules
2928// At this time, the corresponding output remote submix device is also connected
2929// and active playback use cases can be transferred to this mix if needed when reconnecting
2930// after AudioTracks are invalidated
2931//
2932// When playback starts, getOutputForAttr() will:
2933// - 1 look for a mix matching the address passed in attribtutes tags if any
2934// - 2 if none found, look for a mix matching the attributes usage
2935// - 3 if none found, default to device and output selection by policy rules.
2936
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002937status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002938{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002939 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2940 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002941 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002942 sp<HwModule> rSubmixModule;
2943 // examine each mix's route type
2944 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002945 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002946 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2947 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2948 ALOGE("Unsupported Policy Mix %zu of %zu: "
2949 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2950 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002951 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002952 break;
2953 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002954 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2955 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002956 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002957 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2958 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002959 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002960 rSubmixModule = mHwModules.getModuleFromName(
2961 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2962 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002963 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002964 i);
2965 res = INVALID_OPERATION;
2966 break;
2967 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002968 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002969
Eric Laurent97ac8712018-07-27 18:59:02 -07002970 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002971 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07002972 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002973 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002974 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2975 } else {
2976 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2977 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07002978 }
François Gaffie036e1e92015-03-19 10:16:24 +01002979
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002980 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002981 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002982 res = INVALID_OPERATION;
2983 break;
2984 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002985 audio_config_t outputConfig = mix.mFormat;
2986 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07002987 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
2988 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002989 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2990 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07002991 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002992 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07002993 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002994 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002995
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002996 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07002997 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2998 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2999 ALOGE("Failed to set remote submix device available, type %u, address %s",
3000 mix.mDeviceType, address.string());
3001 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003002 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003003 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3004 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003005 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003006 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003007 i, mixes.size(), type, address.string());
3008
3009 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3010 mix.mDeviceType, mix.mDeviceAddress,
3011 String8(), AUDIO_FORMAT_DEFAULT);
3012 if (device == nullptr) {
3013 res = INVALID_OPERATION;
3014 break;
3015 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003016
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003017 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003018 // First try to find an already opened output supporting the device
3019 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003020 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003021
Eric Laurentc529cf62020-04-17 18:19:10 -07003022 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003023 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003024 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3025 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003026 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003027 } else {
3028 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003029 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003030 }
3031 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003032 // If no output found, try to find a direct output profile supporting the device
3033 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3034 sp<HwModule> module = mHwModules[i];
3035 for (size_t j = 0;
3036 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3037 j++) {
3038 sp<IOProfile> profile = module->getOutputProfiles()[j];
3039 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3040 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3041 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3042 address.string());
3043 res = INVALID_OPERATION;
3044 } else {
3045 foundOutput = true;
3046 }
3047 }
3048 }
3049 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003050 if (res != NO_ERROR) {
3051 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003052 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003053 res = INVALID_OPERATION;
3054 break;
3055 } else if (!foundOutput) {
3056 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003057 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003058 res = INVALID_OPERATION;
3059 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003060 } else {
3061 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003062 }
Eric Laurentc722f302014-12-10 11:21:49 -08003063 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003064 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003065 if (res != NO_ERROR) {
3066 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003067 } else if (checkOutputs) {
3068 checkForDeviceAndOutputChanges();
3069 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003070 }
3071 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003072}
3073
3074status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3075{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003076 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003077 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003078 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003079 sp<HwModule> rSubmixModule;
3080 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003081 for (const auto& mix : mixes) {
3082 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003083
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003084 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003085 rSubmixModule = mHwModules.getModuleFromName(
3086 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3087 if (rSubmixModule == 0) {
3088 res = INVALID_OPERATION;
3089 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003090 }
3091 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003092
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003093 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003094
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003095 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003096 res = INVALID_OPERATION;
3097 continue;
3098 }
3099
Kevin Rocard04ed0462019-05-02 17:53:24 -07003100 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3101 if (getDeviceConnectionState(device, address.string()) ==
3102 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3103 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3104 address.string(), "remote-submix",
3105 AUDIO_FORMAT_DEFAULT);
3106 if (res != OK) {
3107 ALOGE("Error making RemoteSubmix device unavailable for mix "
3108 "with type %d, address %s", device, address.string());
3109 }
3110 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003111 }
jiabin5740f082019-08-19 15:08:30 -07003112 rSubmixModule->removeOutputProfile(address.c_str());
3113 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003114
Kevin Rocard153f92d2018-12-18 18:33:28 -08003115 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003116 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003117 res = INVALID_OPERATION;
3118 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003119 } else {
3120 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003121 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003122 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003123 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003124 if (res == NO_ERROR && checkOutputs) {
3125 checkForDeviceAndOutputChanges();
3126 updateCallAndOutputRouting();
3127 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003128 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003129}
3130
Mikhail Naganov100f0122018-11-29 11:22:16 -08003131void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3132{
3133 size_t i = 0;
3134 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3135 for (const auto& fmt : mManualSurroundFormats) {
3136 if (i++ != 0) dst->append(", ");
3137 std::string sfmt;
3138 FormatConverter::toString(fmt, sfmt);
3139 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3140 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3141 }
3142}
3143
Eric Laurentc529cf62020-04-17 18:19:10 -07003144// Returns true if all devices types match the predicate and are supported by one HW module
3145bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003146 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003147 std::function<bool(audio_devices_t)> predicate,
3148 const char *context) {
3149 for (size_t i = 0; i < devices.size(); i++) {
3150 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003151 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003152 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003153 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003154 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003155 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003156 return false;
3157 }
3158 }
3159 return true;
3160}
3161
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003162status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003163 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003164 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003165 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3166 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003167 }
3168 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003169 if (res != NO_ERROR) {
3170 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3171 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003172 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003173
3174 checkForDeviceAndOutputChanges();
3175 updateCallAndOutputRouting();
3176
3177 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003178}
3179
3180status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3181 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003182 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3183 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003184 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003185 __FUNCTION__, uid);
3186 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003187 }
3188
Eric Laurentc529cf62020-04-17 18:19:10 -07003189 checkForDeviceAndOutputChanges();
3190 updateCallAndOutputRouting();
3191
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003192 return res;
3193}
3194
Eric Laurent2517af32020-11-25 15:31:27 +01003195
jiabin0a488932020-08-07 17:32:40 -07003196status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3197 device_role_t role,
3198 const AudioDeviceTypeAddrVector &devices) {
3199 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3200 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003201
Eric Laurentc529cf62020-04-17 18:19:10 -07003202 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003203 return BAD_VALUE;
3204 }
jiabin0a488932020-08-07 17:32:40 -07003205 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003206 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003207 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3208 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003209 return status;
3210 }
3211
3212 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003213
3214 bool forceVolumeReeval = false;
3215 // FIXME: workaround for truncated touch sounds
3216 // to be removed when the problem is handled by system UI
3217 uint32_t delayMs = 0;
3218 if (strategy == mCommunnicationStrategy) {
3219 forceVolumeReeval = true;
3220 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3221 updateInputRouting();
3222 }
3223 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003224
3225 return NO_ERROR;
3226}
3227
3228void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3229{
3230 uint32_t waitMs = 0;
3231 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3232 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3233 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003234 // Only apply special touch sound delay once
3235 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003236 }
3237 for (size_t i = 0; i < mOutputs.size(); i++) {
3238 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3239 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3240 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3241 // As done in setDeviceConnectionState, we could also fix default device issue by
3242 // preventing the force re-routing in case of default dev that distinguishes on address.
3243 // Let's give back to engine full device choice decision however.
3244 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003245 // Only apply special touch sound delay once
3246 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003247 }
3248 if (forceVolumeReeval && !newDevices.isEmpty()) {
3249 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3250 }
3251 }
3252}
3253
Eric Laurent2517af32020-11-25 15:31:27 +01003254void AudioPolicyManager::updateInputRouting() {
3255 for (const auto& activeDesc : mInputs.getActiveInputs()) {
3256 auto newDevice = getNewInputDevice(activeDesc);
3257 // Force new input selection if the new device can not be reached via current input
3258 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3259 setInputDevice(activeDesc->mIoHandle, newDevice);
3260 } else {
3261 closeInput(activeDesc->mIoHandle);
3262 }
3263 }
3264}
3265
jiabin0a488932020-08-07 17:32:40 -07003266status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3267 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003268{
jiabin0a488932020-08-07 17:32:40 -07003269 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003270
jiabin0a488932020-08-07 17:32:40 -07003271 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003272 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003273 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3274 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003275 return status;
3276 }
3277
3278 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003279
3280 bool forceVolumeReeval = false;
3281 // FIXME: workaround for truncated touch sounds
3282 // to be removed when the problem is handled by system UI
3283 uint32_t delayMs = 0;
3284 if (strategy == mCommunnicationStrategy) {
3285 forceVolumeReeval = true;
3286 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3287 updateInputRouting();
3288 }
3289 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003290
3291 return NO_ERROR;
3292}
3293
jiabin0a488932020-08-07 17:32:40 -07003294status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3295 device_role_t role,
3296 AudioDeviceTypeAddrVector &devices) {
3297 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003298}
3299
Jiabin Huang3b98d322020-09-03 17:54:16 +00003300status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3301 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3302 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3303 dumpAudioDeviceTypeAddrVector(devices).c_str());
3304
Mikhail Naganov55773032020-10-01 15:08:13 -07003305 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003306 return BAD_VALUE;
3307 }
3308 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3309 ALOGW_IF(status != NO_ERROR,
3310 "Engine could not set preferred devices %s for audio source %d role %d",
3311 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3312
3313 return status;
3314}
3315
3316status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3317 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3318 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3319 dumpAudioDeviceTypeAddrVector(devices).c_str());
3320
Mikhail Naganov55773032020-10-01 15:08:13 -07003321 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003322 return BAD_VALUE;
3323 }
3324 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3325 ALOGW_IF(status != NO_ERROR,
3326 "Engine could not add preferred devices %s for audio source %d role %d",
3327 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3328
Eric Laurent2517af32020-11-25 15:31:27 +01003329 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003330 return status;
3331}
3332
3333status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3334 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3335{
3336 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3337 dumpAudioDeviceTypeAddrVector(devices).c_str());
3338
Mikhail Naganov55773032020-10-01 15:08:13 -07003339 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003340 return BAD_VALUE;
3341 }
3342
3343 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3344 audioSource, role, devices);
3345 ALOGW_IF(status != NO_ERROR,
3346 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3347
Eric Laurent2517af32020-11-25 15:31:27 +01003348 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003349 return status;
3350}
3351
3352status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3353 device_role_t role) {
3354 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3355
3356 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3357 ALOGW_IF(status != NO_ERROR,
3358 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3359
Eric Laurent2517af32020-11-25 15:31:27 +01003360 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003361 return status;
3362}
3363
3364status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3365 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3366 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3367}
3368
Oscar Azucena90e77632019-11-27 17:12:28 -08003369status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003370 const AudioDeviceTypeAddrVector& devices) {
3371 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003372 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3373 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003374 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003375 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3376 if (status != NO_ERROR) {
3377 ALOGE("%s() could not set device affinity for userId %d",
3378 __FUNCTION__, userId);
3379 return status;
3380 }
3381
3382 // reevaluate outputs for all devices
3383 checkForDeviceAndOutputChanges();
3384 updateCallAndOutputRouting();
3385
3386 return NO_ERROR;
3387}
3388
3389status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3390 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3391 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3392 if (status != NO_ERROR) {
3393 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3394 __FUNCTION__, userId);
3395 return status;
3396 }
3397
3398 // reevaluate outputs for all devices
3399 checkForDeviceAndOutputChanges();
3400 updateCallAndOutputRouting();
3401
3402 return NO_ERROR;
3403}
3404
Andy Hungc29d82b2018-10-05 12:23:17 -07003405void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003406{
Andy Hungc29d82b2018-10-05 12:23:17 -07003407 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3408 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003409 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003410 std::string stateLiteral;
3411 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003412 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003413 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3414 "communications", "media", "record", "dock", "system",
3415 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3416 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3417 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003418 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3419 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3420 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3421 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3422 dst->append(" (MANUAL: ");
3423 dumpManualSurroundFormats(dst);
3424 dst->append(")");
3425 }
3426 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003427 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003428 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3429 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003430 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003431 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003432
Andy Hungc29d82b2018-10-05 12:23:17 -07003433 mAvailableOutputDevices.dump(dst, String8("Available output"));
3434 mAvailableInputDevices.dump(dst, String8("Available input"));
3435 mHwModulesAll.dump(dst);
3436 mOutputs.dump(dst);
3437 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003438 mEffects.dump(dst);
3439 mAudioPatches.dump(dst);
3440 mPolicyMixes.dump(dst);
3441 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003442
Kevin Rocardb99cc752019-03-21 20:52:24 -07003443 dst->appendFormat(" AllowedCapturePolicies:\n");
3444 for (auto& policy : mAllowedCapturePolicies) {
3445 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3446 }
3447
François Gaffiec005e562018-11-06 15:04:49 +01003448 dst->appendFormat("\nPolicy Engine dump:\n");
3449 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003450}
3451
3452status_t AudioPolicyManager::dump(int fd)
3453{
3454 String8 result;
3455 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003456 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003457 return NO_ERROR;
3458}
3459
Kevin Rocardb99cc752019-03-21 20:52:24 -07003460status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3461{
3462 mAllowedCapturePolicies[uid] = capturePolicy;
3463 return NO_ERROR;
3464}
3465
Eric Laurente552edb2014-03-10 17:42:56 -07003466// This function checks for the parameters which can be offloaded.
3467// This can be enhanced depending on the capability of the DSP and policy
3468// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003469audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003470{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003471 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003472 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003473 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003474 offloadInfo.format,
3475 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3476 offloadInfo.has_video);
3477
Andy Hung2ddee192015-12-18 17:34:44 -08003478 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003479 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003480 }
3481
Eric Laurente552edb2014-03-10 17:42:56 -07003482 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003483 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003484 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3485 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003486 }
3487
3488 // Check if stream type is music, then only allow offload as of now.
3489 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3490 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003491 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3492 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003493 }
3494
3495 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003496 const bool allowOffloadWithVideo =
3497 property_get_bool("audio.offload.video", false /* default_value */);
3498 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003499 ALOGV("%s: has_video == true, returning false", __func__);
3500 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003501 }
3502
3503 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003504 const int min_duration_secs = property_get_int32(
3505 "audio.offload.min.duration.secs", -1 /* default_value */);
3506 if (min_duration_secs >= 0) {
3507 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003508 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3509 __func__, min_duration_secs);
3510 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003511 }
3512 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003513 ALOGV("%s: Offload denied by duration < default min(=%u)",
3514 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3515 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003516 }
3517
3518 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3519 // creating an offloaded track and tearing it down immediately after start when audioflinger
3520 // detects there is an active non offloadable effect.
3521 // FIXME: We should check the audio session here but we do not have it in this context.
3522 // This may prevent offloading in rare situations where effects are left active by apps
3523 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003524 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003525 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003526 }
3527
3528 // See if there is a profile to support this.
3529 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003530 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003531 offloadInfo.sample_rate,
3532 offloadInfo.format,
3533 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003534 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3535 true /* directOnly */);
Eric Laurent90fe31c2020-11-26 20:06:35 +01003536 ALOGV("%s: profile %sfound", __func__, profile != 0 ? "" : "NOT ");
3537 if (profile == nullptr) {
3538 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3539 }
3540 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3541 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3542 }
3543 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003544}
3545
Michael Chana94fbb22018-04-24 14:31:19 +10003546bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3547 const audio_attributes_t& attributes) {
3548 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003549 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003550 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003551 config.sample_rate,
3552 config.format,
3553 config.channel_mask,
3554 output_flags,
3555 true /* directOnly */);
3556 ALOGV("%s() profile %sfound with name: %s, "
3557 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3558 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003559 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003560 config.sample_rate, config.format, config.channel_mask, output_flags);
3561 return (profile != 0);
3562}
3563
Eric Laurent6a94d692014-05-20 11:18:06 -07003564status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3565 audio_port_type_t type,
3566 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003567 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003568 unsigned int *generation)
3569{
jiabin19cdba52020-11-24 11:28:58 -08003570 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3571 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003572 return BAD_VALUE;
3573 }
3574 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003575 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003576 *num_ports = 0;
3577 }
3578
3579 size_t portsWritten = 0;
3580 size_t portsMax = *num_ports;
3581 *num_ports = 0;
3582 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003583 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3584 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003585 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003586 for (const auto& dev : mAvailableOutputDevices) {
3587 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003588 continue;
3589 }
3590 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003591 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003592 }
3593 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003594 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003595 }
3596 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003597 for (const auto& dev : mAvailableInputDevices) {
3598 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003599 continue;
3600 }
3601 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003602 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003603 }
3604 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003605 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003606 }
3607 }
3608 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3609 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3610 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3611 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3612 }
3613 *num_ports += mInputs.size();
3614 }
3615 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003616 size_t numOutputs = 0;
3617 for (size_t i = 0; i < mOutputs.size(); i++) {
3618 if (!mOutputs[i]->isDuplicated()) {
3619 numOutputs++;
3620 if (portsWritten < portsMax) {
3621 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3622 }
3623 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003624 }
Eric Laurent84c70242014-06-23 08:46:27 -07003625 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003626 }
3627 }
3628 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003629 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003630 return NO_ERROR;
3631}
3632
jiabin19cdba52020-11-24 11:28:58 -08003633status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003634{
Eric Laurent99fcae42018-05-17 16:59:18 -07003635 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3636 return BAD_VALUE;
3637 }
3638 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3639 if (dev != 0) {
3640 dev->toAudioPort(port);
3641 return NO_ERROR;
3642 }
3643 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3644 if (dev != 0) {
3645 dev->toAudioPort(port);
3646 return NO_ERROR;
3647 }
3648 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3649 if (out != 0) {
3650 out->toAudioPort(port);
3651 return NO_ERROR;
3652 }
3653 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3654 if (in != 0) {
3655 in->toAudioPort(port);
3656 return NO_ERROR;
3657 }
3658 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003659}
3660
François Gaffieafd4cea2019-11-18 15:50:22 +01003661status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3662 audio_patch_handle_t *handle,
3663 uid_t uid, uint32_t delayMs,
3664 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003665{
François Gaffieafd4cea2019-11-18 15:50:22 +01003666 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003667 if (handle == NULL || patch == NULL) {
3668 return BAD_VALUE;
3669 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003670 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003671
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003672 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003673 return BAD_VALUE;
3674 }
3675 // only one source per audio patch supported for now
3676 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003677 return INVALID_OPERATION;
3678 }
Eric Laurent874c42872014-08-08 15:13:39 -07003679
3680 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003681 return INVALID_OPERATION;
3682 }
Eric Laurent874c42872014-08-08 15:13:39 -07003683 for (size_t i = 0; i < patch->num_sinks; i++) {
3684 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3685 return INVALID_OPERATION;
3686 }
3687 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003688
3689 sp<AudioPatch> patchDesc;
3690 ssize_t index = mAudioPatches.indexOfKey(*handle);
3691
François Gaffieafd4cea2019-11-18 15:50:22 +01003692 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3693 patch->sources[0].role,
3694 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003695#if LOG_NDEBUG == 0
3696 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003697 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3698 patch->sinks[i].role,
3699 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003700 }
3701#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003702
3703 if (index >= 0) {
3704 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003705 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3706 __func__, mUidCached, patchDesc->getUid(), uid);
3707 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003708 return INVALID_OPERATION;
3709 }
3710 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003711 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003712 }
3713
3714 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003715 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003716 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003717 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003718 return BAD_VALUE;
3719 }
Eric Laurent84c70242014-06-23 08:46:27 -07003720 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3721 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003722 if (patchDesc != 0) {
3723 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003724 ALOGV("%s source id differs for patch current id %d new id %d",
3725 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003726 return BAD_VALUE;
3727 }
3728 }
Eric Laurent874c42872014-08-08 15:13:39 -07003729 DeviceVector devices;
3730 for (size_t i = 0; i < patch->num_sinks; i++) {
3731 // Only support mix to devices connection
3732 // TODO add support for mix to mix connection
3733 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003734 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003735 return INVALID_OPERATION;
3736 }
3737 sp<DeviceDescriptor> devDesc =
3738 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3739 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003740 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003741 return BAD_VALUE;
3742 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003743
François Gaffie11d30102018-11-02 16:09:09 +01003744 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003745 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003746 NULL, // updatedSamplingRate
3747 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003748 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003749 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003750 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003751 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003752 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003753 return INVALID_OPERATION;
3754 }
3755 devices.add(devDesc);
3756 }
3757 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003758 return INVALID_OPERATION;
3759 }
Eric Laurent874c42872014-08-08 15:13:39 -07003760
Eric Laurent6a94d692014-05-20 11:18:06 -07003761 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003762 ALOGV("%s setting device %s on output %d",
3763 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003764 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003765 index = mAudioPatches.indexOfKey(*handle);
3766 if (index >= 0) {
3767 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003768 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003769 }
3770 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003771 patchDesc->setUid(uid);
3772 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003773 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003774 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003775 return INVALID_OPERATION;
3776 }
3777 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3778 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3779 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003780 // only one sink supported when connecting an input device to a mix
3781 if (patch->num_sinks > 1) {
3782 return INVALID_OPERATION;
3783 }
François Gaffie53615e22015-03-19 09:24:12 +01003784 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003785 if (inputDesc == NULL) {
3786 return BAD_VALUE;
3787 }
3788 if (patchDesc != 0) {
3789 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3790 return BAD_VALUE;
3791 }
3792 }
François Gaffie11d30102018-11-02 16:09:09 +01003793 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003794 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003795 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003796 return BAD_VALUE;
3797 }
3798
François Gaffie11d30102018-11-02 16:09:09 +01003799 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003800 patch->sinks[0].sample_rate,
3801 NULL, /*updatedSampleRate*/
3802 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003803 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003804 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003805 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003806 // FIXME for the parameter type,
3807 // and the NONE
3808 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003809 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003810 return INVALID_OPERATION;
3811 }
3812 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003813 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003814 device->toString().c_str(), inputDesc->mIoHandle);
3815 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003816 index = mAudioPatches.indexOfKey(*handle);
3817 if (index >= 0) {
3818 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003819 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003820 }
3821 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003822 patchDesc->setUid(uid);
3823 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003824 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003825 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003826 return INVALID_OPERATION;
3827 }
3828 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3829 // device to device connection
3830 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003831 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003832 return BAD_VALUE;
3833 }
3834 }
François Gaffie11d30102018-11-02 16:09:09 +01003835 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003836 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003837 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003838 return BAD_VALUE;
3839 }
Eric Laurent874c42872014-08-08 15:13:39 -07003840
Eric Laurent6a94d692014-05-20 11:18:06 -07003841 //update source and sink with our own data as the data passed in the patch may
3842 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003843 PatchBuilder patchBuilder;
3844 audio_port_config sourcePortConfig = {};
3845 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3846 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003847
Eric Laurent874c42872014-08-08 15:13:39 -07003848 for (size_t i = 0; i < patch->num_sinks; i++) {
3849 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003850 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003851 return INVALID_OPERATION;
3852 }
François Gaffie11d30102018-11-02 16:09:09 +01003853 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003854 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003855 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003856 return BAD_VALUE;
3857 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003858 audio_port_config sinkPortConfig = {};
3859 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3860 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003861
Eric Laurent3bcf8592015-04-03 12:13:24 -07003862 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003863 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003864 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003865 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01003866 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3867 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003868 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3869 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01003870 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3871 (sourceDesc != nullptr &&
3872 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003873 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003874 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003875 return INVALID_OPERATION;
3876 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003877 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3878 if (sourceDesc != nullptr) {
3879 // take care of dynamic routing for SwOutput selection,
3880 audio_attributes_t attributes = sourceDesc->attributes();
3881 audio_stream_type_t stream = sourceDesc->stream();
3882 audio_attributes_t resultAttr;
3883 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3884 config.sample_rate = sourceDesc->config().sample_rate;
3885 config.channel_mask = sourceDesc->config().channel_mask;
3886 config.format = sourceDesc->config().format;
3887 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3888 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3889 bool isRequestedDeviceForExclusiveUse = false;
François Gaffieafd4cea2019-11-18 15:50:22 +01003890 output_type_t outputType;
3891 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3892 &stream, sourceDesc->uid(), &config, &flags,
3893 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07003894 nullptr, &outputType);
François Gaffieafd4cea2019-11-18 15:50:22 +01003895 if (output == AUDIO_IO_HANDLE_NONE) {
3896 ALOGV("%s no output for device %s",
3897 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurent874c42872014-08-08 15:13:39 -07003898 return INVALID_OPERATION;
3899 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003900 } else {
3901 SortedVector<audio_io_handle_t> outputs =
3902 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3903 // if the sink device is reachable via an opened output stream, request to
3904 // go via this output stream by adding a second source to the patch
3905 // description
3906 output = selectOutput(outputs);
3907 }
3908 if (output != AUDIO_IO_HANDLE_NONE) {
3909 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3910 if (outputDesc->isDuplicated()) {
3911 ALOGV("%s output for device %s is duplicated",
3912 __FUNCTION__, sinkDevice->toString().c_str());
3913 return INVALID_OPERATION;
3914 }
3915 audio_port_config srcMixPortConfig = {};
3916 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
3917 if (sourceDesc != nullptr) {
3918 sourceDesc->setSwOutput(outputDesc);
3919 }
3920 // for volume control, we may need a valid stream
3921 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3922 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3923 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003924 }
Eric Laurent83b88082014-06-20 18:31:16 -07003925 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003926 }
3927 // TODO: check from routing capabilities in config file and other conflicting patches
3928
François Gaffieafd4cea2019-11-18 15:50:22 +01003929 status_t status = installPatch(
3930 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003931 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003932 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003933 return INVALID_OPERATION;
3934 }
3935 } else {
3936 return BAD_VALUE;
3937 }
3938 } else {
3939 return BAD_VALUE;
3940 }
3941 return NO_ERROR;
3942}
3943
3944status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3945 uid_t uid)
3946{
3947 ALOGV("releaseAudioPatch() patch %d", handle);
3948
3949 ssize_t index = mAudioPatches.indexOfKey(handle);
3950
3951 if (index < 0) {
3952 return BAD_VALUE;
3953 }
3954 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003955 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
3956 __func__, mUidCached, patchDesc->getUid(), uid);
3957 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003958 return INVALID_OPERATION;
3959 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003960 return releaseAudioPatchInternal(handle);
3961}
Eric Laurent6a94d692014-05-20 11:18:06 -07003962
François Gaffieafd4cea2019-11-18 15:50:22 +01003963status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
3964 uint32_t delayMs)
3965{
3966 ALOGV("%s patch %d", __func__, handle);
3967 if (mAudioPatches.indexOfKey(handle) < 0) {
3968 ALOGE("%s: no patch found with handle=%d", __func__, handle);
3969 return BAD_VALUE;
3970 }
3971 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003972 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01003973 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07003974 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003975 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003977 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003978 return BAD_VALUE;
3979 }
3980
François Gaffie11d30102018-11-02 16:09:09 +01003981 setOutputDevices(outputDesc,
3982 getNewOutputDevices(outputDesc, true /*fromCache*/),
3983 true,
3984 0,
3985 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003986 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3987 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003988 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003990 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003991 return BAD_VALUE;
3992 }
3993 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003994 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 true,
3996 NULL);
3997 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003998 status_t status =
3999 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4000 ALOGV("%s patch panel returned %d patchHandle %d",
4001 __func__, status, patchDesc->getAfHandle());
4002 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004003 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004004 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004005 // SW Bridge
4006 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4007 sp<SwAudioOutputDescriptor> outputDesc =
4008 mOutputs.getOutputFromId(patch->sources[1].id);
4009 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004010 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4011 // releaseOutput has already called closeOuput in case of direct output
4012 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004013 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004014 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4015 // force SwOutput patch removal as AF counter part patch has already gone.
4016 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4017 removeAudioPatch(outputDesc->getPatchHandle());
4018 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004019 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4020 setOutputDevices(outputDesc,
4021 getNewOutputDevices(outputDesc, true /*fromCache*/),
4022 true, /*force*/
4023 0,
4024 NULL);
4025 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004026 } else {
4027 return BAD_VALUE;
4028 }
4029 } else {
4030 return BAD_VALUE;
4031 }
4032 return NO_ERROR;
4033}
4034
4035status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4036 struct audio_patch *patches,
4037 unsigned int *generation)
4038{
François Gaffie53615e22015-03-19 09:24:12 +01004039 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 return BAD_VALUE;
4041 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004042 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004043 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004044}
4045
Eric Laurente1715a42014-05-20 11:30:42 -07004046status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004047{
Eric Laurente1715a42014-05-20 11:30:42 -07004048 ALOGV("setAudioPortConfig()");
4049
4050 if (config == NULL) {
4051 return BAD_VALUE;
4052 }
4053 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4054 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004055 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4056 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004057 }
4058
Eric Laurenta121f902014-06-03 13:32:54 -07004059 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004060 if (config->type == AUDIO_PORT_TYPE_MIX) {
4061 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004062 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004063 if (outputDesc == NULL) {
4064 return BAD_VALUE;
4065 }
Eric Laurent84c70242014-06-23 08:46:27 -07004066 ALOG_ASSERT(!outputDesc->isDuplicated(),
4067 "setAudioPortConfig() called on duplicated output %d",
4068 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004069 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004070 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004071 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004072 if (inputDesc == NULL) {
4073 return BAD_VALUE;
4074 }
Eric Laurenta121f902014-06-03 13:32:54 -07004075 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004076 } else {
4077 return BAD_VALUE;
4078 }
4079 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4080 sp<DeviceDescriptor> deviceDesc;
4081 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4082 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4083 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4084 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4085 } else {
4086 return BAD_VALUE;
4087 }
4088 if (deviceDesc == NULL) {
4089 return BAD_VALUE;
4090 }
Eric Laurenta121f902014-06-03 13:32:54 -07004091 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004092 } else {
4093 return BAD_VALUE;
4094 }
4095
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004096 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004097 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4098 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004099 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004100 audioPortConfig->toAudioPortConfig(&newConfig, config);
4101 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004102 }
Eric Laurenta121f902014-06-03 13:32:54 -07004103 if (status != NO_ERROR) {
4104 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004105 }
Eric Laurente1715a42014-05-20 11:30:42 -07004106
4107 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004108}
4109
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004110void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4111{
Eric Laurentd60560a2015-04-10 11:31:20 -07004112 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004113 clearAudioPatches(uid);
4114 clearSessionRoutes(uid);
4115}
4116
Eric Laurent6a94d692014-05-20 11:18:06 -07004117void AudioPolicyManager::clearAudioPatches(uid_t uid)
4118{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004119 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004120 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004121 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004122 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 }
4124 }
4125}
4126
François Gaffiec005e562018-11-06 15:04:49 +01004127void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004128{
François Gaffiec005e562018-11-06 15:04:49 +01004129 // Take the first attributes following the product strategy as it is used to retrieve the routed
4130 // device. All attributes wihin a strategy follows the same "routing strategy"
4131 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4132 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004133 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004134 for (size_t j = 0; j < mOutputs.size(); j++) {
4135 if (mOutputs.keyAt(j) == ouptutToSkip) {
4136 continue;
4137 }
4138 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004139 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004140 continue;
4141 }
4142 // If the default device for this strategy is on another output mix,
4143 // invalidate all tracks in this strategy to force re connection.
4144 // Otherwise select new device on the output mix.
4145 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004146 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4147 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004148 }
4149 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004150 setOutputDevices(
4151 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004152 }
4153 }
4154}
4155
4156void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4157{
4158 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004159 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004160 for (size_t i = 0; i < mOutputs.size(); i++) {
4161 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004162 for (const auto& client : outputDesc->getClientIterable()) {
4163 if (client->hasPreferredDevice() && client->uid() == uid) {
4164 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004165 auto clientStrategy = client->strategy();
4166 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4167 end(affectedStrategies)) {
4168 continue;
4169 }
4170 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004171 }
4172 }
4173 }
4174 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004175 for (const auto& strategy : affectedStrategies) {
4176 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004177 }
4178
4179 // remove input routes associated with this uid
4180 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004181 for (size_t i = 0; i < mInputs.size(); i++) {
4182 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004183 for (const auto& client : inputDesc->getClientIterable()) {
4184 if (client->hasPreferredDevice() && client->uid() == uid) {
4185 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4186 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004187 }
4188 }
4189 }
4190 // reroute inputs if necessary
4191 SortedVector<audio_io_handle_t> inputsToClose;
4192 for (size_t i = 0; i < mInputs.size(); i++) {
4193 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004194 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004195 inputsToClose.add(inputDesc->mIoHandle);
4196 }
4197 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004198 for (const auto& input : inputsToClose) {
4199 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004200 }
4201}
4202
Eric Laurentd60560a2015-04-10 11:31:20 -07004203void AudioPolicyManager::clearAudioSources(uid_t uid)
4204{
4205 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004206 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4207 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004208 stopAudioSource(mAudioSources.keyAt(i));
4209 }
4210 }
4211}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004212
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004213status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4214 audio_io_handle_t *ioHandle,
4215 audio_devices_t *device)
4216{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004217 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4218 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004219 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004220 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004221
François Gaffiedf372692015-03-19 10:43:27 +01004222 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004223}
4224
Eric Laurentd60560a2015-04-10 11:31:20 -07004225status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004226 const audio_attributes_t *attributes,
4227 audio_port_handle_t *portId,
4228 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004229{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004230 ALOGV("%s", __FUNCTION__);
4231 *portId = AUDIO_PORT_HANDLE_NONE;
4232
4233 if (source == NULL || attributes == NULL || portId == NULL) {
4234 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4235 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004236 return BAD_VALUE;
4237 }
4238
Eric Laurentd60560a2015-04-10 11:31:20 -07004239 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4240 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004241 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4242 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004243 return INVALID_OPERATION;
4244 }
4245
François Gaffie11d30102018-11-02 16:09:09 +01004246 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004247 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004248 String8(source->ext.device.address),
4249 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004250 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004251 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004252 return BAD_VALUE;
4253 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004254
jiabin4ef93452019-09-10 14:29:54 -07004255 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004256
François Gaffieaaac0fd2018-11-22 17:56:39 +01004257 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004258 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004259 mEngine->getStreamTypeForAttributes(*attributes),
4260 mEngine->getProductStrategyForAttributes(*attributes),
4261 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004262
4263 status_t status = connectAudioSource(sourceDesc);
4264 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004265 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004266 }
4267 return status;
4268}
4269
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004270status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004271{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004272 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004273
4274 // make sure we only have one patch per source.
4275 disconnectAudioSource(sourceDesc);
Francois Gaffieff1eb522020-05-06 18:37:04 +02004276 sourceDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurentd60560a2015-04-10 11:31:20 -07004277
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004278 audio_attributes_t attributes = sourceDesc->attributes();
François Gaffie11d30102018-11-02 16:09:09 +01004279 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07004280
François Gaffiec005e562018-11-06 15:04:49 +01004281 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004282 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004283 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004284 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
4285 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
4286 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07004287
François Gaffieafd4cea2019-11-18 15:50:22 +01004288 PatchBuilder patchBuilder;
4289 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4290 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4291 status_t status =
4292 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4293 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4294 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4295 return INVALID_OPERATION;
4296 }
4297 sourceDesc->setPatchHandle(handle);
4298 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4299 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4300 if (swOutput != 0) {
4301 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004302 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004303 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004304 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004305 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004306 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004307 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004308 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004309 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004310 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004311 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004312 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004313 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4314 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004315 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004316 if (delayMs != 0) {
4317 usleep(delayMs * 1000);
4318 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004319 } else {
4320 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4321 if (hwOutputDesc != 0) {
4322 // create Hwoutput and add to mHwOutputs
4323 } else {
4324 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4325 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004326 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004327 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004328
4329FailureSourceActive:
4330 swOutput->stop();
4331 releaseOutput(sourceDesc->portId());
4332FailureSourceAdded:
4333 sourceDesc->setSwOutput(nullptr);
4334FailureReleasePatch:
4335 releaseAudioPatchInternal(handle);
4336 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004337}
4338
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004339status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004340{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004341 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4342 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004343 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004344 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004345 return BAD_VALUE;
4346 }
4347 status_t status = disconnectAudioSource(sourceDesc);
4348
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004349 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004350 return status;
4351}
4352
Andy Hung2ddee192015-12-18 17:34:44 -08004353status_t AudioPolicyManager::setMasterMono(bool mono)
4354{
4355 if (mMasterMono == mono) {
4356 return NO_ERROR;
4357 }
4358 mMasterMono = mono;
4359 // if enabling mono we close all offloaded devices, which will invalidate the
4360 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4361 // for recreating the new AudioTrack as non-offloaded PCM.
4362 //
4363 // If disabling mono, we leave all tracks as is: we don't know which clients
4364 // and tracks are able to be recreated as offloaded. The next "song" should
4365 // play back offloaded.
4366 if (mMasterMono) {
4367 Vector<audio_io_handle_t> offloaded;
4368 for (size_t i = 0; i < mOutputs.size(); ++i) {
4369 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4370 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4371 offloaded.push(desc->mIoHandle);
4372 }
4373 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004374 for (const auto& handle : offloaded) {
4375 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004376 }
4377 }
4378 // update master mono for all remaining outputs
4379 for (size_t i = 0; i < mOutputs.size(); ++i) {
4380 updateMono(mOutputs.keyAt(i));
4381 }
4382 return NO_ERROR;
4383}
4384
4385status_t AudioPolicyManager::getMasterMono(bool *mono)
4386{
4387 *mono = mMasterMono;
4388 return NO_ERROR;
4389}
4390
Eric Laurentac9cef52017-06-09 15:46:26 -07004391float AudioPolicyManager::getStreamVolumeDB(
4392 audio_stream_type_t stream, int index, audio_devices_t device)
4393{
jiabin9a3361e2019-10-01 09:38:30 -07004394 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004395}
4396
jiabin81772902018-04-02 17:52:27 -07004397status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4398 audio_format_t *surroundFormats,
4399 bool *surroundFormatsEnabled,
4400 bool reported)
4401{
4402 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4403 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4404 return BAD_VALUE;
4405 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004406 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4407 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004408
4409 size_t formatsWritten = 0;
4410 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004411 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004412 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004413 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004414 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004415 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4416 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
Kriti Dangef6be8f2020-11-05 11:58:19 +01004417 audio_devices_t deviceType = device->type();
4418 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4419 // returns formats reported by HDMI devices.
4420 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4421 continue;
4422 }
4423 // Formats reported by sink devices
4424 std::unordered_set<audio_format_t> formatset;
4425 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4426 formatset.insert(it->second.begin(), it->second.end());
4427 }
4428
4429 // Formats hard-coded in the in policy configuration file (if any).
4430 FormatVector encodedFormats = device->encodedFormats();
4431 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4432 // Filter the formats which are supported by the vendor hardware.
4433 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4434 if (mConfig.getSurroundFormats().count(*it) != 0) {
4435 formats.insert(*it);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004436 } else {
4437 for (const auto& pair : mConfig.getSurroundFormats()) {
Kriti Dangef6be8f2020-11-05 11:58:19 +01004438 if (pair.second.count(*it) != 0) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004439 formats.insert(pair.first);
4440 break;
4441 }
4442 }
4443 }
4444 }
jiabin81772902018-04-02 17:52:27 -07004445 }
4446 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004447 for (const auto& pair : mConfig.getSurroundFormats()) {
4448 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004449 }
4450 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004451 *numSurroundFormats = formats.size();
4452 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4453 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004454 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004455 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004456 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004457 bool formatEnabled = true;
4458 switch (forceUse) {
4459 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4460 formatEnabled = mManualSurroundFormats.count(format) != 0;
4461 break;
4462 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4463 formatEnabled = false;
4464 break;
4465 default: // AUTO or ALWAYS => true
4466 break;
jiabin81772902018-04-02 17:52:27 -07004467 }
4468 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4469 }
jiabin81772902018-04-02 17:52:27 -07004470 }
4471 return NO_ERROR;
4472}
4473
4474status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4475{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004476 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004477 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4478 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004479 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004480 return BAD_VALUE;
4481 }
4482
Mikhail Naganov100f0122018-11-29 11:22:16 -08004483 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4484 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004485 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004486 return INVALID_OPERATION;
4487 }
4488
Mikhail Naganov100f0122018-11-29 11:22:16 -08004489 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004490 return NO_ERROR;
4491 }
4492
Mikhail Naganov100f0122018-11-29 11:22:16 -08004493 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004494 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004495 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004496 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004497 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004498 }
4499 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004500 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004501 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004502 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004503 }
4504 }
4505
4506 sp<SwAudioOutputDescriptor> outputDesc;
4507 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004508 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4509 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004510 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4511 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004512 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004513 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004514 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4515 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4516 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004517 name.c_str(),
4518 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004519 if (status != NO_ERROR) {
4520 continue;
4521 }
4522 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4523 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4524 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004525 name.c_str(),
4526 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004527 profileUpdated |= (status == NO_ERROR);
4528 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004529 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004530 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004531 AUDIO_DEVICE_IN_HDMI);
4532 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4533 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004534 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004535 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004536 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4537 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4538 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004539 name.c_str(),
4540 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004541 if (status != NO_ERROR) {
4542 continue;
4543 }
4544 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4545 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4546 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004547 name.c_str(),
4548 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004549 profileUpdated |= (status == NO_ERROR);
4550 }
4551
jiabin81772902018-04-02 17:52:27 -07004552 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004553 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004554 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004555 }
4556
4557 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4558}
4559
Eric Laurent5ada82e2019-08-29 17:53:54 -07004560void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004561{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004562 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004563 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004564 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004565 }
4566}
4567
jiabin6012f912018-11-02 17:06:30 -07004568bool AudioPolicyManager::isHapticPlaybackSupported()
4569{
4570 for (const auto& hwModule : mHwModules) {
4571 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4572 for (const auto &outProfile : outputProfiles) {
4573 struct audio_port audioPort;
4574 outProfile->toAudioPort(&audioPort);
4575 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4576 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4577 return true;
4578 }
4579 }
4580 }
4581 }
4582 return false;
4583}
4584
Eric Laurent8340e672019-11-06 11:01:08 -08004585bool AudioPolicyManager::isCallScreenModeSupported()
4586{
4587 return getConfig().isCallScreenModeSupported();
4588}
4589
4590
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004591status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004592{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004593 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
François Gaffieafd4cea2019-11-18 15:50:22 +01004594 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4595 if (swOutput != 0) {
4596 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004597 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004598 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004599 }
jiabinbce0c1d2020-10-05 11:20:18 -07004600 if (releaseOutput(sourceDesc->portId())) {
4601 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4602 // no need to release audio patch here but just return NO_ERROR.
4603 return NO_ERROR;
4604 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004605 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004606 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004607 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004608 // close Hwoutput and remove from mHwOutputs
4609 } else {
4610 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4611 }
4612 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004613 return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
Eric Laurentd60560a2015-04-10 11:31:20 -07004614}
4615
François Gaffiec005e562018-11-06 15:04:49 +01004616sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4617 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004618{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004619 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004620 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004621 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004622 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004623 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4624 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004625 source = sourceDesc;
4626 break;
4627 }
4628 }
4629 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004630}
4631
Eric Laurente552edb2014-03-10 17:42:56 -07004632// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004633// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004634// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004635uint32_t AudioPolicyManager::nextAudioPortGeneration()
4636{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004637 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004638}
4639
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004640static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004641 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4642 !audioPolicyXmlConfigFile.empty()) {
4643 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4644 if (ret == NO_ERROR) {
4645 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004646 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004647 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004648 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004649 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004650}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004651
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004652AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4653 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004654 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004655 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004656 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004657 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004658 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004659 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004660 mAudioPortGeneration(1),
4661 mBeaconMuteRefCount(0),
4662 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004663 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004664 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004665 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004666 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004667{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004668}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004669
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004670AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4671 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4672{
4673 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004674}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004675
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004676void AudioPolicyManager::loadConfig() {
4677 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004678 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004679 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004680 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004681}
4682
4683status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004684 {
4685 auto engLib = EngineLibrary::load(
4686 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4687 if (!engLib) {
4688 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4689 return NO_INIT;
4690 }
4691 mEngine = engLib->createEngine();
4692 if (mEngine == nullptr) {
4693 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4694 return NO_INIT;
4695 }
François Gaffie2110e042015-03-24 08:41:51 +01004696 }
4697 mEngine->setObserver(this);
4698 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004699 if (status != NO_ERROR) {
4700 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4701 return status;
4702 }
François Gaffie2110e042015-03-24 08:41:51 +01004703
Eric Laurent1d69c872021-01-11 18:53:01 +01004704 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4705 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4706
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004707 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004708 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004709 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004710
Eric Laurent3a4311c2014-03-17 12:00:47 -07004711 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004712 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4713 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4714 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004715 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004716 }
jiabin9ff780e2018-03-19 18:19:52 -07004717 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004718 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004719 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004720 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004721 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004722 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004723 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004724 }
4725 }
4726 }
Eric Laurente552edb2014-03-10 17:42:56 -07004727
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004728 if (mPrimaryOutput == 0) {
4729 ALOGE("Failed to open primary output");
4730 status = NO_INIT;
4731 }
Eric Laurente552edb2014-03-10 17:42:56 -07004732
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004733 // Silence ALOGV statements
4734 property_set("log.tag." LOG_TAG, "D");
4735
Eric Laurente552edb2014-03-10 17:42:56 -07004736 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004737 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004738}
4739
Eric Laurente0720872014-03-11 09:30:41 -07004740AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004741{
Eric Laurente552edb2014-03-10 17:42:56 -07004742 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004743 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004744 }
4745 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004746 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004747 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004748 mAvailableOutputDevices.clear();
4749 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004750 mOutputs.clear();
4751 mInputs.clear();
4752 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004753 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004754 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004755}
4756
Eric Laurente0720872014-03-11 09:30:41 -07004757status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004758{
Eric Laurent87ffa392015-05-22 10:32:38 -07004759 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004760}
4761
Eric Laurente552edb2014-03-10 17:42:56 -07004762// ---
4763
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004764void AudioPolicyManager::onNewAudioModulesAvailable()
4765{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004766 DeviceVector newDevices;
4767 onNewAudioModulesAvailableInt(&newDevices);
4768 if (!newDevices.empty()) {
4769 nextAudioPortGeneration();
4770 mpClientInterface->onAudioPortListUpdate();
4771 }
4772}
4773
4774void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4775{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004776 for (const auto& hwModule : mHwModulesAll) {
4777 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4778 continue;
4779 }
4780 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4781 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4782 ALOGW("could not open HW module %s", hwModule->getName());
4783 continue;
4784 }
4785 mHwModules.push_back(hwModule);
4786 // open all output streams needed to access attached devices
4787 // except for direct output streams that are only opened when they are actually
4788 // required by an app.
4789 // This also validates mAvailableOutputDevices list
4790 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4791 if (!outProfile->canOpenNewIo()) {
4792 ALOGE("Invalid Output profile max open count %u for profile %s",
4793 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4794 continue;
4795 }
4796 if (!outProfile->hasSupportedDevices()) {
4797 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4798 continue;
4799 }
4800 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4801 mTtsOutputAvailable = true;
4802 }
4803
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004804 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4805 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4806 sp<DeviceDescriptor> supportedDevice = 0;
4807 if (supportedDevices.contains(mDefaultOutputDevice)) {
4808 supportedDevice = mDefaultOutputDevice;
4809 } else {
4810 // choose first device present in profile's SupportedDevices also part of
4811 // mAvailableOutputDevices.
4812 if (availProfileDevices.isEmpty()) {
4813 continue;
4814 }
4815 supportedDevice = availProfileDevices.itemAt(0);
4816 }
4817 if (!mOutputDevicesAll.contains(supportedDevice)) {
4818 continue;
4819 }
4820 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4821 mpClientInterface);
4822 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4823 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4824 AUDIO_STREAM_DEFAULT,
4825 AUDIO_OUTPUT_FLAG_NONE, &output);
4826 if (status != NO_ERROR) {
4827 ALOGW("Cannot open output stream for devices %s on hw module %s",
4828 supportedDevice->toString().c_str(), hwModule->getName());
4829 continue;
4830 }
4831 for (const auto &device : availProfileDevices) {
4832 // give a valid ID to an attached device once confirmed it is reachable
4833 if (!device->isAttached()) {
4834 device->attach(hwModule);
4835 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004836 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004837 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004838 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4839 }
4840 }
4841 if (mPrimaryOutput == 0 &&
4842 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4843 mPrimaryOutput = outputDesc;
4844 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004845 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4846 outputDesc->close();
4847 } else {
4848 addOutput(output, outputDesc);
4849 setOutputDevices(outputDesc,
4850 DeviceVector(supportedDevice),
4851 true,
4852 0,
4853 NULL);
4854 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004855 }
4856 // open input streams needed to access attached devices to validate
4857 // mAvailableInputDevices list
4858 for (const auto& inProfile : hwModule->getInputProfiles()) {
4859 if (!inProfile->canOpenNewIo()) {
4860 ALOGE("Invalid Input profile max open count %u for profile %s",
4861 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4862 continue;
4863 }
4864 if (!inProfile->hasSupportedDevices()) {
4865 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4866 continue;
4867 }
4868 // chose first device present in profile's SupportedDevices also part of
4869 // available input devices
4870 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4871 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4872 if (availProfileDevices.isEmpty()) {
4873 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4874 continue;
4875 }
4876 sp<AudioInputDescriptor> inputDesc =
4877 new AudioInputDescriptor(inProfile, mpClientInterface);
4878
4879 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4880 status_t status = inputDesc->open(nullptr,
4881 availProfileDevices.itemAt(0),
4882 AUDIO_SOURCE_MIC,
4883 AUDIO_INPUT_FLAG_NONE,
4884 &input);
4885 if (status != NO_ERROR) {
4886 ALOGW("Cannot open input stream for device %s on hw module %s",
4887 availProfileDevices.toString().c_str(),
4888 hwModule->getName());
4889 continue;
4890 }
4891 for (const auto &device : availProfileDevices) {
4892 // give a valid ID to an attached device once confirmed it is reachable
4893 if (!device->isAttached()) {
4894 device->attach(hwModule);
4895 device->importAudioPortAndPickAudioProfile(inProfile, true);
4896 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004897 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004898 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4899 }
4900 }
4901 inputDesc->close();
4902 }
4903 }
4904}
4905
Eric Laurent98e38192018-02-15 18:31:53 -08004906void AudioPolicyManager::addOutput(audio_io_handle_t output,
4907 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004908{
Eric Laurent1c333e22014-05-20 10:48:17 -07004909 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07004910 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004911 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004912 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004914}
4915
François Gaffie53615e22015-03-19 09:24:12 +01004916void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4917{
4918 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004919 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004920}
4921
Eric Laurent98e38192018-02-15 18:31:53 -08004922void AudioPolicyManager::addInput(audio_io_handle_t input,
4923 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004924{
Eric Laurent1c333e22014-05-20 10:48:17 -07004925 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004927}
Eric Laurente552edb2014-03-10 17:42:56 -07004928
François Gaffie11d30102018-11-02 16:09:09 +01004929status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004930 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004931 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004932{
François Gaffie11d30102018-11-02 16:09:09 +01004933 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07004934 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004935 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004936
François Gaffie11d30102018-11-02 16:09:09 +01004937 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004938 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004939 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004940 }
Eric Laurente552edb2014-03-10 17:42:56 -07004941
Eric Laurent3b73df72014-03-11 09:06:29 -07004942 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07004943 // first call getAudioPort to get the supported attributes from the HAL
4944 struct audio_port_v7 port = {};
4945 device->toAudioPort(&port);
4946 status_t status = mpClientInterface->getAudioPort(&port);
4947 if (status == NO_ERROR) {
4948 device->importAudioPort(port);
4949 }
4950
4951 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07004952 for (size_t i = 0; i < mOutputs.size(); i++) {
4953 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004954 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07004955 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004956 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4957 mOutputs.keyAt(i), device->toString().c_str());
4958 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004959 }
4960 }
4961 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004962 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004963 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004964 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4965 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004966 if (profile->supportsDevice(device)) {
4967 profiles.add(profile);
4968 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4969 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004970 }
4971 }
4972 }
4973
Eric Laurent7b279bb2015-12-14 10:18:23 -08004974 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004975
Eric Laurente552edb2014-03-10 17:42:56 -07004976 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004977 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004978 return BAD_VALUE;
4979 }
4980
4981 // open outputs for matching profiles if needed. Direct outputs are also opened to
4982 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4983 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004984 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004985
4986 // nothing to do if one output is already opened for this profile
4987 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004988 for (j = 0; j < outputs.size(); j++) {
4989 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004990 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004991 // matching profile: save the sample rates, format and channel masks supported
4992 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004993 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07004994 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004995 }
Eric Laurente552edb2014-03-10 17:42:56 -07004996 break;
4997 }
4998 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004999 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005000 continue;
5001 }
5002
Eric Laurent3974e3b2017-12-07 17:58:43 -08005003 if (!profile->canOpenNewIo()) {
5004 ALOGW("Max Output number %u already opened for this profile %s",
5005 profile->maxOpenCount, profile->getTagName().c_str());
5006 continue;
5007 }
5008
Eric Laurent83efe1c2017-07-09 16:51:08 -07005009 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005010 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005011 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5012 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005013 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005014 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005015 profiles.removeAt(profile_index);
5016 profile_index--;
5017 } else {
5018 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005019 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005020 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005021 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5022 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005023 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005024 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005025
François Gaffie11d30102018-11-02 16:09:09 +01005026 if (device_distinguishes_on_address(deviceType)) {
5027 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5028 device->toString().c_str());
5029 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5030 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005031 }
Eric Laurente552edb2014-03-10 17:42:56 -07005032 ALOGV("checkOutputsForDevice(): adding output %d", output);
5033 }
5034 }
5035
5036 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005037 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005038 return BAD_VALUE;
5039 }
Eric Laurentd4692962014-05-05 18:13:44 -07005040 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005041 // check if one opened output is not needed any more after disconnecting one device
5042 for (size_t i = 0; i < mOutputs.size(); i++) {
5043 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005044 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005045 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005046 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005047 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005048 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005049 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005050 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5051 mOutputs.keyAt(i));
5052 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005053 }
Eric Laurente552edb2014-03-10 17:42:56 -07005054 }
5055 }
Eric Laurentd4692962014-05-05 18:13:44 -07005056 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005057 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005058 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5059 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005060 if (!profile->supportsDevice(device)) {
5061 continue;
5062 }
5063 ALOGV("checkOutputsForDevice(): "
5064 "clearing direct output profile %zu on module %s",
5065 j, hwModule->getName());
5066 profile->clearAudioProfiles();
5067 if (!profile->hasDynamicAudioProfile()) {
5068 continue;
5069 }
5070 // When a device is disconnected, if there is an IOProfile that contains dynamic
5071 // profiles and supports the disconnected device, call getAudioPort to repopulate
5072 // the capabilities of the devices that is supported by the IOProfile.
5073 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5074 if (supportedDevice == device ||
5075 !mAvailableOutputDevices.contains(supportedDevice)) {
5076 continue;
5077 }
5078 struct audio_port_v7 port;
5079 supportedDevice->toAudioPort(&port);
5080 status_t status = mpClientInterface->getAudioPort(&port);
5081 if (status == NO_ERROR) {
5082 supportedDevice->importAudioPort(port);
5083 }
Eric Laurente552edb2014-03-10 17:42:56 -07005084 }
5085 }
5086 }
5087 }
5088 return NO_ERROR;
5089}
5090
François Gaffie11d30102018-11-02 16:09:09 +01005091status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005092 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005093{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005094 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005095
François Gaffie11d30102018-11-02 16:09:09 +01005096 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005097 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005098 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005099 }
5100
Eric Laurentd4692962014-05-05 18:13:44 -07005101 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005102 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005103 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005104 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005105 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005106 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005107 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005108 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005109
François Gaffie11d30102018-11-02 16:09:09 +01005110 if (profile->supportsDevice(device)) {
5111 profiles.add(profile);
5112 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5113 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005114 }
5115 }
5116 }
5117
Eric Laurent0dd51852019-04-19 18:18:58 -07005118 if (profiles.isEmpty()) {
5119 ALOGW("%s: No input profile available for device %s",
5120 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005121 return BAD_VALUE;
5122 }
5123
5124 // open inputs for matching profiles if needed. Direct inputs are also opened to
5125 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5126 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5127
Eric Laurent1c333e22014-05-20 10:48:17 -07005128 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005129
Eric Laurentd4692962014-05-05 18:13:44 -07005130 // nothing to do if one input is already opened for this profile
5131 size_t input_index;
5132 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5133 desc = mInputs.valueAt(input_index);
5134 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005135 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005136 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005137 }
Eric Laurentd4692962014-05-05 18:13:44 -07005138 break;
5139 }
5140 }
5141 if (input_index != mInputs.size()) {
5142 continue;
5143 }
5144
Eric Laurent3974e3b2017-12-07 17:58:43 -08005145 if (!profile->canOpenNewIo()) {
5146 ALOGW("Max Input number %u already opened for this profile %s",
5147 profile->maxOpenCount, profile->getTagName().c_str());
5148 continue;
5149 }
5150
Eric Laurentfe231122017-11-17 17:48:06 -08005151 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005152 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005153 status_t status = desc->open(nullptr,
5154 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005155 AUDIO_SOURCE_MIC,
5156 AUDIO_INPUT_FLAG_NONE,
5157 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005158
Eric Laurentcf2c0212014-07-25 16:20:43 -07005159 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005160 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005161 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005162 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005163 mpClientInterface->setParameters(input, String8(param));
5164 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005165 }
François Gaffie11d30102018-11-02 16:09:09 +01005166 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005167 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005168 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005169 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005170 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005171 }
5172
Eric Laurent0dd51852019-04-19 18:18:58 -07005173 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005174 addInput(input, desc);
5175 }
5176 } // endif input != 0
5177
Eric Laurentcf2c0212014-07-25 16:20:43 -07005178 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005179 ALOGW("%s could not open input for device %s", __func__,
5180 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005181 profiles.removeAt(profile_index);
5182 profile_index--;
5183 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005184 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005185 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005186 }
Eric Laurentd4692962014-05-05 18:13:44 -07005187 ALOGV("checkInputsForDevice(): adding input %d", input);
5188 }
5189 } // end scan profiles
5190
5191 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005192 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005193 return BAD_VALUE;
5194 }
5195 } else {
5196 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005197 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005198 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005199 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005200 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005201 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005202 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005203 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005204 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5205 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005206 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005207 }
5208 }
5209 }
5210 } // end disconnect
5211
5212 return NO_ERROR;
5213}
5214
5215
Eric Laurente0720872014-03-11 09:30:41 -07005216void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005217{
5218 ALOGV("closeOutput(%d)", output);
5219
François Gaffie1c878552018-11-22 16:53:21 +01005220 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5221 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005222 ALOGW("closeOutput() unknown output %d", output);
5223 return;
5224 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005225 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005226 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005227
Eric Laurente552edb2014-03-10 17:42:56 -07005228 // look for duplicated outputs connected to the output being removed.
5229 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005230 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5231 if (dupOutput->isDuplicated() &&
5232 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5233 sp<SwAudioOutputDescriptor> remainingOutput =
5234 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005235 // As all active tracks on duplicated output will be deleted,
5236 // and as they were also referenced on the other output, the reference
5237 // count for their stream type must be adjusted accordingly on
5238 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005239 const bool wasActive = remainingOutput->isActive();
5240 // Note: no-op on the closing output where all clients has already been set inactive
5241 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005242 // stop() will be a no op if the output is still active but is needed in case all
5243 // active streams refcounts where cleared above
5244 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005245 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005246 }
Eric Laurente552edb2014-03-10 17:42:56 -07005247 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5248 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5249
5250 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005251 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005252 }
5253 }
5254
Eric Laurent05b90f82014-08-27 15:32:29 -07005255 nextAudioPortGeneration();
5256
François Gaffie1c878552018-11-22 16:53:21 +01005257 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005258 if (index >= 0) {
5259 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005260 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5261 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005262 mAudioPatches.removeItemsAt(index);
5263 mpClientInterface->onAudioPatchListUpdate();
5264 }
5265
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005266 if (closingOutputWasActive) {
5267 closingOutput->stop();
5268 }
François Gaffie1c878552018-11-22 16:53:21 +01005269 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005270
François Gaffie53615e22015-03-19 09:24:12 +01005271 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005272 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005273
5274 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5275 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005276 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005277 bool directOutputOpen = false;
5278 for (size_t i = 0; i < mOutputs.size(); i++) {
5279 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5280 directOutputOpen = true;
5281 break;
5282 }
5283 }
5284 if (!directOutputOpen) {
5285 ALOGV("no direct outputs open, reset MSD patch");
5286 setMsdPatch();
5287 }
5288 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005289}
5290
5291void AudioPolicyManager::closeInput(audio_io_handle_t input)
5292{
5293 ALOGV("closeInput(%d)", input);
5294
5295 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5296 if (inputDesc == NULL) {
5297 ALOGW("closeInput() unknown input %d", input);
5298 return;
5299 }
5300
Eric Laurent6a94d692014-05-20 11:18:06 -07005301 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005302
François Gaffie11d30102018-11-02 16:09:09 +01005303 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005304 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005305 if (index >= 0) {
5306 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005307 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5308 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005309 mAudioPatches.removeItemsAt(index);
5310 mpClientInterface->onAudioPatchListUpdate();
5311 }
5312
Eric Laurentfe231122017-11-17 17:48:06 -08005313 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005314 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005315
François Gaffie11d30102018-11-02 16:09:09 +01005316 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5317 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005318 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005319 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005320 }
Eric Laurente552edb2014-03-10 17:42:56 -07005321}
5322
François Gaffie11d30102018-11-02 16:09:09 +01005323SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5324 const DeviceVector &devices,
5325 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005326{
5327 SortedVector<audio_io_handle_t> outputs;
5328
François Gaffie11d30102018-11-02 16:09:09 +01005329 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005330 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005331 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005332 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005333 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005334 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005335 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005336 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005337 outputs.add(openOutputs.keyAt(i));
5338 }
5339 }
5340 return outputs;
5341}
5342
Mikhail Naganov37977152018-07-11 15:54:44 -07005343void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5344{
5345 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5346 // output is suspended before any tracks are moved to it
5347 checkA2dpSuspend();
5348 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005349 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005350 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005351 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005352 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005353 setMsdPatch();
5354 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005355 // an event that changed routing likely occurred, inform upper layers
5356 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005357}
5358
François Gaffiec005e562018-11-06 15:04:49 +01005359bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5360 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005361{
François Gaffiec005e562018-11-06 15:04:49 +01005362 return mEngine->getProductStrategyForAttributes(lAttr) ==
5363 mEngine->getProductStrategyForAttributes(rAttr);
5364}
5365
Francois Gaffieff1eb522020-05-06 18:37:04 +02005366void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5367{
5368 for (size_t i = 0; i < mAudioSources.size(); i++) {
5369 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5370 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
5371 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE) {
5372 connectAudioSource(sourceDesc);
5373 }
5374 }
5375}
5376
5377void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5378{
5379 for (size_t i = 0; i < mAudioSources.size(); i++) {
5380 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5381 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5382 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5383 disconnectAudioSource(sourceDesc);
5384 }
5385 }
5386}
5387
François Gaffiec005e562018-11-06 15:04:49 +01005388void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5389{
5390 auto psId = mEngine->getProductStrategyForAttributes(attr);
5391
5392 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5393 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005394
François Gaffie11d30102018-11-02 16:09:09 +01005395 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5396 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005397
Eric Laurentc209fe42020-06-05 18:11:23 -07005398 uint32_t maxLatency = 0;
5399 bool invalidate = false;
5400 // take into account dynamic audio policies related changes: if a client is now associated
5401 // to a different policy mix than at creation time, invalidate corresponding stream
5402 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5403 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5404 if (desc->isDuplicated()) {
5405 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005406 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005407 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5408 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5409 continue;
5410 }
5411 sp<AudioPolicyMix> primaryMix;
5412 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5413 client->flags(), primaryMix, nullptr);
5414 if (status != OK) {
5415 continue;
5416 }
yucliuf4de36d2020-09-14 14:57:56 -07005417 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005418 invalidate = true;
5419 if (desc->isStrategyActive(psId)) {
5420 maxLatency = desc->latency();
5421 }
5422 break;
5423 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005424 }
5425 }
5426
Eric Laurentc209fe42020-06-05 18:11:23 -07005427 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005428 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5429 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005430 for (audio_io_handle_t srcOut : srcOutputs) {
5431 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005432 if (desc == nullptr) continue;
5433
5434 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005435 maxLatency = desc->latency();
5436 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005437
5438 if (invalidate) continue;
5439
5440 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005441 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005442 // a client on a non direct outputs has necessarily a linear PCM format
5443 // so we can call selectOutput() safely
5444 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5445 client->flags(),
5446 client->config().format,
5447 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005448 client->config().sample_rate,
5449 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005450 if (newOutput != srcOut) {
5451 invalidate = true;
5452 break;
5453 }
5454 } else {
5455 sp<IOProfile> profile = getProfileForOutput(newDevices,
5456 client->config().sample_rate,
5457 client->config().format,
5458 client->config().channel_mask,
5459 client->flags(),
5460 true /* directOnly */);
5461 if (profile != desc->mProfile) {
5462 invalidate = true;
5463 break;
5464 }
5465 }
5466 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005467 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005468
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005469 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005470 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005471 std::to_string(srcOutputs[0]).c_str(),
5472 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005473 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005474 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005475 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005476 if (desc == nullptr) continue;
5477
5478 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005479 setStrategyMute(psId, true, desc);
5480 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005481 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005482 }
François Gaffiec005e562018-11-06 15:04:49 +01005483 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005484 if (source != nullptr) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005485 connectAudioSource(source);
5486 }
Eric Laurente552edb2014-03-10 17:42:56 -07005487 }
5488
François Gaffiec005e562018-11-06 15:04:49 +01005489 // Move effects associated to this stream from previous output to new output
5490 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005491 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005492 }
François Gaffiec005e562018-11-06 15:04:49 +01005493 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005494 if (invalidate) {
5495 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5496 mpClientInterface->invalidateStream(stream);
5497 }
Eric Laurente552edb2014-03-10 17:42:56 -07005498 }
5499 }
5500}
5501
Eric Laurente0720872014-03-11 09:30:41 -07005502void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005503{
François Gaffiec005e562018-11-06 15:04:49 +01005504 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5505 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5506 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005507 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005508 }
Eric Laurente552edb2014-03-10 17:42:56 -07005509}
5510
Kevin Rocard153f92d2018-12-18 18:33:28 -08005511void AudioPolicyManager::checkSecondaryOutputs() {
5512 std::set<audio_stream_type_t> streamsToInvalidate;
5513 for (size_t i = 0; i < mOutputs.size(); i++) {
5514 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5515 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005516 sp<AudioPolicyMix> primaryMix;
5517 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005518 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005519 client->flags(), primaryMix, &secondaryMixes);
5520 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5521 for (auto &secondaryMix : secondaryMixes) {
5522 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5523 if (outputDesc != nullptr &&
5524 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5525 secondaryDescs.push_back(outputDesc);
5526 }
5527 }
5528
Kevin Rocard94114a22019-04-01 19:38:23 -07005529 if (status != OK ||
5530 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005531 client->getSecondaryOutputs().end(),
5532 secondaryDescs.begin(), secondaryDescs.end())) {
5533 streamsToInvalidate.insert(client->stream());
5534 }
5535 }
5536 }
5537 for (audio_stream_type_t stream : streamsToInvalidate) {
5538 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5539 mpClientInterface->invalidateStream(stream);
5540 }
5541}
5542
Eric Laurent2517af32020-11-25 15:31:27 +01005543bool AudioPolicyManager::isScoRequestedForComm() const {
5544 AudioDeviceTypeAddrVector devices;
5545 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5546 for (const auto &device : devices) {
5547 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5548 return true;
5549 }
5550 }
5551 return false;
5552}
5553
Eric Laurente0720872014-03-11 09:30:41 -07005554void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005555{
François Gaffie53615e22015-03-19 09:24:12 +01005556 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005557 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005558 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005559 return;
5560 }
5561
Eric Laurent3a4311c2014-03-17 12:00:47 -07005562 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005563 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5564 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005565 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005566
5567 // if suspended, restore A2DP output if:
5568 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005569 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005570 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005571 //
Eric Laurentf732e072016-08-03 19:30:28 -07005572 // if not suspended, suspend A2DP output if:
5573 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005574 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005575 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005576 //
5577 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005578 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005579 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005580 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005581 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005582
5583 mpClientInterface->restoreOutput(a2dpOutput);
5584 mA2dpSuspended = false;
5585 }
5586 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005587 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005588 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005589 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005590 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005591
5592 mpClientInterface->suspendOutput(a2dpOutput);
5593 mA2dpSuspended = true;
5594 }
5595 }
5596}
5597
François Gaffie11d30102018-11-02 16:09:09 +01005598DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5599 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005600{
François Gaffie11d30102018-11-02 16:09:09 +01005601 DeviceVector devices;
5602
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005603 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005604 if (index >= 0) {
5605 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005606 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005607 ALOGV("%s device %s forced by patch %d", __func__,
5608 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5609 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005610 }
5611 }
5612
Dean Wheatley514b4312020-06-17 21:45:00 +10005613 // Do not retrieve engine device for outputs through MSD
5614 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5615 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5616 return outputDesc->devices();
5617 }
5618
Eric Laurent97ac8712018-07-27 18:59:02 -07005619 // Honor explicit routing requests only if no client using default routing is active on this
5620 // input: a specific app can not force routing for other apps by setting a preferred device.
5621 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005622 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005623 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005624 if (device != nullptr) {
5625 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005626 }
5627
François Gaffiea807ef92018-11-05 10:44:33 +01005628 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5629 // of setForceUse / Default Bus device here
5630 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5631 if (device != nullptr) {
5632 return DeviceVector(device);
5633 }
5634
François Gaffiec005e562018-11-06 15:04:49 +01005635 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5636 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5637 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005638
François Gaffiec005e562018-11-06 15:04:49 +01005639 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005640 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5641 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005642 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005643 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5644 outputDesc->isStrategyActive(productStrategy)) {
5645 // Retrieval of devices for voice DL is done on primary output profile, cannot
5646 // check the route (would force modifying configuration file for this profile)
5647 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5648 break;
5649 }
Eric Laurente552edb2014-03-10 17:42:56 -07005650 }
François Gaffiec005e562018-11-06 15:04:49 +01005651 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005652 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005653}
5654
François Gaffie11d30102018-11-02 16:09:09 +01005655sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5656 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005657{
François Gaffie11d30102018-11-02 16:09:09 +01005658 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005659
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005660 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005661 if (index >= 0) {
5662 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005663 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005664 ALOGV("getNewInputDevice() device %s forced by patch %d",
5665 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5666 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005667 }
5668 }
5669
Eric Laurent97ac8712018-07-27 18:59:02 -07005670 // Honor explicit routing requests only if no client using default routing is active on this
5671 // input: a specific app can not force routing for other apps by setting a preferred device.
5672 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005673 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5674 if (device != nullptr) {
5675 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005676 }
5677
Eric Laurentdc95a252018-04-12 12:46:56 -07005678 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005679 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005680 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5681 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5682 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005683 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005684 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005685 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005686 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005687
Eric Laurente552edb2014-03-10 17:42:56 -07005688 return device;
5689}
5690
Eric Laurent794fde22016-03-11 09:50:45 -08005691bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5692 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005693 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005694}
5695
Eric Laurente0720872014-03-11 09:30:41 -07005696audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005697 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005698 // getOutputDevicesForStream's behavior for invalid streams.
5699 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5700 // device for music stream), but we want to return the empty set.
5701 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005702 return AUDIO_DEVICE_NONE;
5703 }
François Gaffie11d30102018-11-02 16:09:09 +01005704 DeviceVector activeDevices;
5705 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005706 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5707 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005708 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005709 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005710 }
François Gaffiec005e562018-11-06 15:04:49 +01005711 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005712 devices.merge(curDevices);
5713 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005714 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005715 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005716 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005717 }
5718 }
Eric Laurente552edb2014-03-10 17:42:56 -07005719 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005720
Eric Laurentb0688d62018-08-14 15:49:18 -07005721 // Favor devices selected on active streams if any to report correct device in case of
5722 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005723 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005724 devices = activeDevices;
5725 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005726 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5727 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005728 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005729 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005730 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005731 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005732 }
jiabin9a3361e2019-10-01 09:38:30 -07005733 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5734 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005735}
5736
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005737status_t AudioPolicyManager::getDevicesForAttributes(
5738 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5739 if (devices == nullptr) {
5740 return BAD_VALUE;
5741 }
5742 // check dynamic policies but only for primary descriptors (secondary not used for audible
5743 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005744 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005745 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005746 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005747 if (status != OK) {
5748 return status;
5749 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005750 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5751 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5752 devices->push_back(device);
5753 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005754 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005755 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5756 for (const auto& device : curDevices) {
5757 devices->push_back(device->getDeviceTypeAddr());
5758 }
5759 return NO_ERROR;
5760}
5761
Eric Laurente0720872014-03-11 09:30:41 -07005762void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005763 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005764 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005765 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005766 updateDevicesAndOutputs();
5767 break;
5768 default:
5769 break;
5770 }
5771}
5772
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005773uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005774
5775 // skip beacon mute management if a dedicated TTS output is available
5776 if (mTtsOutputAvailable) {
5777 return 0;
5778 }
5779
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005780 switch(event) {
5781 case STARTING_OUTPUT:
5782 mBeaconMuteRefCount++;
5783 break;
5784 case STOPPING_OUTPUT:
5785 if (mBeaconMuteRefCount > 0) {
5786 mBeaconMuteRefCount--;
5787 }
5788 break;
5789 case STARTING_BEACON:
5790 mBeaconPlayingRefCount++;
5791 break;
5792 case STOPPING_BEACON:
5793 if (mBeaconPlayingRefCount > 0) {
5794 mBeaconPlayingRefCount--;
5795 }
5796 break;
5797 }
5798
5799 if (mBeaconMuteRefCount > 0) {
5800 // any playback causes beacon to be muted
5801 return setBeaconMute(true);
5802 } else {
5803 // no other playback: unmute when beacon starts playing, mute when it stops
5804 return setBeaconMute(mBeaconPlayingRefCount == 0);
5805 }
5806}
5807
5808uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5809 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5810 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5811 // keep track of muted state to avoid repeating mute/unmute operations
5812 if (mBeaconMuted != mute) {
5813 // mute/unmute AUDIO_STREAM_TTS on all outputs
5814 ALOGV("\t muting %d", mute);
5815 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005816 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005817 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005818 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005819 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005820 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005821 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005822 maxLatency = latency;
5823 }
5824 }
5825 mBeaconMuted = mute;
5826 return maxLatency;
5827 }
5828 return 0;
5829}
5830
Eric Laurente0720872014-03-11 09:30:41 -07005831void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005832{
François Gaffiec005e562018-11-06 15:04:49 +01005833 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005834 mPreviousOutputs = mOutputs;
5835}
5836
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005837uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005838 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005839 uint32_t delayMs)
5840{
5841 // mute/unmute strategies using an incompatible device combination
5842 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5843 // if unmuting, unmute only after the specified delay
5844 if (outputDesc->isDuplicated()) {
5845 return 0;
5846 }
5847
5848 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005849 DeviceVector devices = outputDesc->devices();
5850 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005851
François Gaffiec005e562018-11-06 15:04:49 +01005852 auto productStrategies = mEngine->getOrderedProductStrategies();
5853 for (const auto &productStrategy : productStrategies) {
5854 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5855 DeviceVector curDevices =
5856 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5857 curDevices = curDevices.filter(outputDesc->supportedDevices());
5858 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005859 bool doMute = false;
5860
François Gaffiec005e562018-11-06 15:04:49 +01005861 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005862 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005863 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5864 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005865 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005866 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005867 }
Eric Laurent99401132014-05-07 19:48:15 -07005868 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005869 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005870 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005871 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005872 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005873 continue;
5874 }
François Gaffiec005e562018-11-06 15:04:49 +01005875 ALOGVV("%s() %s (curDevice %s)", __func__,
5876 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5877 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5878 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005879 if (mute) {
5880 // FIXME: should not need to double latency if volume could be applied
5881 // immediately by the audioflinger mixer. We must account for the delay
5882 // between now and the next time the audioflinger thread for this output
5883 // will process a buffer (which corresponds to one buffer size,
5884 // usually 1/2 or 1/4 of the latency).
5885 if (muteWaitMs < desc->latency() * 2) {
5886 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005887 }
5888 }
5889 }
5890 }
5891 }
5892 }
5893
Eric Laurent99401132014-05-07 19:48:15 -07005894 // temporary mute output if device selection changes to avoid volume bursts due to
5895 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005896 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005897 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5898 // temporary mute duration is conservatively set to 4 times the reported latency
5899 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5900 if (muteWaitMs < tempMuteWaitMs) {
5901 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005902 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005903 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5904 // make sure that we do not start the temporary mute period too early in case of
5905 // delayed device change
5906 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5907 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005908 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005909 }
5910 }
5911
Eric Laurente552edb2014-03-10 17:42:56 -07005912 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5913 if (muteWaitMs > delayMs) {
5914 muteWaitMs -= delayMs;
5915 usleep(muteWaitMs * 1000);
5916 return muteWaitMs;
5917 }
5918 return 0;
5919}
5920
François Gaffie11d30102018-11-02 16:09:09 +01005921uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5922 const DeviceVector &devices,
5923 bool force,
5924 int delayMs,
5925 audio_patch_handle_t *patchHandle,
5926 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005927{
François Gaffie11d30102018-11-02 16:09:09 +01005928 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005929 uint32_t muteWaitMs;
5930
5931 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005932 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5933 nullptr /* patchHandle */, requiresMuteCheck);
5934 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5935 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005936 return muteWaitMs;
5937 }
Eric Laurente552edb2014-03-10 17:42:56 -07005938
5939 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005940 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005941 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005942
François Gaffie11d30102018-11-02 16:09:09 +01005943 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5944
5945 if (!filteredDevices.isEmpty()) {
5946 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005947 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005948
5949 // if the outputs are not materially active, there is no need to mute.
5950 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005951 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005952 } else {
5953 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5954 muteWaitMs = 0;
5955 }
Eric Laurente552edb2014-03-10 17:42:56 -07005956
Eric Laurent79ea9582020-06-11 18:49:24 -07005957 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5958 // output profile or if new device is not supported AND previous device(s) is(are) still
5959 // available (otherwise reset device must be done on the output)
5960 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5961 !mAvailableOutputDevices.filter(prevDevices).empty()) {
5962 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5963 // restore previous device after evaluating strategy mute state
5964 outputDesc->setDevices(prevDevices);
5965 return muteWaitMs;
5966 }
5967
Eric Laurente552edb2014-03-10 17:42:56 -07005968 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005969 // the requested device is AUDIO_DEVICE_NONE
5970 // OR the requested device is the same as current device
5971 // AND force is not specified
5972 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005973 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005974 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005975 !force && outputDesc->getPatchHandle() != 0) {
5976 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5977 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005978 return muteWaitMs;
5979 }
5980
François Gaffie11d30102018-11-02 16:09:09 +01005981 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005982
Eric Laurente552edb2014-03-10 17:42:56 -07005983 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005984 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005985 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005986 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005987 PatchBuilder patchBuilder;
5988 patchBuilder.addSource(outputDesc);
5989 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5990 for (const auto &filteredDevice : filteredDevices) {
5991 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005992 }
5993
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08005994 // Add half reported latency to delayMs when muteWaitMs is null in order
5995 // to avoid disordered sequence of muting volume and changing devices.
5996 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
5997 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005998 }
Eric Laurente552edb2014-03-10 17:42:56 -07005999
6000 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006001 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006002
6003 return muteWaitMs;
6004}
6005
Eric Laurentc75307b2015-03-17 15:29:32 -07006006status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006007 int delayMs,
6008 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006009{
Eric Laurent6a94d692014-05-20 11:18:06 -07006010 ssize_t index;
6011 if (patchHandle) {
6012 index = mAudioPatches.indexOfKey(*patchHandle);
6013 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006014 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006015 }
6016 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006017 return INVALID_OPERATION;
6018 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006019 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006020 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006021 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006022 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006023 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006024 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006025 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006026 return status;
6027}
6028
6029status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006030 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006031 bool force,
6032 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006033{
6034 status_t status = NO_ERROR;
6035
Eric Laurent1f2f2232014-06-02 12:01:23 -07006036 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006037 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6038 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006039
François Gaffie11d30102018-11-02 16:09:09 +01006040 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006041 PatchBuilder patchBuilder;
6042 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006043 // AUDIO_SOURCE_HOTWORD is for internal use only:
6044 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006045 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6046 auto result = usecase;
6047 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6048 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6049 }
6050 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006051 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006052 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006053 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006054 }
6055 }
6056 return status;
6057}
6058
Eric Laurent6a94d692014-05-20 11:18:06 -07006059status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6060 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006061{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006062 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006063 ssize_t index;
6064 if (patchHandle) {
6065 index = mAudioPatches.indexOfKey(*patchHandle);
6066 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006067 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006068 }
6069 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006070 return INVALID_OPERATION;
6071 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006072 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006073 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006074 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006075 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006076 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006077 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006078 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006079 return status;
6080}
6081
François Gaffie11d30102018-11-02 16:09:09 +01006082sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006083 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006084 audio_format_t& format,
6085 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006086 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006087{
6088 // Choose an input profile based on the requested capture parameters: select the first available
6089 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006090 //
6091 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6092 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006093
Glenn Kasten730b9262018-03-29 15:01:26 -07006094 sp<IOProfile> firstInexact;
6095 uint32_t updatedSamplingRate = 0;
6096 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6097 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006098 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006099 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006100 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006101 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006102 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006103 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006104 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006105 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006106 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006107 &channelMask /*updatedChannelMask*/,
6108 // FIXME ugly cast
6109 (audio_output_flags_t) flags,
6110 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006111 return profile;
6112 }
François Gaffie11d30102018-11-02 16:09:09 +01006113 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006114 samplingRate,
6115 &updatedSamplingRate,
6116 format,
6117 &updatedFormat,
6118 channelMask,
6119 &updatedChannelMask,
6120 // FIXME ugly cast
6121 (audio_output_flags_t) flags,
6122 false /*exactMatchRequiredForInputFlags*/)) {
6123 firstInexact = profile;
6124 }
6125
Eric Laurente552edb2014-03-10 17:42:56 -07006126 }
6127 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006128 if (firstInexact != nullptr) {
6129 samplingRate = updatedSamplingRate;
6130 format = updatedFormat;
6131 channelMask = updatedChannelMask;
6132 return firstInexact;
6133 }
Eric Laurente552edb2014-03-10 17:42:56 -07006134 return NULL;
6135}
6136
François Gaffieaaac0fd2018-11-22 17:56:39 +01006137float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6138 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006139 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006140 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006141{
jiabin9a3361e2019-10-01 09:38:30 -07006142 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006143
6144 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6145 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6146 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6147 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006148 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6149 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6150 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6151 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006152 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006153
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006154 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006155 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6156 mOutputs.isActive(ringVolumeSrc, 0)) {
6157 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006158 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006159 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006160 }
6161
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006162 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006163 if ((volumeSource != callVolumeSrc && (isInCall() ||
6164 mOutputs.isActiveLocally(callVolumeSrc))) &&
6165 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6166 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6167 volumeSource == alarmVolumeSrc ||
6168 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6169 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6170 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006171 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006172 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006173 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006174 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006175 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006176 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006177 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6178 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6179 // programmatically muted.
6180 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6181 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6182 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006183 bool exemptFromCapping =
6184 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6185 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006186 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6187 volumeSource, volumeDb);
6188 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006189 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6190 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6191 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006192 }
6193 }
Eric Laurente552edb2014-03-10 17:42:56 -07006194 // if a headset is connected, apply the following rules to ring tones and notifications
6195 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006196 // - always attenuate notifications volume by 6dB
6197 // - attenuate ring tones volume by 6dB unless music is not playing and
6198 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006199 // - if music is playing, always limit the volume to current music volume,
6200 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006201 if (!Intersection(deviceTypes,
6202 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6203 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006204 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6205 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006206 ((volumeSource == alarmVolumeSrc ||
6207 volumeSource == ringVolumeSrc) ||
6208 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6209 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6210 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6211 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6212 curves.canBeMuted()) {
6213
Eric Laurente552edb2014-03-10 17:42:56 -07006214 // when the phone is ringing we must consider that music could have been paused just before
6215 // by the music application and behave as if music was active if the last music track was
6216 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006217 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006218 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006219 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006220 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006221 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6222 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006223 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006224 float musicVolDb = computeVolume(musicCurves,
6225 musicVolumeSrc,
6226 musicCurves.getVolumeIndex(musicDevice),
6227 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006228 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6229 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6230 if (volumeDb > minVolDb) {
6231 volumeDb = minVolDb;
6232 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006233 }
jiabin9a3361e2019-10-01 09:38:30 -07006234 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6235 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006236 // on A2DP, also ensure notification volume is not too low compared to media when
6237 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006238 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006239 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006240 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6241 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006242 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6243 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006244 }
6245 }
jiabin9a3361e2019-10-01 09:38:30 -07006246 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006247 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006248 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006249 }
6250 }
6251
François Gaffie43c73442018-11-08 08:21:55 +01006252 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006253}
6254
Eric Laurent3839bc02018-07-10 18:33:34 -07006255int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006256 VolumeSource fromVolumeSource,
6257 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006258{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006259 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006260 return srcIndex;
6261 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006262 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6263 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006264 float minSrc = (float)srcCurves.getVolumeIndexMin();
6265 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6266 float minDst = (float)dstCurves.getVolumeIndexMin();
6267 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006268
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006269 // preserve mute request or correct range
6270 if (srcIndex < minSrc) {
6271 if (srcIndex == 0) {
6272 return 0;
6273 }
6274 srcIndex = minSrc;
6275 } else if (srcIndex > maxSrc) {
6276 srcIndex = maxSrc;
6277 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006278 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6279}
6280
François Gaffieaaac0fd2018-11-22 17:56:39 +01006281status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6282 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006283 int index,
6284 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006285 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006286 int delayMs,
6287 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006288{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006289 // do not change actual attributes volume if the attributes is muted
6290 if (outputDesc->isMuted(volumeSource)) {
6291 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6292 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006293 return NO_ERROR;
6294 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006295 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6296 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6297 bool isVoiceVolSrc = callVolSrc == volumeSource;
6298 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6299
Eric Laurent2517af32020-11-25 15:31:27 +01006300 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006301 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006302 // if sco and call follow same curves, bypass forceUseForComm
6303 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006304 ((isVoiceVolSrc && isScoRequested) ||
6305 (isBtScoVolSrc && !isScoRequested))) {
6306 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6307 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006308 // Do not return an error here as AudioService will always set both voice call
6309 // and bluetooth SCO volumes due to stream aliasing.
6310 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006311 }
jiabin9a3361e2019-10-01 09:38:30 -07006312 if (deviceTypes.empty()) {
6313 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006314 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006315
jiabin9a3361e2019-10-01 09:38:30 -07006316 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6317 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006318 // Force VoIP volume to max for bluetooth SCO device except if muted
6319 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006320 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006321 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006322 }
jiabin9a3361e2019-10-01 09:38:30 -07006323 outputDesc->setVolume(
6324 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006325
François Gaffieaaac0fd2018-11-22 17:56:39 +01006326 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006327 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006328 // 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 +01006329 if (isVoiceVolSrc) {
6330 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006331 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006332 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006333 }
Eric Laurent18fba842016-03-31 14:41:26 -07006334 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006335 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6336 mLastVoiceVolume = voiceVolume;
6337 }
6338 }
Eric Laurente552edb2014-03-10 17:42:56 -07006339 return NO_ERROR;
6340}
6341
Eric Laurentc75307b2015-03-17 15:29:32 -07006342void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006343 const DeviceTypeSet& deviceTypes,
6344 int delayMs,
6345 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006346{
jiabincd510522020-01-22 09:40:55 -08006347 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006348 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6349 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6350 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006351 curves.getVolumeIndex(deviceTypes),
6352 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006353 }
6354}
6355
François Gaffiec005e562018-11-06 15:04:49 +01006356void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6357 bool on,
6358 const sp<AudioOutputDescriptor>& outputDesc,
6359 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006360 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006361{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006362 std::vector<VolumeSource> sourcesToMute;
6363 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6364 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6365 toString(attributes).c_str(), on, outputDesc->getId());
6366 VolumeSource source = toVolumeSource(attributes);
6367 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6368 sourcesToMute.push_back(source);
6369 }
Eric Laurente552edb2014-03-10 17:42:56 -07006370 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006371 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006372 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006373 }
6374
Eric Laurente552edb2014-03-10 17:42:56 -07006375}
6376
François Gaffieaaac0fd2018-11-22 17:56:39 +01006377void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6378 bool on,
6379 const sp<AudioOutputDescriptor>& outputDesc,
6380 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006381 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006382{
jiabin9a3361e2019-10-01 09:38:30 -07006383 if (deviceTypes.empty()) {
6384 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006385 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006386 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006387 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006388 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006389 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006390 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6391 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6392 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006393 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006394 }
6395 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006396 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6397 // ignored
6398 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006399 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006400 if (!outputDesc->isMuted(volumeSource)) {
6401 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006402 return;
6403 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006404 if (outputDesc->decMuteCount(volumeSource) == 0) {
6405 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006406 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006407 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006408 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006409 delayMs);
6410 }
6411 }
6412}
6413
François Gaffie53615e22015-03-19 09:24:12 +01006414bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6415{
François Gaffiec005e562018-11-06 15:04:49 +01006416 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006417 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6418 return true;
6419 }
6420
6421 // has known usage?
6422 switch (paa->usage) {
6423 case AUDIO_USAGE_UNKNOWN:
6424 case AUDIO_USAGE_MEDIA:
6425 case AUDIO_USAGE_VOICE_COMMUNICATION:
6426 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6427 case AUDIO_USAGE_ALARM:
6428 case AUDIO_USAGE_NOTIFICATION:
6429 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6430 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6431 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6432 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6433 case AUDIO_USAGE_NOTIFICATION_EVENT:
6434 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6435 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6436 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6437 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006438 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006439 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006440 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006441 case AUDIO_USAGE_EMERGENCY:
6442 case AUDIO_USAGE_SAFETY:
6443 case AUDIO_USAGE_VEHICLE_STATUS:
6444 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006445 break;
6446 default:
6447 return false;
6448 }
6449 return true;
6450}
6451
François Gaffie2110e042015-03-24 08:41:51 +01006452audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6453{
6454 return mEngine->getForceUse(usage);
6455}
6456
6457bool AudioPolicyManager::isInCall()
6458{
6459 return isStateInCall(mEngine->getPhoneState());
6460}
6461
6462bool AudioPolicyManager::isStateInCall(int state)
6463{
6464 return is_state_in_call(state);
6465}
6466
Eric Laurent74b71512019-11-06 17:21:57 -08006467bool AudioPolicyManager::isCallAudioAccessible()
6468{
6469 audio_mode_t mode = mEngine->getPhoneState();
6470 return (mode == AUDIO_MODE_IN_CALL)
6471 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6472 || (mode == AUDIO_MODE_CALL_SCREEN);
6473}
6474
Eric Laurentd60560a2015-04-10 11:31:20 -07006475void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6476{
6477 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006478 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6479 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
6480 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
6481 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006482 }
6483 }
6484
6485 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6486 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6487 bool release = false;
6488 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6489 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6490 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6491 source->ext.device.type == deviceDesc->type()) {
6492 release = true;
6493 }
6494 }
6495 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6496 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6497 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6498 sink->ext.device.type == deviceDesc->type()) {
6499 release = true;
6500 }
6501 }
6502 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006503 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6504 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006505 }
6506 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006507
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006508 mInputs.clearSessionRoutesForDevice(deviceDesc);
6509
Francois Gaffie716e1432019-01-14 16:58:59 +01006510 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006511}
6512
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006513void AudioPolicyManager::modifySurroundFormats(
6514 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006515 std::unordered_set<audio_format_t> enforcedSurround(
6516 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006517 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6518 for (const auto& pair : mConfig.getSurroundFormats()) {
6519 allSurround.insert(pair.first);
6520 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6521 }
Phil Burk09bc4612016-02-24 15:58:15 -08006522
6523 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6524 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006525 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006526 // This is the resulting set of formats depending on the surround mode:
6527 // 'all surround' = allSurround
6528 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6529 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6530 // 'manual surround' = mManualSurroundFormats
6531 // AUTO: formats v 'enforced surround'
6532 // ALWAYS: formats v 'all surround' v 'enforced surround'
6533 // NEVER: formats ^ 'non-surround'
6534 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006535
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006536 std::unordered_set<audio_format_t> formatSet;
6537 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6538 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006539 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006540 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006541 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006542 formatSet.insert(*formatIter);
6543 }
6544 }
6545 } else {
6546 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6547 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006548 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006549
jiabin81772902018-04-02 17:52:27 -07006550 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006551 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006552 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6553 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6554 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006555 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006556 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6557 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6558 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006559 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006560 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006561 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006562 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006563 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006564 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006565}
6566
jiabin06e4bab2019-07-29 10:13:34 -07006567void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6568 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006569 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6570 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6571
6572 // If NEVER, then remove support for channelMasks > stereo.
6573 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006574 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6575 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006576 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6577 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006578 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006579 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006580 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006581 }
6582 }
jiabin81772902018-04-02 17:52:27 -07006583 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6584 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6585 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006586 bool supports5dot1 = false;
6587 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006588 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006589 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6590 supports5dot1 = true;
6591 break;
6592 }
6593 }
6594 // If not then add 5.1 support.
6595 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006596 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006597 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006598 }
Phil Burk09bc4612016-02-24 15:58:15 -08006599 }
6600}
6601
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006602void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006603 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006604 AudioProfileVector &profiles)
6605{
6606 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006607 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006608
François Gaffie112b0af2015-11-19 16:13:25 +01006609 // Format MUST be checked first to update the list of AudioProfile
6610 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006611 reply = mpClientInterface->getParameters(
6612 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006613 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006614 AudioParameter repliedParameters(reply);
6615 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006616 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006617 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6618 return;
6619 }
Phil Burk09bc4612016-02-24 15:58:15 -08006620 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006621 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006622 if (device == AUDIO_DEVICE_OUT_HDMI
6623 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006624 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006625 }
jiabin3e277cc2019-09-10 14:27:34 -07006626 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006627 }
François Gaffie112b0af2015-11-19 16:13:25 +01006628
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006629 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006630 ChannelMaskSet channelMasks;
6631 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006632 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006633 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006634
6635 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006636 reply = mpClientInterface->getParameters(
6637 ioHandle,
6638 requestedParameters.toString() + ";" +
6639 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006640 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006641 AudioParameter repliedParameters(reply);
6642 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006643 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006644 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006645 }
6646 }
6647 if (profiles.hasDynamicChannelsFor(format)) {
6648 reply = mpClientInterface->getParameters(ioHandle,
6649 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006650 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006651 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006652 AudioParameter repliedParameters(reply);
6653 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006654 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006655 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006656 if (device == AUDIO_DEVICE_OUT_HDMI
6657 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006658 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006659 }
François Gaffie112b0af2015-11-19 16:13:25 +01006660 }
6661 }
jiabin3e277cc2019-09-10 14:27:34 -07006662 addDynamicAudioProfileAndSort(
6663 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006664 }
6665}
Eric Laurentd60560a2015-04-10 11:31:20 -07006666
Mikhail Naganovdc769682018-05-04 15:34:08 -07006667status_t AudioPolicyManager::installPatch(const char *caller,
6668 audio_patch_handle_t *patchHandle,
6669 AudioIODescriptorInterface *ioDescriptor,
6670 const struct audio_patch *patch,
6671 int delayMs)
6672{
6673 ssize_t index = mAudioPatches.indexOfKey(
6674 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6675 *patchHandle : ioDescriptor->getPatchHandle());
6676 sp<AudioPatch> patchDesc;
6677 status_t status = installPatch(
6678 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6679 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006680 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006681 }
6682 return status;
6683}
6684
6685status_t AudioPolicyManager::installPatch(const char *caller,
6686 ssize_t index,
6687 audio_patch_handle_t *patchHandle,
6688 const struct audio_patch *patch,
6689 int delayMs,
6690 uid_t uid,
6691 sp<AudioPatch> *patchDescPtr)
6692{
6693 sp<AudioPatch> patchDesc;
6694 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6695 if (index >= 0) {
6696 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006697 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006698 }
6699
6700 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6701 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6702 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6703 if (status == NO_ERROR) {
6704 if (index < 0) {
6705 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006706 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006707 } else {
6708 patchDesc->mPatch = *patch;
6709 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006710 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006711 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006712 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006713 }
6714 nextAudioPortGeneration();
6715 mpClientInterface->onAudioPatchListUpdate();
6716 }
6717 if (patchDescPtr) *patchDescPtr = patchDesc;
6718 return status;
6719}
6720
jiabinbce0c1d2020-10-05 11:20:18 -07006721bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6722{
6723 const TrackClientVector activeClients = output->getActiveClients();
6724 if (activeClients.empty()) {
6725 return true;
6726 }
6727 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6728 if (index < 0) {
6729 ALOGE("%s, no audio patch found while there are active clients on output %d",
6730 __func__, output->getId());
6731 return false;
6732 }
6733 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6734 DeviceVector routedDevices;
6735 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6736 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6737 patchDesc->mPatch.sinks[i].id);
6738 if (device == nullptr) {
6739 ALOGE("%s, no audio device found with id(%d)",
6740 __func__, patchDesc->mPatch.sinks[i].id);
6741 return false;
6742 }
6743 routedDevices.add(device);
6744 }
6745 for (const auto& client : activeClients) {
6746 // TODO: b/175343099 only travel the valid client
6747 sp<DeviceDescriptor> preferredDevice =
6748 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6749 if (mEngine->getOutputDevicesForAttributes(
6750 client->attributes(), preferredDevice, false) == routedDevices) {
6751 return false;
6752 }
6753 }
6754 return true;
6755}
6756
6757sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6758 const sp<IOProfile>& profile, const DeviceVector& devices)
6759{
6760 for (const auto& device : devices) {
6761 // TODO: This should be checking if the profile supports the device combo.
6762 if (!profile->supportsDevice(device)) {
6763 return nullptr;
6764 }
6765 }
6766 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6767 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6768 status_t status = desc->open(nullptr, devices,
6769 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6770 if (status != NO_ERROR) {
6771 return nullptr;
6772 }
6773
6774 // Here is where the out_set_parameters() for card & device gets called
6775 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6776 const audio_devices_t deviceType = device->type();
6777 const String8 &address = String8(device->address().c_str());
6778 if (!address.isEmpty()) {
6779 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6780 mpClientInterface->setParameters(output, String8(param));
6781 free(param);
6782 }
6783 updateAudioProfiles(device, output, profile->getAudioProfiles());
6784 if (!profile->hasValidAudioProfile()) {
6785 ALOGW("%s() missing param", __func__);
6786 desc->close();
6787 return nullptr;
6788 } else if (profile->hasDynamicAudioProfile()) {
6789 desc->close();
6790 output = AUDIO_IO_HANDLE_NONE;
6791 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
6792 profile->pickAudioProfile(
6793 config.sample_rate, config.channel_mask, config.format);
6794 config.offload_info.sample_rate = config.sample_rate;
6795 config.offload_info.channel_mask = config.channel_mask;
6796 config.offload_info.format = config.format;
6797
6798 status = desc->open(&config, devices,
6799 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6800 if (status != NO_ERROR) {
6801 return nullptr;
6802 }
6803 }
6804
6805 addOutput(output, desc);
6806 if (audio_is_remote_submix_device(deviceType) && address != "0") {
6807 sp<AudioPolicyMix> policyMix;
6808 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
6809 policyMix->setOutput(desc);
6810 desc->mPolicyMix = policyMix;
6811 } else {
6812 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
6813 address.string());
6814 }
6815
6816 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
6817 // no duplicated output for direct outputs and
6818 // outputs used by dynamic policy mixes
6819 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
6820
6821 //TODO: configure audio effect output stage here
6822
6823 // open a duplicating output thread for the new output and the primary output
6824 sp<SwAudioOutputDescriptor> dupOutputDesc =
6825 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
6826 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
6827 if (status == NO_ERROR) {
6828 // add duplicated output descriptor
6829 addOutput(duplicatedOutput, dupOutputDesc);
6830 } else {
6831 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
6832 mPrimaryOutput->mIoHandle, output);
6833 desc->close();
6834 removeOutput(output);
6835 nextAudioPortGeneration();
6836 return nullptr;
6837 }
6838 }
6839 return desc;
6840}
6841
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006842} // namespace android