blob: 0ec57bf89e5c992457fcbd31c9d9e97360999ca7 [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))) {
Mikhail Naganov37977152018-07-11 15:54:44 -0700249 closeOutput(output);
250 }
Eric Laurente552edb2014-03-10 17:42:56 -0700251 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700252 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
253 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700254 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700255 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800256 };
257
258 if (doCheckForDeviceAndOutputChanges) {
259 checkForDeviceAndOutputChanges(checkCloseOutputs);
260 } else {
261 checkCloseOutputs();
262 }
Eric Laurente552edb2014-03-10 17:42:56 -0700263
Eric Laurent87ffa392015-05-22 10:32:38 -0700264 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100265 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
266 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700267 }
jiabinbce0c1d2020-10-05 11:20:18 -0700268 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100269 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700270 const DeviceVector activeMediaDevices =
271 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
274 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100275 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700276 // do not force device change on duplicated output because if device is 0, it will
277 // also force a device 0 for the two outputs it is duplicated to which may override
278 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100279 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100280 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700281 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700282 // always force when disconnecting (a non-duplicated device)
283 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100284 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700285 }
jiabinbce0c1d2020-10-05 11:20:18 -0700286 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
287 desc->devices() != activeMediaDevices &&
288 desc->supportsDevicesForPlayback(activeMediaDevices)) {
289 // Reopen the output to query the dynamic profiles when there is not active
290 // clients or all active clients will be rerouted. Otherwise, set the flag
291 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
292 // can be reopened to query dynamic profiles when all clients are inactive.
293 if (areAllActiveTracksRerouted(desc)) {
294 outputsToReopen.push_back(mOutputs.keyAt(i));
295 } else {
296 desc->mPendingReopenToQueryProfiles = true;
297 }
298 }
299 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
300 // Clear the flag that previously set for re-querying profiles.
301 desc->mPendingReopenToQueryProfiles = false;
302 }
303 }
304 for (const auto& output : outputsToReopen) {
305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
306 closeOutput(output);
307 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700308 }
309
Eric Laurentd60560a2015-04-10 11:31:20 -0700310 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100311 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700312 }
313
Eric Laurent72aa32f2014-05-30 18:51:48 -0700314 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700315 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700316 } // end if is output device
317
Eric Laurente552edb2014-03-10 17:42:56 -0700318 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700319 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100320 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700321 switch (state)
322 {
323 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700324 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700327 return INVALID_OPERATION;
328 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700329
330 if (mAvailableInputDevices.add(device) < 0) {
331 return NO_MEMORY;
332 }
333
François Gaffie44481e72016-04-20 07:49:57 +0200334 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
335 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100336 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200337
Eric Laurent0dd51852019-04-19 18:18:58 -0700338 if (checkInputsForDevice(device, state) != NO_ERROR) {
339 mAvailableInputDevices.remove(device);
340
François Gaffie11d30102018-11-02 16:09:09 +0100341 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100342
343 mHwModules.cleanUpForDevice(device);
344
Eric Laurentd4692962014-05-05 18:13:44 -0700345 return INVALID_OPERATION;
346 }
347
Eric Laurentd4692962014-05-05 18:13:44 -0700348 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700349
350 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700351 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700352 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700354 return INVALID_OPERATION;
355 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700356
François Gaffie11d30102018-11-02 16:09:09 +0100357 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700358
359 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100360 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700361
François Gaffie11d30102018-11-02 16:09:09 +0100362 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700363
364 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100365
366 // remove device from mReportedFormatsMap cache
367 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700368 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700369
370 default:
François Gaffie11d30102018-11-02 16:09:09 +0100371 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700372 return BAD_VALUE;
373 }
374
Eric Laurent736a1022019-03-27 18:28:46 -0700375 // Propagate device availability to Engine
376 setEngineDeviceConnectionState(device, state);
377
Eric Laurent0dd51852019-04-19 18:18:58 -0700378 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700379 // As the input device list can impact the output device selection, update
380 // getDeviceForStrategy() cache
381 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700382
Eric Laurent87ffa392015-05-22 10:32:38 -0700383 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100384 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
385 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700386 }
387
Eric Laurentd60560a2015-04-10 11:31:20 -0700388 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700390 }
391
Eric Laurentb52c1522014-05-20 11:27:36 -0700392 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700393 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700394 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700395
François Gaffie11d30102018-11-02 16:09:09 +0100396 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700397 return BAD_VALUE;
398}
399
Eric Laurent736a1022019-03-27 18:28:46 -0700400void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
401 audio_policy_dev_state_t state) {
402
403 // the Engine does not have to know about remote submix devices used by dynamic audio policies
404 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
405 return;
406 }
407 mEngine->setDeviceConnectionState(device, state);
408}
409
410
Eric Laurente0720872014-03-11 09:30:41 -0700411audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100412 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700413{
Eric Laurent634b7142016-04-20 13:48:02 -0700414 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800415 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
416 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700417 (strlen(device_address) != 0)/*matchAddress*/);
418
419 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100420 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700421 device, device_address);
422 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
423 }
François Gaffie53615e22015-03-19 09:24:12 +0100424
Eric Laurent3a4311c2014-03-17 12:00:47 -0700425 DeviceVector *deviceVector;
426
Eric Laurente552edb2014-03-10 17:42:56 -0700427 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700428 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700429 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 deviceVector = &mAvailableInputDevices;
431 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100432 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700433 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700434 }
Eric Laurent634b7142016-04-20 13:48:02 -0700435
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800436 return (deviceVector->getDevice(
437 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700438 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800439}
440
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800441status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
442 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800443 const char *device_name,
444 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800445{
446 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700447 String8 reply;
448 AudioParameter param;
449 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800450
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800451 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
452 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800453
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800454 // connect/disconnect only 1 device at a time
455 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
456
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800457 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700458 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800459 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800460 // Nothing to do: device is not connected
461 return NO_ERROR;
462 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800463 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800464
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700465 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 // configure codecs.
467 // Handle two specific cases by sending a set parameter to
468 // configure A2DP codecs. No need to toggle device state.
469 // Case 1: A2DP active device switches from primary to primary
470 // module
471 // Case 2: A2DP device config changes on primary module.
jiabin9a3361e2019-10-01 09:38:30 -0700472 if (audio_is_a2dp_out_device(device)) {
473 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800474 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
475 if (availablePrimaryOutputDevices().contains(devDesc) &&
476 (module != 0 && module->getHandle() == primaryHandle)) {
477 reply = mpClientInterface->getParameters(
478 AUDIO_IO_HANDLE_NONE,
479 String8(AudioParameter::keyReconfigA2dpSupported));
480 AudioParameter repliedParameters(reply);
481 repliedParameters.getInt(
482 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
483 if (isReconfigA2dpSupported) {
484 const String8 key(AudioParameter::keyReconfigA2dp);
485 param.add(key, String8("true"));
486 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
487 devDesc->setEncodedFormat(encodedFormat);
488 return NO_ERROR;
489 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700490 }
491 }
cnx421bd2dcc42020-07-11 14:58:44 +0800492 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
493 for (size_t i = 0; i < mOutputs.size(); i++) {
494 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
495 // mute media strategies and delay device switch by the largest
496 // This avoid sending the music tail into the earpiece or headset.
497 setStrategyMute(musicStrategy, true, desc);
498 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
499 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
500 nullptr, true /*fromCache*/).types());
501 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800502 // Toggle the device state: UNAVAILABLE -> AVAILABLE
503 // This will force reading again the device configuration
504 status = setDeviceConnectionState(device,
505 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800506 device_address, device_name,
507 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 if (status != NO_ERROR) {
509 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
510 status);
511 return status;
512 }
513
514 status = setDeviceConnectionState(device,
515 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517 if (status != NO_ERROR) {
518 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
519 status);
520 return status;
521 }
522
523 return NO_ERROR;
524}
525
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800526status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
527 std::vector<audio_format_t> *formats)
528{
529 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800530 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800531 std::unordered_set<audio_format_t> formatSet;
532 sp<HwModule> primaryModule =
533 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700534 if (primaryModule == nullptr) {
535 ALOGE("%s() unable to get primary module", __func__);
536 return NO_INIT;
537 }
jiabin9a3361e2019-10-01 09:38:30 -0700538 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
539 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800540 for (const auto& device : declaredDevices) {
541 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800542 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800543 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800544 return status;
545}
546
François Gaffie11d30102018-11-02 16:09:09 +0100547uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700548{
549 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100550 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700551 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700552
jiabin9a3361e2019-10-01 09:38:30 -0700553 if(!hasPrimaryOutput() ||
554 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700555 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700556 }
François Gaffie11d30102018-11-02 16:09:09 +0100557 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
558
Francois Gaffie716e1432019-01-14 16:58:59 +0100559 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100560 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100561 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100562
563 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100564 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700565
566 // release existing RX patch if any
567 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100568 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700569 mCallRxPatch.clear();
570 }
571 // release TX patch if any
572 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100573 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700574 mCallTxPatch.clear();
575 }
576
François Gaffie9eb18552018-11-05 10:33:26 +0100577 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700578 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100579 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700580 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100581 // retrieve Rx Source and Tx Sink device descriptors
582 sp<DeviceDescriptor> rxSourceDevice =
583 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
584 String8(),
585 AUDIO_FORMAT_DEFAULT);
586 sp<DeviceDescriptor> txSinkDevice =
587 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
588 String8(),
589 AUDIO_FORMAT_DEFAULT);
590
591 // RX and TX Telephony device are declared by Primary Audio HAL
592 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
593 (telephonyRxModule->getHalVersionMajor() >= 3)) {
594 if (rxSourceDevice == 0 || txSinkDevice == 0) {
595 // RX / TX Telephony device(s) is(are) not currently available
596 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
597 return muteWaitMs;
598 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100599 // createAudioPatchInternal now supports both HW / SW bridging
600 createRxPatch = true;
601 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100602 } else {
603 // If the RX device is on the primary HW module, then use legacy routing method for
604 // voice calls via setOutputDevice() on primary output.
605 // Otherwise, create two audio patches for TX and RX path.
606 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
607 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700608 // If the TX device is also on the primary HW module, setOutputDevice() will take care
609 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100610 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
611 (txSinkDevice != 0);
612 }
613 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
614 // Otherwise, create two audio patches for TX and RX path.
615 if (!createRxPatch) {
616 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700617 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100618 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800619
620 // If the TX device is on the primary HW module but RX device is
621 // on other HW module, SinkMetaData of telephony input should handle it
622 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700623 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700624 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100625 // terminate active capture if on the same HW module as the call TX source device
626 // FIXME: would be better to refine to only inputs whose profile connects to the
627 // call TX device but this information is not in the audio patch and logic here must be
628 // symmetric to the one in startInput()
629 for (const auto& activeDesc : mInputs.getActiveInputs()) {
630 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
631 closeActiveClients(activeDesc);
632 }
633 }
François Gaffie9eb18552018-11-05 10:33:26 +0100634 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800635 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700636
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800637 return muteWaitMs;
638}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700639
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800640sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100641 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700642 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700643
François Gaffie11d30102018-11-02 16:09:09 +0100644 if (device == nullptr) {
645 return nullptr;
646 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100647
648 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800649 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100650 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800651 addSource(mAvailableInputDevices.getDevice(
652 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800653 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100654 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800655 addSink(mAvailableOutputDevices.getDevice(
656 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800657 }
658
François Gaffieafd4cea2019-11-18 15:50:22 +0100659 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
660 status_t status =
661 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
662 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
663 if (status != NO_ERROR || index < 0) {
664 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
665 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800666 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100667 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800668}
669
Mikhail Naganov100f0122018-11-29 11:22:16 -0800670bool AudioPolicyManager::isDeviceOfModule(
671 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
672 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
673 if (module != 0) {
674 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
675 .indexOf(devDesc) != NAME_NOT_FOUND
676 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
677 .indexOf(devDesc) != NAME_NOT_FOUND;
678 }
679 return false;
680}
681
Eric Laurente0720872014-03-11 09:30:41 -0700682void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700683{
684 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100685 // store previous phone state for management of sonification strategy below
686 int oldState = mEngine->getPhoneState();
687
688 if (mEngine->setPhoneState(state) != NO_ERROR) {
689 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700690 return;
691 }
François Gaffie2110e042015-03-24 08:41:51 +0100692 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700693 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700694 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700695 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800696 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700697 }
698
François Gaffie2110e042015-03-24 08:41:51 +0100699 /**
700 * Switching to or from incall state or switching between telephony and VoIP lead to force
701 * routing command.
702 */
Eric Laurent74b71512019-11-06 17:21:57 -0800703 bool force = ((isStateInCall(oldState) != isStateInCall(state))
704 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700705
706 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700707 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700708
Eric Laurente552edb2014-03-10 17:42:56 -0700709 int delayMs = 0;
710 if (isStateInCall(state)) {
711 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100712 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
713 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700714 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700715 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700716 // mute media and sonification strategies and delay device switch by the largest
717 // latency of any output where either strategy is active.
718 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100719 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
720 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
721 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700722 (delayMs < (int)desc->latency()*2)) {
723 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700724 }
François Gaffiec005e562018-11-06 15:04:49 +0100725 setStrategyMute(musicStrategy, true, desc);
726 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
727 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
728 nullptr, true /*fromCache*/).types());
729 setStrategyMute(sonificationStrategy, true, desc);
730 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
731 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
732 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700733 }
734 }
735
Eric Laurent87ffa392015-05-22 10:32:38 -0700736 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100737 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700738 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100739 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700740 // force routing command to audio hardware when ending call
741 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100742 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
743 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700744 }
Eric Laurente552edb2014-03-10 17:42:56 -0700745
Eric Laurent87ffa392015-05-22 10:32:38 -0700746 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100747 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700748 } else if (oldState == AUDIO_MODE_IN_CALL) {
749 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100750 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700751 mCallRxPatch.clear();
752 }
753 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100754 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700755 mCallTxPatch.clear();
756 }
François Gaffie11d30102018-11-02 16:09:09 +0100757 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700758 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100759 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700761 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700762
763 // reevaluate routing on all outputs in case tracks have been started during the call
764 for (size_t i = 0; i < mOutputs.size(); i++) {
765 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100766 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700767 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100768 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700769 }
770 }
771
Eric Laurente552edb2014-03-10 17:42:56 -0700772 if (isStateInCall(state)) {
773 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700774 // force reevaluating accessibility routing when call starts
775 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700776 }
777
778 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100779 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
780 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700781}
782
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700783audio_mode_t AudioPolicyManager::getPhoneState() {
784 return mEngine->getPhoneState();
785}
786
Eric Laurente0720872014-03-11 09:30:41 -0700787void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100788 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700789{
François Gaffie2110e042015-03-24 08:41:51 +0100790 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700791 if (config == mEngine->getForceUse(usage)) {
792 return;
793 }
Eric Laurente552edb2014-03-10 17:42:56 -0700794
François Gaffie2110e042015-03-24 08:41:51 +0100795 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
796 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
797 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700798 }
François Gaffie2110e042015-03-24 08:41:51 +0100799 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
800 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
801 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700802
803 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700804 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800805
Eric Laurent22fcda22019-05-17 16:28:47 -0700806 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
807 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
808 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
809 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
810 }
811
Eric Laurentdc462862016-07-19 12:29:53 -0700812 //FIXME: workaround for truncated touch sounds
813 // to be removed when the problem is handled by system UI
814 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700815 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
816 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
817 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700818
819 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100820 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700821}
822
Eric Laurente0720872014-03-11 09:30:41 -0700823void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700824{
825 ALOGV("setSystemProperty() property %s, value %s", property, value);
826}
827
Michael Chana94fbb22018-04-24 14:31:19 +1000828// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
829// search to profiles for direct outputs.
830sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100831 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000832 uint32_t samplingRate,
833 audio_format_t format,
834 audio_channel_mask_t channelMask,
835 audio_output_flags_t flags,
836 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700837{
Michael Chana94fbb22018-04-24 14:31:19 +1000838 if (directOnly) {
839 // only retain flags that will drive the direct output profile selection
840 // if explicitly requested
841 static const uint32_t kRelevantFlags =
842 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700843 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000844 flags =
845 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
846 }
Eric Laurent861a6282015-05-18 15:40:16 -0700847
848 sp<IOProfile> profile;
849
Mikhail Naganovd4120142017-12-06 15:49:22 -0800850 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800851 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100852 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700853 samplingRate, NULL /*updatedSamplingRate*/,
854 format, NULL /*updatedFormat*/,
855 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700856 flags)) {
857 continue;
858 }
859 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100860 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700861 continue;
862 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800863 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700864 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800865 continue;
866 }
Michael Chana94fbb22018-04-24 14:31:19 +1000867 if (!directOnly) return curProfile;
868 // when searching for direct outputs, if several profiles are compatible, give priority
869 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100870 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700871 continue;
872 }
873 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100874 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700875 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700876 }
Eric Laurente552edb2014-03-10 17:42:56 -0700877 }
878 }
Eric Laurent861a6282015-05-18 15:40:16 -0700879 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700880}
881
Eric Laurentf4e63452017-11-06 19:31:46 +0000882audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700883{
François Gaffiec005e562018-11-06 15:04:49 +0100884 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800885
886 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
887 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
888 // format, flags, etc. This may result in some discrepancy for functions that utilize
889 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
890 // and AudioSystem::getOutputSamplingRate().
891
François Gaffie11d30102018-11-02 16:09:09 +0100892 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700893 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700894
François Gaffie11d30102018-11-02 16:09:09 +0100895 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
896 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000897 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700898}
899
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700900status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
901 const audio_attributes_t *srcAttr,
902 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700903{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700904 if (srcAttr != NULL) {
905 if (!isValidAttributes(srcAttr)) {
906 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
907 __func__,
908 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
909 srcAttr->tags);
910 return BAD_VALUE;
911 }
912 *dstAttr = *srcAttr;
913 } else {
914 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
915 ALOGE("%s: invalid stream type", __func__);
916 return BAD_VALUE;
917 }
François Gaffiec005e562018-11-06 15:04:49 +0100918 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700919 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700920
921 // Only honor audibility enforced when required. The client will be
922 // forced to reconnect if the forced usage changes.
923 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700924 dstAttr->flags = static_cast<audio_flags_mask_t>(
925 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700926 }
927
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700928 return NO_ERROR;
929}
930
Kevin Rocard153f92d2018-12-18 18:33:28 -0800931status_t AudioPolicyManager::getOutputForAttrInt(
932 audio_attributes_t *resultAttr,
933 audio_io_handle_t *output,
934 audio_session_t session,
935 const audio_attributes_t *attr,
936 audio_stream_type_t *stream,
937 uid_t uid,
938 const audio_config_t *config,
939 audio_output_flags_t *flags,
940 audio_port_handle_t *selectedDeviceId,
941 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700942 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800943 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700944{
François Gaffiec005e562018-11-06 15:04:49 +0100945 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100946 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100947 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100948 const sp<DeviceDescriptor> requestedDevice =
949 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
950
Eric Laurent8a1095a2019-11-08 14:44:16 -0800951 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700952 status_t status = getAudioAttributes(resultAttr, attr, *stream);
953 if (status != NO_ERROR) {
954 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700955 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700956 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700957 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700958 }
François Gaffiec005e562018-11-06 15:04:49 +0100959 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700960
François Gaffiec005e562018-11-06 15:04:49 +0100961 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
962 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700963
Kevin Rocard153f92d2018-12-18 18:33:28 -0800964 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
965 // otherwise, fallback to the dynamic policies, if none match, query the engine.
966 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700967 sp<AudioPolicyMix> primaryMix;
968 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700969 if (status != OK) {
970 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800971 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700972
Kevin Rocard153f92d2018-12-18 18:33:28 -0800973 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700974 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800975
976 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700977 if ((usePrimaryOutputFromPolicyMixes
978 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800979 && !audio_is_linear_pcm(config->format)) {
980 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800981 return BAD_VALUE;
982 }
983 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700984 sp<DeviceDescriptor> deviceDesc =
985 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
986 primaryMix->mDeviceAddress,
987 AUDIO_FORMAT_DEFAULT);
988 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -0700989 if (deviceDesc != nullptr
990 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700991 audio_io_handle_t newOutput;
992 status = openDirectOutput(
993 *stream, session, config,
994 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
995 DeviceVector(deviceDesc), &newOutput);
996 if (status != NO_ERROR) {
997 policyDesc = nullptr;
998 } else {
999 policyDesc = mOutputs.valueFor(newOutput);
1000 primaryMix->setOutput(policyDesc);
1001 }
1002 }
1003 if (policyDesc != nullptr) {
1004 policyDesc->mPolicyMix = primaryMix;
1005 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001006 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001007
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001008 ALOGV("getOutputForAttr() returns output %d", *output);
1009 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1010 *outputType = API_OUT_MIX_PLAYBACK;
1011 } else {
1012 *outputType = API_OUTPUT_LEGACY;
1013 }
1014 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001015 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001016 }
François Gaffiec005e562018-11-06 15:04:49 +01001017 // Virtual sources must always be dynamicaly or explicitly routed
1018 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1019 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1020 return BAD_VALUE;
1021 }
1022 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1023 // in order to let the choice of the order to future vendor engine
1024 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001025
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001026 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001027 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001028 }
1029
Nadav Barb2f18162018-07-18 13:01:53 +03001030 // Set incall music only if device was explicitly set, and fallback to the device which is
1031 // chosen by the engine if not.
1032 // FIXME: provide a more generic approach which is not device specific and move this back
1033 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001034 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001035 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001036 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001037 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001038 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001039 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001040 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001041 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001042 }
1043 }
1044
François Gaffiec005e562018-11-06 15:04:49 +01001045 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1046 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1047 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001048
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001049 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001050 if (!msdDevices.isEmpty()) {
1051 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001052 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1053 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1054 ALOGV("%s() Using MSD devices %s instead of devices %s",
1055 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001056 } else {
1057 *output = AUDIO_IO_HANDLE_NONE;
1058 }
1059 }
1060 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001061 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001062 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001063 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001064 if (*output == AUDIO_IO_HANDLE_NONE) {
1065 return INVALID_OPERATION;
1066 }
Paul McLeanaa981192015-03-21 09:55:15 -07001067
François Gaffiec005e562018-11-06 15:04:49 +01001068 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001069
Eric Laurent8a1095a2019-11-08 14:44:16 -08001070 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1071 *outputType = API_OUTPUT_TELEPHONY_TX;
1072 } else {
1073 *outputType = API_OUTPUT_LEGACY;
1074 }
1075
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001076 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1077
1078 return NO_ERROR;
1079}
1080
1081status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1082 audio_io_handle_t *output,
1083 audio_session_t session,
1084 audio_stream_type_t *stream,
1085 uid_t uid,
1086 const audio_config_t *config,
1087 audio_output_flags_t *flags,
1088 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001089 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001090 std::vector<audio_io_handle_t> *secondaryOutputs,
1091 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001092{
1093 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1094 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1095 return INVALID_OPERATION;
1096 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001097 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001098 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001099 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001100 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001101 const sp<DeviceDescriptor> requestedDevice =
1102 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1103
1104 // Prevent from storing invalid requested device id in clients
1105 const audio_port_handle_t sanitizedRequestedPortId =
1106 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1107 *selectedDeviceId = sanitizedRequestedPortId;
1108
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001109 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001110 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001111 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001112 if (status != NO_ERROR) {
1113 return status;
1114 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001115 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001116 if (secondaryOutputs != nullptr) {
1117 for (auto &secondaryMix : secondaryMixes) {
1118 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1119 if (outputDesc != nullptr &&
1120 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1121 secondaryOutputs->push_back(outputDesc->mIoHandle);
1122 weakSecondaryOutputDescs.push_back(outputDesc);
1123 }
1124 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001125 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126
Eric Laurent8fc147b2018-07-22 19:13:55 -07001127 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001128 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001129 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001130 };
jiabin4ef93452019-09-10 14:29:54 -07001131 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001132
Eric Laurentc209fe42020-06-05 18:11:23 -07001133 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001134 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001135 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001136 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001137 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001138 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001139 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001140 std::move(weakSecondaryOutputDescs),
1141 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001142 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001143
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001144 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1145 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001146
Eric Laurente83b55d2014-11-14 10:06:21 -08001147 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001148}
1149
Eric Laurentc529cf62020-04-17 18:19:10 -07001150status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1151 audio_session_t session,
1152 const audio_config_t *config,
1153 audio_output_flags_t flags,
1154 const DeviceVector &devices,
1155 audio_io_handle_t *output) {
1156
1157 *output = AUDIO_IO_HANDLE_NONE;
1158
1159 // skip direct output selection if the request can obviously be attached to a mixed output
1160 // and not explicitly requested
1161 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1162 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1163 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1164 return NAME_NOT_FOUND;
1165 }
1166
1167 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1168 // This prevents creating an offloaded track and tearing it down immediately after start
1169 // when audioflinger detects there is an active non offloadable effect.
1170 // FIXME: We should check the audio session here but we do not have it in this context.
1171 // This may prevent offloading in rare situations where effects are left active by apps
1172 // in the background.
1173 sp<IOProfile> profile;
1174 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1175 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1176 profile = getProfileForOutput(
1177 devices, config->sample_rate, config->format, config->channel_mask,
1178 flags, true /* directOnly */);
1179 }
1180
1181 if (profile == nullptr) {
1182 return NAME_NOT_FOUND;
1183 }
1184
1185 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1186 for (size_t i = 0; i < mOutputs.size(); i++) {
1187 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1188 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1189 // reuse direct output if currently open by the same client
1190 // and configured with same parameters
1191 if ((config->sample_rate == desc->getSamplingRate()) &&
1192 (config->format == desc->getFormat()) &&
1193 (config->channel_mask == desc->getChannelMask()) &&
1194 (session == desc->mDirectClientSession)) {
1195 desc->mDirectOpenCount++;
1196 ALOGI("%s reusing direct output %d for session %d", __func__,
1197 mOutputs.keyAt(i), session);
1198 *output = mOutputs.keyAt(i);
1199 return NO_ERROR;
1200 }
1201 }
1202 }
1203
1204 if (!profile->canOpenNewIo()) {
1205 return NAME_NOT_FOUND;
1206 }
1207
1208 sp<SwAudioOutputDescriptor> outputDesc =
1209 new SwAudioOutputDescriptor(profile, mpClientInterface);
1210
1211 String8 address = getFirstDeviceAddress(devices);
1212
1213 // MSD patch may be using the only output stream that can service this request. Release
1214 // MSD patch to prioritize this request over any active output on MSD.
1215 AudioPatchCollection msdPatches = getMsdPatches();
1216 for (size_t i = 0; i < msdPatches.size(); i++) {
1217 const auto& patch = msdPatches[i];
1218 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1219 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1220 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1221 devices.containsDeviceWithType(sink->ext.device.type) &&
1222 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1223 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1224 releaseAudioPatch(patch->getHandle(), mUidCached);
1225 break;
1226 }
1227 }
1228 }
1229
1230 status_t status = outputDesc->open(config, devices, stream, flags, output);
1231
1232 // only accept an output with the requested parameters
1233 if (status != NO_ERROR ||
1234 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1235 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1236 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1237 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1238 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1239 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1240 config->channel_mask, outputDesc->getChannelMask());
1241 if (*output != AUDIO_IO_HANDLE_NONE) {
1242 outputDesc->close();
1243 }
1244 // fall back to mixer output if possible when the direct output could not be open
1245 if (audio_is_linear_pcm(config->format) &&
1246 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1247 return NAME_NOT_FOUND;
1248 }
1249 *output = AUDIO_IO_HANDLE_NONE;
1250 return BAD_VALUE;
1251 }
1252 outputDesc->mDirectOpenCount = 1;
1253 outputDesc->mDirectClientSession = session;
1254
1255 addOutput(*output, outputDesc);
1256 mPreviousOutputs = mOutputs;
1257 ALOGV("%s returns new direct output %d", __func__, *output);
1258 mpClientInterface->onAudioPortListUpdate();
1259 return NO_ERROR;
1260}
1261
François Gaffie11d30102018-11-02 16:09:09 +01001262audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1263 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001264 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001265 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001266 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001267 audio_output_flags_t *flags,
1268 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001269{
Andy Hungc88b0642018-04-27 15:42:35 -07001270 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001271
jiabine375d412019-02-26 12:54:53 -08001272 // Discard haptic channel mask when forcing muting haptic channels.
1273 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001274 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1275 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001276
Eric Laurente552edb2014-03-10 17:42:56 -07001277 // open a direct output if required by specified parameters
1278 //force direct flag if offload flag is set: offloading implies a direct output stream
1279 // and all common behaviors are driven by checking only the direct flag
1280 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001281 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1282 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001283 }
Nadav Bar766fb022018-01-07 12:18:03 +02001284 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1285 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001286 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001287 // only allow deep buffering for music stream type
1288 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001289 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001290 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001291 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001292 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1293 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001294 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001295 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001296 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001297 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001298 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001299 audio_is_linear_pcm(config->format) &&
1300 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001301 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001302 AUDIO_OUTPUT_FLAG_DIRECT);
1303 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001304 }
Eric Laurente552edb2014-03-10 17:42:56 -07001305
Eric Laurentc529cf62020-04-17 18:19:10 -07001306 audio_config_t directConfig = *config;
1307 directConfig.channel_mask = channelMask;
1308 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1309 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001310 return output;
1311 }
1312
Eric Laurent14cbfca2016-03-17 09:42:16 -07001313 // A request for HW A/V sync cannot fallback to a mixed output because time
1314 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001315 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001316 return AUDIO_IO_HANDLE_NONE;
1317 }
1318
Eric Laurente552edb2014-03-10 17:42:56 -07001319 // ignoring channel mask due to downmix capability in mixer
1320
1321 // open a non direct output
1322
1323 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001324 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001325 // get which output is suitable for the specified stream. The actual
1326 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001327 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001328
Eric Laurent8838a382014-09-08 16:44:28 -07001329 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001330 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001331 output = selectOutput(
1332 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001333 }
François Gaffie11d30102018-11-02 16:09:09 +01001334 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001335 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001336 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001337
Eric Laurente552edb2014-03-10 17:42:56 -07001338 return output;
1339}
1340
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001341sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001342 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1343 mAvailableInputDevices);
1344 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1345}
1346
1347DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1348 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1349 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001350}
1351
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1353 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001354 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1355 if (msdModule != 0) {
1356 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1357 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1358 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1359 const struct audio_port_config *source = &patch->mPatch.sources[j];
1360 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1361 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001362 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001363 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001364 }
1365 }
1366 }
1367 return msdPatches;
1368}
1369
François Gaffie11d30102018-11-02 16:09:09 +01001370status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001371 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1372{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001373 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001374 if (msdModule == nullptr) {
1375 ALOGE("%s() unable to get MSD module", __func__);
1376 return NO_INIT;
1377 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001378 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001379 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001380 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001381 return NO_INIT;
1382 }
1383 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1384 if (inputProfiles.isEmpty()) {
1385 ALOGE("%s() no input profiles for MSD module", __func__);
1386 return NO_INIT;
1387 }
1388 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1389 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001390 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001391 return NO_INIT;
1392 }
1393 AudioProfileVector msdProfiles;
1394 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1395 for (const auto &inProfile : inputProfiles) {
1396 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001397 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001398 }
1399 }
1400 AudioProfileVector deviceProfiles;
1401 for (const auto &outProfile : outputProfiles) {
1402 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001403 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001404 }
1405 }
1406 struct audio_config_base bestSinkConfig;
jiabin3e277cc2019-09-10 14:27:34 -07001407 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001408 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabin3e277cc2019-09-10 14:27:34 -07001409 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001410 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001411 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1412 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001413 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001414 }
1415 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1416 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1417 sinkConfig->format = bestSinkConfig.format;
1418 // For encoded streams force direct flag to prevent downstream mixing.
1419 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1420 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001421 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1422 // For formats compatible with IEC61937 encapsulation, assume that
1423 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1424 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1425 // raw and IEC61937 framed streams.
1426 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1427 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1428 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001429 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1430 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1431 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1432 sourceConfig->format = bestSinkConfig.format;
1433 // Copy input stream directly without any processing (e.g. resampling).
1434 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1435 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1436 if (hwAvSync) {
1437 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1438 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1439 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1440 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1441 }
1442 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1443 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1444 sinkConfig->config_mask |= config_mask;
1445 sourceConfig->config_mask |= config_mask;
1446 return NO_ERROR;
1447}
1448
François Gaffie11d30102018-11-02 16:09:09 +01001449PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001450{
1451 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001452 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001453 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1454 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1455 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1456 // For now, we just forcefully try with HwAvSync first.
1457 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1458 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1459 getBestMsdAudioProfileFor(
1460 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1461 if (res == NO_ERROR) {
1462 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1463 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1464 }
1465 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1466 " supporting PCM format conversion.", __func__);
1467 return patchBuilder;
1468}
1469
François Gaffie11d30102018-11-02 16:09:09 +01001470status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1471 sp<DeviceDescriptor> device = outputDevice;
1472 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001473 // Use media strategy for unspecified output device. This should only
1474 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1475 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001476 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1477 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001478 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1479 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001480 }
François Gaffie11d30102018-11-02 16:09:09 +01001481 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1482 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001483 const struct audio_patch* patch = patchBuilder.patch();
1484 const AudioPatchCollection msdPatches = getMsdPatches();
1485 if (!msdPatches.isEmpty()) {
1486 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1487 "The current MSD prototype only supports one output patch");
1488 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1489 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1490 return NO_ERROR;
1491 }
François Gaffieafd4cea2019-11-18 15:50:22 +01001492 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001493 }
1494 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1495 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1496 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1497 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001498 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1499 device->toString().c_str(), patch->sources[0].format,
1500 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001501 return status;
1502}
1503
Eric Laurente0720872014-03-11 09:30:41 -07001504audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001505 audio_output_flags_t flags,
1506 audio_format_t format,
1507 audio_channel_mask_t channelMask,
1508 uint32_t samplingRate,
1509 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001510{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001511 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1512 "%s called with format %#x", __func__, format);
1513
jiabinebb6af42020-06-09 17:31:17 -07001514 // Return the output that haptic-generating attached to when 1) session id is specified,
1515 // 2) haptic-generating effect exists for given session id and 3) the output that
1516 // haptic-generating effect attached to is in given outputs.
1517 if (sessionId != AUDIO_SESSION_NONE) {
1518 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1519 sessionId, FX_IID_HAPTICGENERATOR);
1520 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1521 return hapticGeneratingOutput;
1522 }
1523 }
1524
Eric Laurent16c66dd2019-05-01 17:54:10 -07001525 // Flags disqualifying an output: the match must happen before calling selectOutput()
1526 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1527 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1528
1529 // Flags expressing a functional request: must be honored in priority over
1530 // other criteria
1531 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1532 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1533 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1534 // Flags expressing a performance request: have lower priority than serving
1535 // requested sampling rate or channel mask
1536 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1537 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1538 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1539
1540 const audio_output_flags_t functionalFlags =
1541 (audio_output_flags_t)(flags & kFunctionalFlags);
1542 const audio_output_flags_t performanceFlags =
1543 (audio_output_flags_t)(flags & kPerformanceFlags);
1544
1545 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1546
Eric Laurente552edb2014-03-10 17:42:56 -07001547 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001548 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001549 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001550 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001551 // 2: the output with the highest number of requested functional flags
1552 // 3: the output supporting the exact channel mask
1553 // 4: the output with a higher channel count than requested
1554 // 5: the output with a higher sampling rate than requested
1555 // 6: the output with the highest number of requested performance flags
1556 // 7: the output with the bit depth the closest to the requested one
1557 // 8: the primary output
1558 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001559
Eric Laurent16c66dd2019-05-01 17:54:10 -07001560 // matching criteria values in priority order for best matching output so far
1561 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001562
Eric Laurent16c66dd2019-05-01 17:54:10 -07001563 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1564 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1565 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001566
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001567 for (audio_io_handle_t output : outputs) {
1568 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001569 // matching criteria values in priority order for current output
1570 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001571
Eric Laurent16c66dd2019-05-01 17:54:10 -07001572 if (outputDesc->isDuplicated()) {
1573 continue;
1574 }
1575 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1576 continue;
1577 }
Eric Laurent8838a382014-09-08 16:44:28 -07001578
Eric Laurent16c66dd2019-05-01 17:54:10 -07001579 // If haptic channel is specified, use the haptic output if present.
1580 // When using haptic output, same audio format and sample rate are required.
1581 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001582 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001583 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1584 continue;
1585 }
1586 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001587 && format == outputDesc->getFormat()
1588 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001589 currentMatchCriteria[0] = outputHapticChannelCount;
1590 }
1591
1592 // functional flags match
1593 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1594
1595 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001596 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1597 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001598 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1599 channelCount <= outputChannelCount) {
1600 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001601 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1602 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001603 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001604 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001605 currentMatchCriteria[3] = outputChannelCount;
1606 }
1607
1608 // sampling rate match
1609 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001610 samplingRate <= outputDesc->getSamplingRate()) {
1611 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001612 }
1613
1614 // performance flags match
1615 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1616
1617 // format match
1618 if (format != AUDIO_FORMAT_INVALID) {
1619 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001620 PolicyAudioPort::kFormatDistanceMax -
1621 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001622 }
1623
1624 // primary output match
1625 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1626
1627 // compare match criteria by priority then value
1628 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1629 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1630 bestMatchCriteria = currentMatchCriteria;
1631 bestOutput = output;
1632
1633 std::stringstream result;
1634 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1635 std::ostream_iterator<int>(result, " "));
1636 ALOGV("%s new bestOutput %d criteria %s",
1637 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001638 }
1639 }
1640
Eric Laurent16c66dd2019-05-01 17:54:10 -07001641 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001642}
1643
Eric Laurent8fc147b2018-07-22 19:13:55 -07001644status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001645{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001646 ALOGV("%s portId %d", __FUNCTION__, portId);
1647
1648 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1649 if (outputDesc == 0) {
1650 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001651 return BAD_VALUE;
1652 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001653 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001654
Eric Laurent8fc147b2018-07-22 19:13:55 -07001655 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001656 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001657
Eric Laurent733ce942017-12-07 12:18:25 -08001658 status_t status = outputDesc->start();
1659 if (status != NO_ERROR) {
1660 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001661 }
1662
Eric Laurent97ac8712018-07-27 18:59:02 -07001663 uint32_t delayMs;
1664 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001665
1666 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001667 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001668 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001669 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001670 if (delayMs != 0) {
1671 usleep(delayMs * 1000);
1672 }
1673
1674 return status;
1675}
1676
Eric Laurent97ac8712018-07-27 18:59:02 -07001677status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1678 const sp<TrackClientDescriptor>& client,
1679 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001680{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001681 // cannot start playback of STREAM_TTS if any other output is being used
1682 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001683
1684 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001685 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001686 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001687 auto clientStrategy = client->strategy();
1688 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001689 if (stream == AUDIO_STREAM_TTS) {
1690 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001691 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001692 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001693 return INVALID_OPERATION;
1694 } else {
1695 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1696 }
1697 } else {
1698 // some playback other than beacon starts
1699 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1700 }
1701
Eric Laurent77305a62016-07-25 16:39:22 -07001702 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001703 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001704 bool force = !outputDesc->isActive() &&
1705 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001706
François Gaffie11d30102018-11-02 16:09:09 +01001707 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001708 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001709 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001710 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001711 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001712 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001713 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001714 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001715 } else {
1716 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001717 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001718 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1719 AUDIO_FORMAT_DEFAULT);
1720 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1721 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001722 }
1723
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001724 // requiresMuteCheck is false when we can bypass mute strategy.
1725 // It covers a common case when there is no materially active audio
1726 // and muting would result in unnecessary delay and dropped audio.
1727 const uint32_t outputLatencyMs = outputDesc->latency();
1728 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1729
Eric Laurente552edb2014-03-10 17:42:56 -07001730 // increment usage count for this stream on the requested output:
1731 // NOTE that the usage count is the same for duplicated output and hardware output which is
1732 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001733 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001734
1735 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001736 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1737 client->isPreferredDeviceForExclusiveUse()) {
1738 // Preferred device may be exclusive, use only if no other active clients on this output
1739 devices = DeviceVector(
1740 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1741 } else {
1742 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1743 }
François Gaffie11d30102018-11-02 16:09:09 +01001744 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001745 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001746 }
1747 }
Eric Laurente552edb2014-03-10 17:42:56 -07001748
François Gaffiec005e562018-11-06 15:04:49 +01001749 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001750 selectOutputForMusicEffects();
1751 }
1752
François Gaffie1c878552018-11-22 16:53:21 +01001753 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001754 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001755 if (devices.isEmpty()) {
1756 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001757 }
François Gaffiec005e562018-11-06 15:04:49 +01001758 bool shouldWait =
1759 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1760 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1761 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001762 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001763 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001764 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001765 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001766 // An output has a shared device if
1767 // - managed by the same hw module
1768 // - supports the currently selected device
1769 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001770 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001771
Eric Laurent77305a62016-07-25 16:39:22 -07001772 // force a device change if any other output is:
1773 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001774 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001775 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001776 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001777 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001778 // change the device currently selected by the other output.
1779 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001780 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001781 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001782 force = true;
1783 }
1784 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001785 // a notification so that audio focus effect can propagate, or that a mute/unmute
1786 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001787 const uint32_t latencyMs = desc->latency();
1788 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1789
1790 if (shouldWait && isActive && (waitMs < latencyMs)) {
1791 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001792 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001793
1794 // Require mute check if another output is on a shared device
1795 // and currently active to have proper drain and avoid pops.
1796 // Note restoring AudioTracks onto this output needs to invoke
1797 // a volume ramp if there is no mute.
1798 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001799 }
1800 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001801
1802 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001803 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001804
Eric Laurente552edb2014-03-10 17:42:56 -07001805 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001806 auto &curves = getVolumeCurves(client->attributes());
1807 checkAndSetVolume(curves, client->volumeSource(),
1808 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001809 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001810 outputDesc->devices().types(), 0 /*delay*/,
1811 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001812
1813 // update the outputs if starting an output with a stream that can affect notification
1814 // routing
1815 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001816
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001817 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001818 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001819 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1820 }
Eric Laurentdc462862016-07-19 12:29:53 -07001821
1822 if (waitMs > muteWaitMs) {
1823 *delayMs = waitMs - muteWaitMs;
1824 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001825
1826 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1827 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1828 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1829 // change occurs after the MixerThread starts and causes a stream volume
1830 // glitch.
1831 //
1832 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001833 }
Eric Laurentdc462862016-07-19 12:29:53 -07001834
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001835 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001836 mEngine->getForceUse(
1837 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001838 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001839 }
1840
Eric Laurent97ac8712018-07-27 18:59:02 -07001841 // Automatically enable the remote submix input when output is started on a re routing mix
1842 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001843 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1844 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001845 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1846 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1847 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001848 "remote-submix",
1849 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001850 }
1851
Eric Laurente552edb2014-03-10 17:42:56 -07001852 return NO_ERROR;
1853}
1854
Eric Laurent8fc147b2018-07-22 19:13:55 -07001855status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001856{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001857 ALOGV("%s portId %d", __FUNCTION__, portId);
1858
1859 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1860 if (outputDesc == 0) {
1861 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001862 return BAD_VALUE;
1863 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001864 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001865
Eric Laurent97ac8712018-07-27 18:59:02 -07001866 ALOGV("stopOutput() output %d, stream %d, session %d",
1867 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001868
Eric Laurent97ac8712018-07-27 18:59:02 -07001869 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001870
Eric Laurent733ce942017-12-07 12:18:25 -08001871 if (status == NO_ERROR ) {
1872 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001873 }
1874 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001875}
1876
Eric Laurent97ac8712018-07-27 18:59:02 -07001877status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1878 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001879{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001880 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001881 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001882 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001883
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001884 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1885
François Gaffie1c878552018-11-22 16:53:21 +01001886 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1887 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001888 // Automatically disable the remote submix input when output is stopped on a
1889 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001890 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001891 if (isSingleDeviceType(
1892 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001893 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001894 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001895 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1896 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001897 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001898 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001899 }
1900 }
1901 bool forceDeviceUpdate = false;
1902 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001903 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001904 forceDeviceUpdate = true;
1905 }
1906
Eric Laurente552edb2014-03-10 17:42:56 -07001907 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001908 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001909
Eric Laurente552edb2014-03-10 17:42:56 -07001910 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001911 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001912 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001913 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001914 // delay the device switch by twice the latency because stopOutput() is executed when
1915 // the track stop() command is received and at that time the audio track buffer can
1916 // still contain data that needs to be drained. The latency only covers the audio HAL
1917 // and kernel buffers. Also the latency does not always include additional delay in the
1918 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001919 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001920
1921 // force restoring the device selection on other active outputs if it differs from the
1922 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001923 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001924 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001925 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001926 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001927 desc->isActive() &&
1928 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001929 (newDevices != desc->devices())) {
1930 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1931 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001932
François Gaffie11d30102018-11-02 16:09:09 +01001933 setOutputDevices(desc, newDevices2, force, delayMs);
1934
Eric Laurent57de36c2016-09-28 16:59:11 -07001935 // re-apply device specific volume if not done by setOutputDevice()
1936 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001937 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001938 }
Eric Laurente552edb2014-03-10 17:42:56 -07001939 }
1940 }
1941 // update the outputs if stopping one with a stream that can affect notification routing
1942 handleNotificationRoutingForStream(stream);
1943 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001944
1945 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1946 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001947 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001948 }
1949
François Gaffiec005e562018-11-06 15:04:49 +01001950 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001951 selectOutputForMusicEffects();
1952 }
Eric Laurente552edb2014-03-10 17:42:56 -07001953 return NO_ERROR;
1954 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001955 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001956 return INVALID_OPERATION;
1957 }
1958}
1959
jiabinbce0c1d2020-10-05 11:20:18 -07001960bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001961{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001962 ALOGV("%s portId %d", __FUNCTION__, portId);
1963
1964 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1965 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001966 // If an output descriptor is closed due to a device routing change,
1967 // then there are race conditions with releaseOutput from tracks
1968 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1969 // destroyed shortly thereafter.
1970 //
1971 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001972 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07001973 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07001974 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001975
1976 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001977
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05301978 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
1979 if (outputDesc->isClientActive(client)) {
1980 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
1981 stopOutput(portId);
1982 }
1983
Eric Laurent8fc147b2018-07-22 19:13:55 -07001984 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1985 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001986 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001987 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07001988 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07001989 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001990 if (--outputDesc->mDirectOpenCount == 0) {
1991 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001992 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001993 }
1994 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05301995
Andy Hung39efb7a2018-09-26 15:39:28 -07001996 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07001997 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
1998 // The output is pending reopened to query dynamic profiles and
1999 // there is no active clients
2000 closeOutput(outputDesc->mIoHandle);
2001 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2002 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2003 if (newOutputDesc == nullptr) {
2004 ALOGE("%s failed to open output", __func__);
2005 }
2006 return true;
2007 }
2008 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002009}
2010
Eric Laurentcaf7f482014-11-25 17:50:47 -08002011status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2012 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002013 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002014 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002015 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002016 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002017 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002018 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002019 input_type_t *inputType,
2020 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002021{
François Gaffiec005e562018-11-06 15:04:49 +01002022 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2023 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2024 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002025
Eric Laurentad2e7b92017-09-14 20:06:42 -07002026 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002027 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002028 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002029 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002030 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002031 sp<AudioInputDescriptor> inputDesc;
2032 sp<RecordClientDescriptor> clientDesc;
2033 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002034 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035
2036 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2037 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2038 return INVALID_OPERATION;
2039 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002040
Francois Gaffie716e1432019-01-14 16:58:59 +01002041 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2042 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002043 }
2044
Paul McLean466dc8e2015-04-17 13:15:36 -06002045 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002046 sp<DeviceDescriptor> explicitRoutingDevice =
2047 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002048
Eric Laurentad2e7b92017-09-14 20:06:42 -07002049 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2050 // possible
2051 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2052 *input != AUDIO_IO_HANDLE_NONE) {
2053 ssize_t index = mInputs.indexOfKey(*input);
2054 if (index < 0) {
2055 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2056 status = BAD_VALUE;
2057 goto error;
2058 }
2059 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002060 RecordClientVector clients = inputDesc->getClientsForSession(session);
2061 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002062 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2063 status = BAD_VALUE;
2064 goto error;
2065 }
2066 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2067 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002068 // corresponds to a new client and is only permitted from the same UID.
2069 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002070 if (clients.size() > 1) {
2071 for (const auto& client : clients) {
2072 // The client map is ordered by key values (portId) and portIds are allocated
2073 // incrementaly. So the first client in this list is the one opened by audio flinger
2074 // when the mmap stream is created and should be ignored as it does not correspond
2075 // to an actual client
2076 if (client == *clients.cbegin()) {
2077 continue;
2078 }
2079 if (uid != client->uid() && !client->isSilenced()) {
2080 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2081 uid, client->portId(), client->uid());
2082 status = INVALID_OPERATION;
2083 goto error;
2084 }
Eric Laurent331679c2018-04-16 17:03:16 -07002085 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002086 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002087 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002088 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002089
Eric Laurent8f42ea12018-08-08 09:08:25 -07002090 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002091 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002092 }
2093
2094 *input = AUDIO_IO_HANDLE_NONE;
2095 *inputType = API_INPUT_INVALID;
2096
Francois Gaffie716e1432019-01-14 16:58:59 +01002097 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002098
Francois Gaffie716e1432019-01-14 16:58:59 +01002099 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2100 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2101 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002102 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002103 ALOGW("%s could not find input mix for attr %s",
2104 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002105 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002106 }
jiabinc1de2df2019-05-07 14:26:40 -07002107 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2108 String8(attr->tags + strlen("addr=")),
2109 AUDIO_FORMAT_DEFAULT);
2110 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002111 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002112 __func__, attributes.source, attributes.tags);
2113 status = BAD_VALUE;
2114 goto error;
2115 }
2116
Kevin Rocard25f9b052019-02-27 15:08:54 -08002117 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2118 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2119 } else {
2120 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2121 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002122 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002123 if (explicitRoutingDevice != nullptr) {
2124 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002125 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002126 // Prevent from storing invalid requested device id in clients
2127 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002128 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002129 }
François Gaffie11d30102018-11-02 16:09:09 +01002130 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002131 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002132 status = BAD_VALUE;
2133 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002134 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002135 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002136 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2137 // there is an external policy, but this input is attached to a mix of recorders,
2138 // meaning it receives audio injected into the framework, so the recorder doesn't
2139 // know about it and is therefore considered "legacy"
2140 *inputType = API_INPUT_LEGACY;
2141 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002142 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002143 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002144 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002145 } else {
2146 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002147 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002148
Eric Laurent599c7582015-12-07 18:05:55 -08002149 }
2150
François Gaffiec005e562018-11-06 15:04:49 +01002151 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002152 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002153 status = INVALID_OPERATION;
2154 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002155 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002156
Eric Laurent8f42ea12018-08-08 09:08:25 -07002157exit:
2158
François Gaffiec005e562018-11-06 15:04:49 +01002159 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2160 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002161
Francois Gaffie716e1432019-01-14 16:58:59 +01002162 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002163 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002164 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165
Mikhail Naganov2996f672019-04-18 12:29:59 -07002166 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002167 requestedDeviceId, attributes.source, flags,
2168 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002169 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002170 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002171
2172 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2173 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002174
Eric Laurent599c7582015-12-07 18:05:55 -08002175 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002176
2177error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002178 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002179}
2180
2181
François Gaffie11d30102018-11-02 16:09:09 +01002182audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002183 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002184 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002185 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002186 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002187 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002188{
2189 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002190 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002191 bool isSoundTrigger = false;
2192
François Gaffiec005e562018-11-06 15:04:49 +01002193 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002194 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2195 if (index >= 0) {
2196 input = mSoundTriggerSessions.valueFor(session);
2197 isSoundTrigger = true;
2198 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2199 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2200 } else {
2201 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002202 }
François Gaffiec005e562018-11-06 15:04:49 +01002203 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002204 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002205 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002206 }
2207
Andy Hungf129b032015-04-07 13:45:50 -07002208 // find a compatible input profile (not necessarily identical in parameters)
2209 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002210 // sampling rate and flags may be updated by getInputProfile
2211 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2212 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002213 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002214 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002215 audio_input_flags_t profileFlags = flags;
2216 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002217 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002218 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002219 profileFlags);
2220 if (profile != 0) {
2221 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002222 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2223 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002224 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2225 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2226 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002227 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2228 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2229 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002230 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002231 }
Eric Laurente552edb2014-03-10 17:42:56 -07002232 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002233 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002234 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002235 if (samplingRate == 0) {
2236 samplingRate = profileSamplingRate;
2237 }
Eric Laurente552edb2014-03-10 17:42:56 -07002238
Eric Laurent322b4d22015-04-03 15:57:54 -07002239 if (profile->getModuleHandle() == 0) {
2240 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002241 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002242 }
2243
Eric Laurent3974e3b2017-12-07 17:58:43 -08002244 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002245 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002246 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002247 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002248 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002249 continue;
2250 }
2251 // if sound trigger, reuse input if used by other sound trigger on same session
2252 // else
2253 // reuse input if active client app is not in IDLE state
2254 //
2255 RecordClientVector clients = desc->clientsList();
2256 bool doClose = false;
2257 for (const auto& client : clients) {
2258 if (isSoundTrigger != client->isSoundTrigger()) {
2259 continue;
2260 }
2261 if (client->isSoundTrigger()) {
2262 if (session == client->session()) {
2263 return desc->mIoHandle;
2264 }
2265 continue;
2266 }
2267 if (client->active() && client->appState() != APP_STATE_IDLE) {
2268 return desc->mIoHandle;
2269 }
2270 doClose = true;
2271 }
2272 if (doClose) {
2273 closeInput(desc->mIoHandle);
2274 } else {
2275 i++;
2276 }
2277 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002278 }
2279
Eric Laurentfe231122017-11-17 17:48:06 -08002280 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002281
Eric Laurentfe231122017-11-17 17:48:06 -08002282 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2283 lConfig.sample_rate = profileSamplingRate;
2284 lConfig.channel_mask = profileChannelMask;
2285 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002286
François Gaffie11d30102018-11-02 16:09:09 +01002287 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002288
2289 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002290 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002291 (profileSamplingRate != lConfig.sample_rate) ||
2292 !audio_formats_match(profileFormat, lConfig.format) ||
2293 (profileChannelMask != lConfig.channel_mask)) {
2294 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002295 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002296 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002297 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002298 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002299 }
Eric Laurent599c7582015-12-07 18:05:55 -08002300 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002301 }
2302
Eric Laurentc722f302014-12-10 11:21:49 -08002303 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002304
Eric Laurent599c7582015-12-07 18:05:55 -08002305 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002306 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002307
Eric Laurent599c7582015-12-07 18:05:55 -08002308 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002309}
2310
Eric Laurent4eb58f12018-12-07 16:41:02 -08002311status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002312{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002313 ALOGV("%s portId %d", __FUNCTION__, portId);
2314
2315 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2316 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002317 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002318 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002319 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002320 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002321 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002322 if (client->active()) {
2323 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2324 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002325 }
2326
Eric Laurent8f42ea12018-08-08 09:08:25 -07002327 audio_session_t session = client->session();
2328
Eric Laurent4eb58f12018-12-07 16:41:02 -08002329 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002330
Eric Laurent4eb58f12018-12-07 16:41:02 -08002331 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002332
Eric Laurent4eb58f12018-12-07 16:41:02 -08002333 status_t status = inputDesc->start();
2334 if (status != NO_ERROR) {
2335 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002336 }
Eric Laurente552edb2014-03-10 17:42:56 -07002337
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002338 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002339 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002340 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002341
Eric Laurent8f42ea12018-08-08 09:08:25 -07002342 // indicate active capture to sound trigger service if starting capture from a mic on
2343 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002344 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002345 if (device != nullptr) {
2346 status = setInputDevice(input, device, true /* force */);
2347 } else {
2348 ALOGW("%s no new input device can be found for descriptor %d",
2349 __FUNCTION__, inputDesc->getId());
2350 status = BAD_VALUE;
2351 }
Eric Laurente552edb2014-03-10 17:42:56 -07002352
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002353 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002354 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002355 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002356 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002357 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2358 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002359 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002360 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002361
François Gaffie11d30102018-11-02 16:09:09 +01002362 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2363 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002364 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002365 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002366 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002367
Eric Laurent8f42ea12018-08-08 09:08:25 -07002368 // automatically enable the remote submix output when input is started if not
2369 // used by a policy mix of type MIX_TYPE_RECORDERS
2370 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002371 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002372 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002373 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002374 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002375 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2376 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002377 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002378 if (address != "") {
2379 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2380 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002381 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002382 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002383 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002384 } else if (status != NO_ERROR) {
2385 // Restore client activity state.
2386 inputDesc->setClientActive(client, false);
2387 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002388 }
2389
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002390 ALOGV("%s input %d source = %d status = %d exit",
2391 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002392
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002393 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002394}
2395
Eric Laurent8fc147b2018-07-22 19:13:55 -07002396status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002397{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002398 ALOGV("%s portId %d", __FUNCTION__, portId);
2399
2400 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2401 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002402 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002403 return BAD_VALUE;
2404 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002405 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002406 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002407 if (!client->active()) {
2408 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002409 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002410 }
2411
Eric Laurent8f42ea12018-08-08 09:08:25 -07002412 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002413
Eric Laurent8f42ea12018-08-08 09:08:25 -07002414 inputDesc->stop();
2415 if (inputDesc->isActive()) {
2416 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2417 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002418 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002419 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002420 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002421 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2422 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002423 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002424 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002425
2426 // automatically disable the remote submix output when input is stopped if not
2427 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002428 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002429 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002430 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002431 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002432 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2433 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002434 }
2435 if (address != "") {
2436 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2437 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002438 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002439 }
2440 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002441 resetInputDevice(input);
2442
2443 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2444 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002445 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2446 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002447 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002448 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002449 }
2450 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002451 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002452 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002453}
2454
Eric Laurent8fc147b2018-07-22 19:13:55 -07002455void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002456{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002457 ALOGV("%s portId %d", __FUNCTION__, portId);
2458
2459 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2460 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002461 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002462 return;
2463 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002464 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002465 audio_io_handle_t input = inputDesc->mIoHandle;
2466
Eric Laurent8f42ea12018-08-08 09:08:25 -07002467 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002468
Andy Hung39efb7a2018-09-26 15:39:28 -07002469 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002470
Andy Hung39efb7a2018-09-26 15:39:28 -07002471 if (inputDesc->getClientCount() > 0) {
2472 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002473 return;
2474 }
2475
Eric Laurent05b90f82014-08-27 15:32:29 -07002476 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002477 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002478 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002479}
2480
Eric Laurent8f42ea12018-08-08 09:08:25 -07002481void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002482{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002483 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002484
2485 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002486 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002487 }
2488}
2489
Eric Laurent8f42ea12018-08-08 09:08:25 -07002490void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2491{
2492 stopInput(portId);
2493 releaseInput(portId);
2494}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002495
Eric Laurent0dd51852019-04-19 18:18:58 -07002496void AudioPolicyManager::checkCloseInputs() {
2497 // After connecting or disconnecting an input device, close input if:
2498 // - it has no client (was just opened to check profile) OR
2499 // - none of its supported devices are connected anymore OR
2500 // - one of its clients cannot be routed to one of its supported
2501 // devices anymore. Otherwise update device selection
2502 std::vector<audio_io_handle_t> inputsToClose;
2503 for (size_t i = 0; i < mInputs.size(); i++) {
2504 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2505 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002506 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002507 inputsToClose.push_back(mInputs.keyAt(i));
2508 } else {
2509 bool close = false;
2510 for (const auto& client : input->clientsList()) {
2511 sp<DeviceDescriptor> device =
2512 mEngine->getInputDeviceForAttributes(client->attributes());
2513 if (!input->supportedDevices().contains(device)) {
2514 close = true;
2515 break;
2516 }
2517 }
2518 if (close) {
2519 inputsToClose.push_back(mInputs.keyAt(i));
2520 } else {
2521 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2522 }
2523 }
2524 }
2525
2526 for (const audio_io_handle_t handle : inputsToClose) {
2527 ALOGV("%s closing input %d", __func__, handle);
2528 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002529 }
Eric Laurentd4692962014-05-05 18:13:44 -07002530}
2531
François Gaffie251c7f02018-11-07 10:41:08 +01002532void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002533{
2534 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002535 if (indexMin < 0 || indexMax < 0) {
2536 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2537 return;
2538 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002539 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002540
2541 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002542 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2543 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002544 continue;
2545 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002546 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002547 }
Eric Laurente552edb2014-03-10 17:42:56 -07002548}
2549
Eric Laurente0720872014-03-11 09:30:41 -07002550status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002551 int index,
2552 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002553{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002554 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002555 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2556 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2557 return NO_ERROR;
2558 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002559 ALOGV("%s: stream %s attributes=%s", __func__,
2560 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002561 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002562}
2563
Eric Laurente0720872014-03-11 09:30:41 -07002564status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002565 int *index,
2566 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002567{
François Gaffiec005e562018-11-06 15:04:49 +01002568 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2569 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002570 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002571 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002572 deviceTypes = mEngine->getOutputDevicesForStream(
2573 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002574 }
jiabin9a3361e2019-10-01 09:38:30 -07002575 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002576}
2577
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002578status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002579 int index,
2580 audio_devices_t device)
2581{
2582 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002583 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2584 if (group == VOLUME_GROUP_NONE) {
2585 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002586 return BAD_VALUE;
2587 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002588 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002589 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002590 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002591 VolumeSource vs = toVolumeSource(group);
2592 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2593
2594 status = setVolumeCurveIndex(index, device, curves);
2595 if (status != NO_ERROR) {
2596 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2597 return status;
2598 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002599
jiabin9a3361e2019-10-01 09:38:30 -07002600 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002601 auto curCurvAttrs = curves.getAttributes();
2602 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2603 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002604 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002605 } else if (!curves.getStreamTypes().empty()) {
2606 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002607 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002608 } else {
2609 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2610 return BAD_VALUE;
2611 }
jiabin9a3361e2019-10-01 09:38:30 -07002612 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2613 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002614
François Gaffiecfe17322018-11-07 13:41:29 +01002615 // update volume on all outputs and streams matching the following:
2616 // - The requested stream (or a stream matching for volume control) is active on the output
2617 // - The device (or devices) selected by the engine for this stream includes
2618 // the requested device
2619 // - For non default requested device, currently selected device on the output is either the
2620 // requested device or one of the devices selected by the engine for this stream
2621 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2622 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002623 for (size_t i = 0; i < mOutputs.size(); i++) {
2624 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002625 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002626
jiabin9a3361e2019-10-01 09:38:30 -07002627 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2628 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002629 }
François Gaffieed91f582020-01-31 10:35:37 +01002630 if (!(desc->isActive(vs) || isInCall())) {
2631 continue;
2632 }
2633 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2634 curDevices.find(device) == curDevices.end()) {
2635 continue;
2636 }
2637 bool applyVolume = false;
2638 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2639 curSrcDevices.insert(device);
2640 applyVolume = (curSrcDevices.find(
2641 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2642 } else {
2643 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2644 }
2645 if (!applyVolume) {
2646 continue; // next output
2647 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002648 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2649 // If a higher priority strategy is active, and the output is routed to a device with a
2650 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002651 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002652 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002653 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2654 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2655 false /*preferredDevice*/);
2656 if (activeClients.empty()) {
2657 continue;
2658 }
2659 bool isPreempted = false;
2660 bool isHigherPriority = productStrategy < strategy;
2661 for (const auto &client : activeClients) {
2662 if (isHigherPriority && (client->volumeSource() != vs)) {
2663 ALOGV("%s: Strategy=%d (\nrequester:\n"
2664 " group %d, volumeGroup=%d attributes=%s)\n"
2665 " higher priority source active:\n"
2666 " volumeGroup=%d attributes=%s) \n"
2667 " on output %zu, bailing out", __func__, productStrategy,
2668 group, group, toString(attributes).c_str(),
2669 client->volumeSource(), toString(client->attributes()).c_str(), i);
2670 applyVolume = false;
2671 isPreempted = true;
2672 break;
2673 }
2674 // However, continue for loop to ensure no higher prio clients running on output
2675 if (client->volumeSource() == vs) {
2676 applyVolume = true;
2677 }
2678 }
2679 if (isPreempted || applyVolume) {
2680 break;
2681 }
2682 }
2683 if (!applyVolume) {
2684 continue; // next output
2685 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002686 }
François Gaffieed91f582020-01-31 10:35:37 +01002687 //FIXME: workaround for truncated touch sounds
2688 // delayed volume change for system stream to be removed when the problem is
2689 // handled by system UI
2690 status_t volStatus = checkAndSetVolume(
2691 curves, vs, index, desc, curDevices,
2692 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2693 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2694 if (volStatus != NO_ERROR) {
2695 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002696 }
2697 }
François Gaffiecfe17322018-11-07 13:41:29 +01002698 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2699 return status;
2700}
2701
François Gaffieaaac0fd2018-11-22 17:56:39 +01002702status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002703 audio_devices_t device,
2704 IVolumeCurves &volumeCurves)
2705{
2706 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2707 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002708 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2709 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002710 (index > volumeCurves.getVolumeIndexMax())) {
2711 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2712 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2713 return BAD_VALUE;
2714 }
2715 if (!audio_is_output_device(device)) {
2716 return BAD_VALUE;
2717 }
2718
2719 // Force max volume if stream cannot be muted
2720 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2721
François Gaffieaaac0fd2018-11-22 17:56:39 +01002722 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002723 volumeCurves.addCurrentVolumeIndex(device, index);
2724 return NO_ERROR;
2725}
2726
2727status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2728 int &index,
2729 audio_devices_t device)
2730{
2731 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2732 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002733 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002734 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002735 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2736 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002737 }
jiabin9a3361e2019-10-01 09:38:30 -07002738 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002739}
2740
2741status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2742 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002743 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002744{
jiabin9a3361e2019-10-01 09:38:30 -07002745 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002746 return BAD_VALUE;
2747 }
jiabin9a3361e2019-10-01 09:38:30 -07002748 index = curves.getVolumeIndex(deviceTypes);
2749 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002750 return NO_ERROR;
2751}
2752
2753status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2754 int &index)
2755{
2756 index = getVolumeCurves(attr).getVolumeIndexMin();
2757 return NO_ERROR;
2758}
2759
2760status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2761 int &index)
2762{
2763 index = getVolumeCurves(attr).getVolumeIndexMax();
2764 return NO_ERROR;
2765}
2766
Eric Laurent36829f92017-04-07 19:04:42 -07002767audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002768{
2769 // select one output among several suitable for global effects.
2770 // The priority is as follows:
2771 // 1: An offloaded output. If the effect ends up not being offloadable,
2772 // AudioFlinger will invalidate the track and the offloaded output
2773 // will be closed causing the effect to be moved to a PCM output.
2774 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002775 // 3: The primary output
2776 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002777
François Gaffiec005e562018-11-06 15:04:49 +01002778 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2779 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002780 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002781
Eric Laurent36829f92017-04-07 19:04:42 -07002782 if (outputs.size() == 0) {
2783 return AUDIO_IO_HANDLE_NONE;
2784 }
Eric Laurente552edb2014-03-10 17:42:56 -07002785
Eric Laurent36829f92017-04-07 19:04:42 -07002786 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2787 bool activeOnly = true;
2788
2789 while (output == AUDIO_IO_HANDLE_NONE) {
2790 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2791 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2792 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2793
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002794 for (audio_io_handle_t output : outputs) {
2795 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002796 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002797 continue;
2798 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002799 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2800 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002801 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002802 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002803 }
2804 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002805 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002806 }
2807 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002808 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002809 }
2810 }
2811 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2812 output = outputOffloaded;
2813 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2814 output = outputDeepBuffer;
2815 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2816 output = outputPrimary;
2817 } else {
2818 output = outputs[0];
2819 }
2820 activeOnly = false;
2821 }
2822
2823 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002824 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002825 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2826 mMusicEffectOutput = output;
2827 }
2828
2829 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002830 return output;
2831}
2832
Eric Laurent36829f92017-04-07 19:04:42 -07002833audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2834{
2835 return selectOutputForMusicEffects();
2836}
2837
Eric Laurente0720872014-03-11 09:30:41 -07002838status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002839 audio_io_handle_t io,
2840 uint32_t strategy,
2841 int session,
2842 int id)
2843{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002844 if (session != AUDIO_SESSION_DEVICE) {
2845 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002846 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002847 index = mInputs.indexOfKey(io);
2848 if (index < 0) {
2849 ALOGW("registerEffect() unknown io %d", io);
2850 return INVALID_OPERATION;
2851 }
Eric Laurente552edb2014-03-10 17:42:56 -07002852 }
2853 }
François Gaffiec005e562018-11-06 15:04:49 +01002854 return mEffects.registerEffect(desc, io, session, id,
2855 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2856 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002857}
2858
Eric Laurentc241b0d2018-11-28 09:08:49 -08002859status_t AudioPolicyManager::unregisterEffect(int id)
2860{
2861 if (mEffects.getEffect(id) == nullptr) {
2862 return INVALID_OPERATION;
2863 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002864 if (mEffects.isEffectEnabled(id)) {
2865 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2866 setEffectEnabled(id, false);
2867 }
2868 return mEffects.unregisterEffect(id);
2869}
2870
2871status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2872{
2873 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2874 if (effect == nullptr) {
2875 return INVALID_OPERATION;
2876 }
2877
2878 status_t status = mEffects.setEffectEnabled(id, enabled);
2879 if (status == NO_ERROR) {
2880 mInputs.trackEffectEnabled(effect, enabled);
2881 }
2882 return status;
2883}
2884
Eric Laurent6c796322019-04-09 14:13:17 -07002885
2886status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2887{
2888 mEffects.moveEffects(ids, io);
2889 return NO_ERROR;
2890}
2891
Eric Laurentc75307b2015-03-17 15:29:32 -07002892bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2893{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002894 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002895}
2896
2897bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2898{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002899 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002900}
2901
Eric Laurente0720872014-03-11 09:30:41 -07002902bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002903{
2904 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002905 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002906 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002907 return true;
2908 }
2909 }
2910 return false;
2911}
2912
Eric Laurent275e8e92014-11-30 15:14:47 -08002913// Register a list of custom mixes with their attributes and format.
2914// When a mix is registered, corresponding input and output profiles are
2915// added to the remote submix hw module. The profile contains only the
2916// parameters (sampling rate, format...) specified by the mix.
2917// The corresponding input remote submix device is also connected.
2918//
2919// When a remote submix device is connected, the address is checked to select the
2920// appropriate profile and the corresponding input or output stream is opened.
2921//
2922// When capture starts, getInputForAttr() will:
2923// - 1 look for a mix matching the address passed in attribtutes tags if any
2924// - 2 if none found, getDeviceForInputSource() will:
2925// - 2.1 look for a mix matching the attributes source
2926// - 2.2 if none found, default to device selection by policy rules
2927// At this time, the corresponding output remote submix device is also connected
2928// and active playback use cases can be transferred to this mix if needed when reconnecting
2929// after AudioTracks are invalidated
2930//
2931// When playback starts, getOutputForAttr() will:
2932// - 1 look for a mix matching the address passed in attribtutes tags if any
2933// - 2 if none found, look for a mix matching the attributes usage
2934// - 3 if none found, default to device and output selection by policy rules.
2935
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002936status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002937{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002938 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2939 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002940 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002941 sp<HwModule> rSubmixModule;
2942 // examine each mix's route type
2943 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002944 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002945 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2946 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2947 ALOGE("Unsupported Policy Mix %zu of %zu: "
2948 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2949 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002950 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002951 break;
2952 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002953 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2954 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002955 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002956 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2957 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002958 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002959 rSubmixModule = mHwModules.getModuleFromName(
2960 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2961 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002962 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002963 i);
2964 res = INVALID_OPERATION;
2965 break;
2966 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002967 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002968
Eric Laurent97ac8712018-07-27 18:59:02 -07002969 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002970 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07002971 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002972 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002973 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2974 } else {
2975 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2976 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07002977 }
François Gaffie036e1e92015-03-19 10:16:24 +01002978
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002979 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002980 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002981 res = INVALID_OPERATION;
2982 break;
2983 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002984 audio_config_t outputConfig = mix.mFormat;
2985 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07002986 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
2987 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002988 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2989 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07002990 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002991 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07002992 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002993 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002994
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002995 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07002996 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2997 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2998 ALOGE("Failed to set remote submix device available, type %u, address %s",
2999 mix.mDeviceType, address.string());
3000 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003001 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003002 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3003 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003004 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003005 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003006 i, mixes.size(), type, address.string());
3007
3008 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3009 mix.mDeviceType, mix.mDeviceAddress,
3010 String8(), AUDIO_FORMAT_DEFAULT);
3011 if (device == nullptr) {
3012 res = INVALID_OPERATION;
3013 break;
3014 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003015
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003016 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003017 // First try to find an already opened output supporting the device
3018 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003019 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003020
Eric Laurentc529cf62020-04-17 18:19:10 -07003021 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003022 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003023 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3024 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003025 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003026 } else {
3027 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003028 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003029 }
3030 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003031 // If no output found, try to find a direct output profile supporting the device
3032 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3033 sp<HwModule> module = mHwModules[i];
3034 for (size_t j = 0;
3035 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3036 j++) {
3037 sp<IOProfile> profile = module->getOutputProfiles()[j];
3038 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3039 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3040 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3041 address.string());
3042 res = INVALID_OPERATION;
3043 } else {
3044 foundOutput = true;
3045 }
3046 }
3047 }
3048 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003049 if (res != NO_ERROR) {
3050 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003051 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003052 res = INVALID_OPERATION;
3053 break;
3054 } else if (!foundOutput) {
3055 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003056 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003057 res = INVALID_OPERATION;
3058 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003059 } else {
3060 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003061 }
Eric Laurentc722f302014-12-10 11:21:49 -08003062 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003063 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003064 if (res != NO_ERROR) {
3065 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003066 } else if (checkOutputs) {
3067 checkForDeviceAndOutputChanges();
3068 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003069 }
3070 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003071}
3072
3073status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3074{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003075 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003076 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003077 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003078 sp<HwModule> rSubmixModule;
3079 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003080 for (const auto& mix : mixes) {
3081 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003082
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003083 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003084 rSubmixModule = mHwModules.getModuleFromName(
3085 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3086 if (rSubmixModule == 0) {
3087 res = INVALID_OPERATION;
3088 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003089 }
3090 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003091
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003092 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003093
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003094 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003095 res = INVALID_OPERATION;
3096 continue;
3097 }
3098
Kevin Rocard04ed0462019-05-02 17:53:24 -07003099 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3100 if (getDeviceConnectionState(device, address.string()) ==
3101 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3102 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3103 address.string(), "remote-submix",
3104 AUDIO_FORMAT_DEFAULT);
3105 if (res != OK) {
3106 ALOGE("Error making RemoteSubmix device unavailable for mix "
3107 "with type %d, address %s", device, address.string());
3108 }
3109 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003110 }
jiabin5740f082019-08-19 15:08:30 -07003111 rSubmixModule->removeOutputProfile(address.c_str());
3112 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003113
Kevin Rocard153f92d2018-12-18 18:33:28 -08003114 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003115 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003116 res = INVALID_OPERATION;
3117 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003118 } else {
3119 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003120 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003121 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003122 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003123 if (res == NO_ERROR && checkOutputs) {
3124 checkForDeviceAndOutputChanges();
3125 updateCallAndOutputRouting();
3126 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003127 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003128}
3129
Mikhail Naganov100f0122018-11-29 11:22:16 -08003130void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3131{
3132 size_t i = 0;
3133 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3134 for (const auto& fmt : mManualSurroundFormats) {
3135 if (i++ != 0) dst->append(", ");
3136 std::string sfmt;
3137 FormatConverter::toString(fmt, sfmt);
3138 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3139 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3140 }
3141}
3142
Eric Laurentc529cf62020-04-17 18:19:10 -07003143// Returns true if all devices types match the predicate and are supported by one HW module
3144bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003145 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003146 std::function<bool(audio_devices_t)> predicate,
3147 const char *context) {
3148 for (size_t i = 0; i < devices.size(); i++) {
3149 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003150 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003151 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003152 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003153 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003154 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003155 return false;
3156 }
3157 }
3158 return true;
3159}
3160
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003161status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003162 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003163 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003164 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3165 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003166 }
3167 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003168 if (res != NO_ERROR) {
3169 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3170 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003171 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003172
3173 checkForDeviceAndOutputChanges();
3174 updateCallAndOutputRouting();
3175
3176 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003177}
3178
3179status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3180 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003181 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3182 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003183 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003184 __FUNCTION__, uid);
3185 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003186 }
3187
Eric Laurentc529cf62020-04-17 18:19:10 -07003188 checkForDeviceAndOutputChanges();
3189 updateCallAndOutputRouting();
3190
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003191 return res;
3192}
3193
Eric Laurent2517af32020-11-25 15:31:27 +01003194
jiabin0a488932020-08-07 17:32:40 -07003195status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3196 device_role_t role,
3197 const AudioDeviceTypeAddrVector &devices) {
3198 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3199 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003200
Eric Laurentc529cf62020-04-17 18:19:10 -07003201 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003202 return BAD_VALUE;
3203 }
jiabin0a488932020-08-07 17:32:40 -07003204 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003205 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003206 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3207 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003208 return status;
3209 }
3210
3211 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003212
3213 bool forceVolumeReeval = false;
3214 // FIXME: workaround for truncated touch sounds
3215 // to be removed when the problem is handled by system UI
3216 uint32_t delayMs = 0;
3217 if (strategy == mCommunnicationStrategy) {
3218 forceVolumeReeval = true;
3219 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3220 updateInputRouting();
3221 }
3222 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003223
3224 return NO_ERROR;
3225}
3226
3227void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3228{
3229 uint32_t waitMs = 0;
3230 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3231 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3232 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003233 // Only apply special touch sound delay once
3234 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003235 }
3236 for (size_t i = 0; i < mOutputs.size(); i++) {
3237 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3238 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3239 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3240 // As done in setDeviceConnectionState, we could also fix default device issue by
3241 // preventing the force re-routing in case of default dev that distinguishes on address.
3242 // Let's give back to engine full device choice decision however.
3243 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003244 // Only apply special touch sound delay once
3245 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003246 }
3247 if (forceVolumeReeval && !newDevices.isEmpty()) {
3248 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3249 }
3250 }
3251}
3252
Eric Laurent2517af32020-11-25 15:31:27 +01003253void AudioPolicyManager::updateInputRouting() {
3254 for (const auto& activeDesc : mInputs.getActiveInputs()) {
3255 auto newDevice = getNewInputDevice(activeDesc);
3256 // Force new input selection if the new device can not be reached via current input
3257 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3258 setInputDevice(activeDesc->mIoHandle, newDevice);
3259 } else {
3260 closeInput(activeDesc->mIoHandle);
3261 }
3262 }
3263}
3264
jiabin0a488932020-08-07 17:32:40 -07003265status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3266 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003267{
jiabin0a488932020-08-07 17:32:40 -07003268 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003269
jiabin0a488932020-08-07 17:32:40 -07003270 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003271 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003272 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3273 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003274 return status;
3275 }
3276
3277 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003278
3279 bool forceVolumeReeval = false;
3280 // FIXME: workaround for truncated touch sounds
3281 // to be removed when the problem is handled by system UI
3282 uint32_t delayMs = 0;
3283 if (strategy == mCommunnicationStrategy) {
3284 forceVolumeReeval = true;
3285 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3286 updateInputRouting();
3287 }
3288 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003289
3290 return NO_ERROR;
3291}
3292
jiabin0a488932020-08-07 17:32:40 -07003293status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3294 device_role_t role,
3295 AudioDeviceTypeAddrVector &devices) {
3296 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003297}
3298
Jiabin Huang3b98d322020-09-03 17:54:16 +00003299status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3300 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3301 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3302 dumpAudioDeviceTypeAddrVector(devices).c_str());
3303
Mikhail Naganov55773032020-10-01 15:08:13 -07003304 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003305 return BAD_VALUE;
3306 }
3307 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3308 ALOGW_IF(status != NO_ERROR,
3309 "Engine could not set preferred devices %s for audio source %d role %d",
3310 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3311
3312 return status;
3313}
3314
3315status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3316 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3317 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3318 dumpAudioDeviceTypeAddrVector(devices).c_str());
3319
Mikhail Naganov55773032020-10-01 15:08:13 -07003320 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003321 return BAD_VALUE;
3322 }
3323 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3324 ALOGW_IF(status != NO_ERROR,
3325 "Engine could not add preferred devices %s for audio source %d role %d",
3326 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3327
Eric Laurent2517af32020-11-25 15:31:27 +01003328 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003329 return status;
3330}
3331
3332status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3333 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3334{
3335 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3336 dumpAudioDeviceTypeAddrVector(devices).c_str());
3337
Mikhail Naganov55773032020-10-01 15:08:13 -07003338 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003339 return BAD_VALUE;
3340 }
3341
3342 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3343 audioSource, role, devices);
3344 ALOGW_IF(status != NO_ERROR,
3345 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3346
Eric Laurent2517af32020-11-25 15:31:27 +01003347 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003348 return status;
3349}
3350
3351status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3352 device_role_t role) {
3353 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3354
3355 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3356 ALOGW_IF(status != NO_ERROR,
3357 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3358
Eric Laurent2517af32020-11-25 15:31:27 +01003359 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003360 return status;
3361}
3362
3363status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3364 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3365 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3366}
3367
Oscar Azucena90e77632019-11-27 17:12:28 -08003368status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003369 const AudioDeviceTypeAddrVector& devices) {
3370 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003371 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3372 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003373 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003374 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3375 if (status != NO_ERROR) {
3376 ALOGE("%s() could not set device affinity for userId %d",
3377 __FUNCTION__, userId);
3378 return status;
3379 }
3380
3381 // reevaluate outputs for all devices
3382 checkForDeviceAndOutputChanges();
3383 updateCallAndOutputRouting();
3384
3385 return NO_ERROR;
3386}
3387
3388status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3389 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3390 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3391 if (status != NO_ERROR) {
3392 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3393 __FUNCTION__, userId);
3394 return status;
3395 }
3396
3397 // reevaluate outputs for all devices
3398 checkForDeviceAndOutputChanges();
3399 updateCallAndOutputRouting();
3400
3401 return NO_ERROR;
3402}
3403
Andy Hungc29d82b2018-10-05 12:23:17 -07003404void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003405{
Andy Hungc29d82b2018-10-05 12:23:17 -07003406 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3407 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003408 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003409 std::string stateLiteral;
3410 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003411 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003412 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3413 "communications", "media", "record", "dock", "system",
3414 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3415 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3416 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003417 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3418 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3419 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3420 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3421 dst->append(" (MANUAL: ");
3422 dumpManualSurroundFormats(dst);
3423 dst->append(")");
3424 }
3425 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003426 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003427 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3428 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003429 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003430 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003431
Andy Hungc29d82b2018-10-05 12:23:17 -07003432 mAvailableOutputDevices.dump(dst, String8("Available output"));
3433 mAvailableInputDevices.dump(dst, String8("Available input"));
3434 mHwModulesAll.dump(dst);
3435 mOutputs.dump(dst);
3436 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003437 mEffects.dump(dst);
3438 mAudioPatches.dump(dst);
3439 mPolicyMixes.dump(dst);
3440 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003441
Kevin Rocardb99cc752019-03-21 20:52:24 -07003442 dst->appendFormat(" AllowedCapturePolicies:\n");
3443 for (auto& policy : mAllowedCapturePolicies) {
3444 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3445 }
3446
François Gaffiec005e562018-11-06 15:04:49 +01003447 dst->appendFormat("\nPolicy Engine dump:\n");
3448 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003449}
3450
3451status_t AudioPolicyManager::dump(int fd)
3452{
3453 String8 result;
3454 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003455 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003456 return NO_ERROR;
3457}
3458
Kevin Rocardb99cc752019-03-21 20:52:24 -07003459status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3460{
3461 mAllowedCapturePolicies[uid] = capturePolicy;
3462 return NO_ERROR;
3463}
3464
Eric Laurente552edb2014-03-10 17:42:56 -07003465// This function checks for the parameters which can be offloaded.
3466// This can be enhanced depending on the capability of the DSP and policy
3467// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003468audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003469{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003470 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003471 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003472 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003473 offloadInfo.format,
3474 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3475 offloadInfo.has_video);
3476
Andy Hung2ddee192015-12-18 17:34:44 -08003477 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003478 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003479 }
3480
Eric Laurente552edb2014-03-10 17:42:56 -07003481 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003482 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003483 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3484 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003485 }
3486
3487 // Check if stream type is music, then only allow offload as of now.
3488 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3489 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003490 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3491 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003492 }
3493
3494 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003495 const bool allowOffloadWithVideo =
3496 property_get_bool("audio.offload.video", false /* default_value */);
3497 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003498 ALOGV("%s: has_video == true, returning false", __func__);
3499 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003500 }
3501
3502 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003503 const int min_duration_secs = property_get_int32(
3504 "audio.offload.min.duration.secs", -1 /* default_value */);
3505 if (min_duration_secs >= 0) {
3506 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003507 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3508 __func__, min_duration_secs);
3509 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003510 }
3511 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003512 ALOGV("%s: Offload denied by duration < default min(=%u)",
3513 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3514 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003515 }
3516
3517 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3518 // creating an offloaded track and tearing it down immediately after start when audioflinger
3519 // detects there is an active non offloadable effect.
3520 // FIXME: We should check the audio session here but we do not have it in this context.
3521 // This may prevent offloading in rare situations where effects are left active by apps
3522 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003523 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003524 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003525 }
3526
3527 // See if there is a profile to support this.
3528 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003529 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003530 offloadInfo.sample_rate,
3531 offloadInfo.format,
3532 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003533 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3534 true /* directOnly */);
Eric Laurent90fe31c2020-11-26 20:06:35 +01003535 ALOGV("%s: profile %sfound", __func__, profile != 0 ? "" : "NOT ");
3536 if (profile == nullptr) {
3537 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3538 }
3539 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3540 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3541 }
3542 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003543}
3544
Michael Chana94fbb22018-04-24 14:31:19 +10003545bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3546 const audio_attributes_t& attributes) {
3547 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003548 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003549 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003550 config.sample_rate,
3551 config.format,
3552 config.channel_mask,
3553 output_flags,
3554 true /* directOnly */);
3555 ALOGV("%s() profile %sfound with name: %s, "
3556 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3557 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003558 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003559 config.sample_rate, config.format, config.channel_mask, output_flags);
3560 return (profile != 0);
3561}
3562
Eric Laurent6a94d692014-05-20 11:18:06 -07003563status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3564 audio_port_type_t type,
3565 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003566 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003567 unsigned int *generation)
3568{
jiabin19cdba52020-11-24 11:28:58 -08003569 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3570 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003571 return BAD_VALUE;
3572 }
3573 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003574 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003575 *num_ports = 0;
3576 }
3577
3578 size_t portsWritten = 0;
3579 size_t portsMax = *num_ports;
3580 *num_ports = 0;
3581 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003582 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3583 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003584 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003585 for (const auto& dev : mAvailableOutputDevices) {
3586 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003587 continue;
3588 }
3589 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003590 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003591 }
3592 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003593 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003594 }
3595 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003596 for (const auto& dev : mAvailableInputDevices) {
3597 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003598 continue;
3599 }
3600 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003601 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003602 }
3603 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003604 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003605 }
3606 }
3607 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3608 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3609 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3610 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3611 }
3612 *num_ports += mInputs.size();
3613 }
3614 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003615 size_t numOutputs = 0;
3616 for (size_t i = 0; i < mOutputs.size(); i++) {
3617 if (!mOutputs[i]->isDuplicated()) {
3618 numOutputs++;
3619 if (portsWritten < portsMax) {
3620 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3621 }
3622 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003623 }
Eric Laurent84c70242014-06-23 08:46:27 -07003624 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003625 }
3626 }
3627 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003628 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003629 return NO_ERROR;
3630}
3631
jiabin19cdba52020-11-24 11:28:58 -08003632status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003633{
Eric Laurent99fcae42018-05-17 16:59:18 -07003634 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3635 return BAD_VALUE;
3636 }
3637 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3638 if (dev != 0) {
3639 dev->toAudioPort(port);
3640 return NO_ERROR;
3641 }
3642 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3643 if (dev != 0) {
3644 dev->toAudioPort(port);
3645 return NO_ERROR;
3646 }
3647 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3648 if (out != 0) {
3649 out->toAudioPort(port);
3650 return NO_ERROR;
3651 }
3652 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3653 if (in != 0) {
3654 in->toAudioPort(port);
3655 return NO_ERROR;
3656 }
3657 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003658}
3659
François Gaffieafd4cea2019-11-18 15:50:22 +01003660status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3661 audio_patch_handle_t *handle,
3662 uid_t uid, uint32_t delayMs,
3663 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003664{
François Gaffieafd4cea2019-11-18 15:50:22 +01003665 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003666 if (handle == NULL || patch == NULL) {
3667 return BAD_VALUE;
3668 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003669 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003670
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003671 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003672 return BAD_VALUE;
3673 }
3674 // only one source per audio patch supported for now
3675 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003676 return INVALID_OPERATION;
3677 }
Eric Laurent874c42872014-08-08 15:13:39 -07003678
3679 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003680 return INVALID_OPERATION;
3681 }
Eric Laurent874c42872014-08-08 15:13:39 -07003682 for (size_t i = 0; i < patch->num_sinks; i++) {
3683 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3684 return INVALID_OPERATION;
3685 }
3686 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003687
3688 sp<AudioPatch> patchDesc;
3689 ssize_t index = mAudioPatches.indexOfKey(*handle);
3690
François Gaffieafd4cea2019-11-18 15:50:22 +01003691 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3692 patch->sources[0].role,
3693 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003694#if LOG_NDEBUG == 0
3695 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003696 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3697 patch->sinks[i].role,
3698 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003699 }
3700#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003701
3702 if (index >= 0) {
3703 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003704 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3705 __func__, mUidCached, patchDesc->getUid(), uid);
3706 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003707 return INVALID_OPERATION;
3708 }
3709 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003710 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003711 }
3712
3713 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003714 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003715 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003716 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003717 return BAD_VALUE;
3718 }
Eric Laurent84c70242014-06-23 08:46:27 -07003719 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3720 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003721 if (patchDesc != 0) {
3722 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003723 ALOGV("%s source id differs for patch current id %d new id %d",
3724 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003725 return BAD_VALUE;
3726 }
3727 }
Eric Laurent874c42872014-08-08 15:13:39 -07003728 DeviceVector devices;
3729 for (size_t i = 0; i < patch->num_sinks; i++) {
3730 // Only support mix to devices connection
3731 // TODO add support for mix to mix connection
3732 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003733 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003734 return INVALID_OPERATION;
3735 }
3736 sp<DeviceDescriptor> devDesc =
3737 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3738 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003739 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003740 return BAD_VALUE;
3741 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003742
François Gaffie11d30102018-11-02 16:09:09 +01003743 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003744 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003745 NULL, // updatedSamplingRate
3746 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003747 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003748 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003749 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003750 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003751 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003752 return INVALID_OPERATION;
3753 }
3754 devices.add(devDesc);
3755 }
3756 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003757 return INVALID_OPERATION;
3758 }
Eric Laurent874c42872014-08-08 15:13:39 -07003759
Eric Laurent6a94d692014-05-20 11:18:06 -07003760 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003761 ALOGV("%s setting device %s on output %d",
3762 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003763 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003764 index = mAudioPatches.indexOfKey(*handle);
3765 if (index >= 0) {
3766 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003767 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003768 }
3769 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003770 patchDesc->setUid(uid);
3771 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003772 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003773 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003774 return INVALID_OPERATION;
3775 }
3776 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3777 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3778 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003779 // only one sink supported when connecting an input device to a mix
3780 if (patch->num_sinks > 1) {
3781 return INVALID_OPERATION;
3782 }
François Gaffie53615e22015-03-19 09:24:12 +01003783 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003784 if (inputDesc == NULL) {
3785 return BAD_VALUE;
3786 }
3787 if (patchDesc != 0) {
3788 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3789 return BAD_VALUE;
3790 }
3791 }
François Gaffie11d30102018-11-02 16:09:09 +01003792 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003793 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003794 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 return BAD_VALUE;
3796 }
3797
François Gaffie11d30102018-11-02 16:09:09 +01003798 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003799 patch->sinks[0].sample_rate,
3800 NULL, /*updatedSampleRate*/
3801 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003802 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003803 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003804 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003805 // FIXME for the parameter type,
3806 // and the NONE
3807 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003808 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003809 return INVALID_OPERATION;
3810 }
3811 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003812 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003813 device->toString().c_str(), inputDesc->mIoHandle);
3814 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003815 index = mAudioPatches.indexOfKey(*handle);
3816 if (index >= 0) {
3817 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003818 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003819 }
3820 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003821 patchDesc->setUid(uid);
3822 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003823 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003824 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003825 return INVALID_OPERATION;
3826 }
3827 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3828 // device to device connection
3829 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003830 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003831 return BAD_VALUE;
3832 }
3833 }
François Gaffie11d30102018-11-02 16:09:09 +01003834 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003835 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003836 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003837 return BAD_VALUE;
3838 }
Eric Laurent874c42872014-08-08 15:13:39 -07003839
Eric Laurent6a94d692014-05-20 11:18:06 -07003840 //update source and sink with our own data as the data passed in the patch may
3841 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003842 PatchBuilder patchBuilder;
3843 audio_port_config sourcePortConfig = {};
3844 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3845 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003846
Eric Laurent874c42872014-08-08 15:13:39 -07003847 for (size_t i = 0; i < patch->num_sinks; i++) {
3848 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003849 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003850 return INVALID_OPERATION;
3851 }
François Gaffie11d30102018-11-02 16:09:09 +01003852 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003853 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003854 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003855 return BAD_VALUE;
3856 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003857 audio_port_config sinkPortConfig = {};
3858 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3859 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003860
Eric Laurent3bcf8592015-04-03 12:13:24 -07003861 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003862 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003863 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003864 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01003865 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3866 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003867 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3868 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01003869 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3870 (sourceDesc != nullptr &&
3871 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003872 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003873 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003874 return INVALID_OPERATION;
3875 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003876 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3877 if (sourceDesc != nullptr) {
3878 // take care of dynamic routing for SwOutput selection,
3879 audio_attributes_t attributes = sourceDesc->attributes();
3880 audio_stream_type_t stream = sourceDesc->stream();
3881 audio_attributes_t resultAttr;
3882 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3883 config.sample_rate = sourceDesc->config().sample_rate;
3884 config.channel_mask = sourceDesc->config().channel_mask;
3885 config.format = sourceDesc->config().format;
3886 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3887 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3888 bool isRequestedDeviceForExclusiveUse = false;
François Gaffieafd4cea2019-11-18 15:50:22 +01003889 output_type_t outputType;
3890 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3891 &stream, sourceDesc->uid(), &config, &flags,
3892 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07003893 nullptr, &outputType);
François Gaffieafd4cea2019-11-18 15:50:22 +01003894 if (output == AUDIO_IO_HANDLE_NONE) {
3895 ALOGV("%s no output for device %s",
3896 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurent874c42872014-08-08 15:13:39 -07003897 return INVALID_OPERATION;
3898 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003899 } else {
3900 SortedVector<audio_io_handle_t> outputs =
3901 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3902 // if the sink device is reachable via an opened output stream, request to
3903 // go via this output stream by adding a second source to the patch
3904 // description
3905 output = selectOutput(outputs);
3906 }
3907 if (output != AUDIO_IO_HANDLE_NONE) {
3908 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3909 if (outputDesc->isDuplicated()) {
3910 ALOGV("%s output for device %s is duplicated",
3911 __FUNCTION__, sinkDevice->toString().c_str());
3912 return INVALID_OPERATION;
3913 }
3914 audio_port_config srcMixPortConfig = {};
3915 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
3916 if (sourceDesc != nullptr) {
3917 sourceDesc->setSwOutput(outputDesc);
3918 }
3919 // for volume control, we may need a valid stream
3920 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3921 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3922 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003923 }
Eric Laurent83b88082014-06-20 18:31:16 -07003924 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003925 }
3926 // TODO: check from routing capabilities in config file and other conflicting patches
3927
François Gaffieafd4cea2019-11-18 15:50:22 +01003928 status_t status = installPatch(
3929 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003930 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003931 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003932 return INVALID_OPERATION;
3933 }
3934 } else {
3935 return BAD_VALUE;
3936 }
3937 } else {
3938 return BAD_VALUE;
3939 }
3940 return NO_ERROR;
3941}
3942
3943status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3944 uid_t uid)
3945{
3946 ALOGV("releaseAudioPatch() patch %d", handle);
3947
3948 ssize_t index = mAudioPatches.indexOfKey(handle);
3949
3950 if (index < 0) {
3951 return BAD_VALUE;
3952 }
3953 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003954 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
3955 __func__, mUidCached, patchDesc->getUid(), uid);
3956 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003957 return INVALID_OPERATION;
3958 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003959 return releaseAudioPatchInternal(handle);
3960}
Eric Laurent6a94d692014-05-20 11:18:06 -07003961
François Gaffieafd4cea2019-11-18 15:50:22 +01003962status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
3963 uint32_t delayMs)
3964{
3965 ALOGV("%s patch %d", __func__, handle);
3966 if (mAudioPatches.indexOfKey(handle) < 0) {
3967 ALOGE("%s: no patch found with handle=%d", __func__, handle);
3968 return BAD_VALUE;
3969 }
3970 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003971 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01003972 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07003973 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003974 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003975 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003976 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003977 return BAD_VALUE;
3978 }
3979
François Gaffie11d30102018-11-02 16:09:09 +01003980 setOutputDevices(outputDesc,
3981 getNewOutputDevices(outputDesc, true /*fromCache*/),
3982 true,
3983 0,
3984 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3986 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003987 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003988 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003989 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 return BAD_VALUE;
3991 }
3992 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003993 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003994 true,
3995 NULL);
3996 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003997 status_t status =
3998 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
3999 ALOGV("%s patch panel returned %d patchHandle %d",
4000 __func__, status, patchDesc->getAfHandle());
4001 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004002 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004003 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004004 // SW Bridge
4005 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4006 sp<SwAudioOutputDescriptor> outputDesc =
4007 mOutputs.getOutputFromId(patch->sources[1].id);
4008 if (outputDesc == NULL) {
4009 ALOGE("%s output not found for id %d", __func__, patch->sources[0].id);
4010 return BAD_VALUE;
4011 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004012 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4013 // force SwOutput patch removal as AF counter part patch has already gone.
4014 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4015 removeAudioPatch(outputDesc->getPatchHandle());
4016 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004017 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4018 setOutputDevices(outputDesc,
4019 getNewOutputDevices(outputDesc, true /*fromCache*/),
4020 true, /*force*/
4021 0,
4022 NULL);
4023 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004024 } else {
4025 return BAD_VALUE;
4026 }
4027 } else {
4028 return BAD_VALUE;
4029 }
4030 return NO_ERROR;
4031}
4032
4033status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4034 struct audio_patch *patches,
4035 unsigned int *generation)
4036{
François Gaffie53615e22015-03-19 09:24:12 +01004037 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004038 return BAD_VALUE;
4039 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004041 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004042}
4043
Eric Laurente1715a42014-05-20 11:30:42 -07004044status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004045{
Eric Laurente1715a42014-05-20 11:30:42 -07004046 ALOGV("setAudioPortConfig()");
4047
4048 if (config == NULL) {
4049 return BAD_VALUE;
4050 }
4051 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4052 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004053 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4054 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004055 }
4056
Eric Laurenta121f902014-06-03 13:32:54 -07004057 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004058 if (config->type == AUDIO_PORT_TYPE_MIX) {
4059 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004060 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004061 if (outputDesc == NULL) {
4062 return BAD_VALUE;
4063 }
Eric Laurent84c70242014-06-23 08:46:27 -07004064 ALOG_ASSERT(!outputDesc->isDuplicated(),
4065 "setAudioPortConfig() called on duplicated output %d",
4066 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004067 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004068 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004069 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004070 if (inputDesc == NULL) {
4071 return BAD_VALUE;
4072 }
Eric Laurenta121f902014-06-03 13:32:54 -07004073 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004074 } else {
4075 return BAD_VALUE;
4076 }
4077 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4078 sp<DeviceDescriptor> deviceDesc;
4079 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4080 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4081 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4082 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4083 } else {
4084 return BAD_VALUE;
4085 }
4086 if (deviceDesc == NULL) {
4087 return BAD_VALUE;
4088 }
Eric Laurenta121f902014-06-03 13:32:54 -07004089 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004090 } else {
4091 return BAD_VALUE;
4092 }
4093
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004094 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004095 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4096 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004097 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004098 audioPortConfig->toAudioPortConfig(&newConfig, config);
4099 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004100 }
Eric Laurenta121f902014-06-03 13:32:54 -07004101 if (status != NO_ERROR) {
4102 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004103 }
Eric Laurente1715a42014-05-20 11:30:42 -07004104
4105 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004106}
4107
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004108void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4109{
Eric Laurentd60560a2015-04-10 11:31:20 -07004110 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004111 clearAudioPatches(uid);
4112 clearSessionRoutes(uid);
4113}
4114
Eric Laurent6a94d692014-05-20 11:18:06 -07004115void AudioPolicyManager::clearAudioPatches(uid_t uid)
4116{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004117 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004118 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004119 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004120 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004121 }
4122 }
4123}
4124
François Gaffiec005e562018-11-06 15:04:49 +01004125void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004126{
François Gaffiec005e562018-11-06 15:04:49 +01004127 // Take the first attributes following the product strategy as it is used to retrieve the routed
4128 // device. All attributes wihin a strategy follows the same "routing strategy"
4129 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4130 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004131 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004132 for (size_t j = 0; j < mOutputs.size(); j++) {
4133 if (mOutputs.keyAt(j) == ouptutToSkip) {
4134 continue;
4135 }
4136 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004137 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004138 continue;
4139 }
4140 // If the default device for this strategy is on another output mix,
4141 // invalidate all tracks in this strategy to force re connection.
4142 // Otherwise select new device on the output mix.
4143 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004144 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4145 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004146 }
4147 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004148 setOutputDevices(
4149 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004150 }
4151 }
4152}
4153
4154void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4155{
4156 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004157 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004158 for (size_t i = 0; i < mOutputs.size(); i++) {
4159 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004160 for (const auto& client : outputDesc->getClientIterable()) {
4161 if (client->hasPreferredDevice() && client->uid() == uid) {
4162 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004163 auto clientStrategy = client->strategy();
4164 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4165 end(affectedStrategies)) {
4166 continue;
4167 }
4168 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004169 }
4170 }
4171 }
4172 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004173 for (const auto& strategy : affectedStrategies) {
4174 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004175 }
4176
4177 // remove input routes associated with this uid
4178 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004179 for (size_t i = 0; i < mInputs.size(); i++) {
4180 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004181 for (const auto& client : inputDesc->getClientIterable()) {
4182 if (client->hasPreferredDevice() && client->uid() == uid) {
4183 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4184 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004185 }
4186 }
4187 }
4188 // reroute inputs if necessary
4189 SortedVector<audio_io_handle_t> inputsToClose;
4190 for (size_t i = 0; i < mInputs.size(); i++) {
4191 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004192 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004193 inputsToClose.add(inputDesc->mIoHandle);
4194 }
4195 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004196 for (const auto& input : inputsToClose) {
4197 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004198 }
4199}
4200
Eric Laurentd60560a2015-04-10 11:31:20 -07004201void AudioPolicyManager::clearAudioSources(uid_t uid)
4202{
4203 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004204 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4205 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004206 stopAudioSource(mAudioSources.keyAt(i));
4207 }
4208 }
4209}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004210
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004211status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4212 audio_io_handle_t *ioHandle,
4213 audio_devices_t *device)
4214{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004215 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4216 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004217 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004218 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004219
François Gaffiedf372692015-03-19 10:43:27 +01004220 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004221}
4222
Eric Laurentd60560a2015-04-10 11:31:20 -07004223status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004224 const audio_attributes_t *attributes,
4225 audio_port_handle_t *portId,
4226 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004227{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004228 ALOGV("%s", __FUNCTION__);
4229 *portId = AUDIO_PORT_HANDLE_NONE;
4230
4231 if (source == NULL || attributes == NULL || portId == NULL) {
4232 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4233 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004234 return BAD_VALUE;
4235 }
4236
Eric Laurentd60560a2015-04-10 11:31:20 -07004237 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4238 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004239 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4240 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004241 return INVALID_OPERATION;
4242 }
4243
François Gaffie11d30102018-11-02 16:09:09 +01004244 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004245 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004246 String8(source->ext.device.address),
4247 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004248 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004249 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004250 return BAD_VALUE;
4251 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004252
jiabin4ef93452019-09-10 14:29:54 -07004253 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004254
François Gaffieaaac0fd2018-11-22 17:56:39 +01004255 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004256 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004257 mEngine->getStreamTypeForAttributes(*attributes),
4258 mEngine->getProductStrategyForAttributes(*attributes),
4259 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004260
4261 status_t status = connectAudioSource(sourceDesc);
4262 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004263 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004264 }
4265 return status;
4266}
4267
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004268status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004269{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004270 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004271
4272 // make sure we only have one patch per source.
4273 disconnectAudioSource(sourceDesc);
4274
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004275 audio_attributes_t attributes = sourceDesc->attributes();
François Gaffie11d30102018-11-02 16:09:09 +01004276 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07004277
François Gaffiec005e562018-11-06 15:04:49 +01004278 DeviceVector sinkDevices =
4279 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
4280 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004281 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
4282 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
4283 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07004284
François Gaffieafd4cea2019-11-18 15:50:22 +01004285 PatchBuilder patchBuilder;
4286 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4287 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4288 status_t status =
4289 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4290 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4291 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4292 return INVALID_OPERATION;
4293 }
4294 sourceDesc->setPatchHandle(handle);
4295 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4296 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4297 if (swOutput != 0) {
4298 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004299 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004300 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004301 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004302 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004303 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004304 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004305 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004306 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004307 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004308 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004309 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004310 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4311 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004312 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004313 if (delayMs != 0) {
4314 usleep(delayMs * 1000);
4315 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004316 } else {
4317 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4318 if (hwOutputDesc != 0) {
4319 // create Hwoutput and add to mHwOutputs
4320 } else {
4321 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4322 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004323 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004324 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004325
4326FailureSourceActive:
4327 swOutput->stop();
4328 releaseOutput(sourceDesc->portId());
4329FailureSourceAdded:
4330 sourceDesc->setSwOutput(nullptr);
4331FailureReleasePatch:
4332 releaseAudioPatchInternal(handle);
4333 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004334}
4335
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004336status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004337{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004338 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4339 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004340 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004341 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004342 return BAD_VALUE;
4343 }
4344 status_t status = disconnectAudioSource(sourceDesc);
4345
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004346 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004347 return status;
4348}
4349
Andy Hung2ddee192015-12-18 17:34:44 -08004350status_t AudioPolicyManager::setMasterMono(bool mono)
4351{
4352 if (mMasterMono == mono) {
4353 return NO_ERROR;
4354 }
4355 mMasterMono = mono;
4356 // if enabling mono we close all offloaded devices, which will invalidate the
4357 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4358 // for recreating the new AudioTrack as non-offloaded PCM.
4359 //
4360 // If disabling mono, we leave all tracks as is: we don't know which clients
4361 // and tracks are able to be recreated as offloaded. The next "song" should
4362 // play back offloaded.
4363 if (mMasterMono) {
4364 Vector<audio_io_handle_t> offloaded;
4365 for (size_t i = 0; i < mOutputs.size(); ++i) {
4366 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4367 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4368 offloaded.push(desc->mIoHandle);
4369 }
4370 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004371 for (const auto& handle : offloaded) {
4372 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004373 }
4374 }
4375 // update master mono for all remaining outputs
4376 for (size_t i = 0; i < mOutputs.size(); ++i) {
4377 updateMono(mOutputs.keyAt(i));
4378 }
4379 return NO_ERROR;
4380}
4381
4382status_t AudioPolicyManager::getMasterMono(bool *mono)
4383{
4384 *mono = mMasterMono;
4385 return NO_ERROR;
4386}
4387
Eric Laurentac9cef52017-06-09 15:46:26 -07004388float AudioPolicyManager::getStreamVolumeDB(
4389 audio_stream_type_t stream, int index, audio_devices_t device)
4390{
jiabin9a3361e2019-10-01 09:38:30 -07004391 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004392}
4393
jiabin81772902018-04-02 17:52:27 -07004394status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4395 audio_format_t *surroundFormats,
4396 bool *surroundFormatsEnabled,
4397 bool reported)
4398{
4399 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4400 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4401 return BAD_VALUE;
4402 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004403 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4404 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004405
4406 size_t formatsWritten = 0;
4407 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004408 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004409 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004410 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004411 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004412 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4413 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
Kriti Dangef6be8f2020-11-05 11:58:19 +01004414 audio_devices_t deviceType = device->type();
4415 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4416 // returns formats reported by HDMI devices.
4417 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4418 continue;
4419 }
4420 // Formats reported by sink devices
4421 std::unordered_set<audio_format_t> formatset;
4422 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4423 formatset.insert(it->second.begin(), it->second.end());
4424 }
4425
4426 // Formats hard-coded in the in policy configuration file (if any).
4427 FormatVector encodedFormats = device->encodedFormats();
4428 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4429 // Filter the formats which are supported by the vendor hardware.
4430 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4431 if (mConfig.getSurroundFormats().count(*it) != 0) {
4432 formats.insert(*it);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004433 } else {
4434 for (const auto& pair : mConfig.getSurroundFormats()) {
Kriti Dangef6be8f2020-11-05 11:58:19 +01004435 if (pair.second.count(*it) != 0) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004436 formats.insert(pair.first);
4437 break;
4438 }
4439 }
4440 }
4441 }
jiabin81772902018-04-02 17:52:27 -07004442 }
4443 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004444 for (const auto& pair : mConfig.getSurroundFormats()) {
4445 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004446 }
4447 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004448 *numSurroundFormats = formats.size();
4449 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4450 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004451 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004452 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004453 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004454 bool formatEnabled = true;
4455 switch (forceUse) {
4456 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4457 formatEnabled = mManualSurroundFormats.count(format) != 0;
4458 break;
4459 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4460 formatEnabled = false;
4461 break;
4462 default: // AUTO or ALWAYS => true
4463 break;
jiabin81772902018-04-02 17:52:27 -07004464 }
4465 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4466 }
jiabin81772902018-04-02 17:52:27 -07004467 }
4468 return NO_ERROR;
4469}
4470
4471status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4472{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004473 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004474 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4475 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004476 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004477 return BAD_VALUE;
4478 }
4479
Mikhail Naganov100f0122018-11-29 11:22:16 -08004480 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4481 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004482 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004483 return INVALID_OPERATION;
4484 }
4485
Mikhail Naganov100f0122018-11-29 11:22:16 -08004486 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004487 return NO_ERROR;
4488 }
4489
Mikhail Naganov100f0122018-11-29 11:22:16 -08004490 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004491 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004492 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004493 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004494 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004495 }
4496 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004497 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004498 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004499 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004500 }
4501 }
4502
4503 sp<SwAudioOutputDescriptor> outputDesc;
4504 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004505 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4506 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004507 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4508 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004509 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004510 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004511 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4512 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4513 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004514 name.c_str(),
4515 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004516 if (status != NO_ERROR) {
4517 continue;
4518 }
4519 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4520 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4521 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004522 name.c_str(),
4523 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004524 profileUpdated |= (status == NO_ERROR);
4525 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004526 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004527 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004528 AUDIO_DEVICE_IN_HDMI);
4529 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4530 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004531 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004532 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004533 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4534 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4535 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004536 name.c_str(),
4537 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004538 if (status != NO_ERROR) {
4539 continue;
4540 }
4541 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4542 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4543 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004544 name.c_str(),
4545 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004546 profileUpdated |= (status == NO_ERROR);
4547 }
4548
jiabin81772902018-04-02 17:52:27 -07004549 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004550 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004551 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004552 }
4553
4554 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4555}
4556
Eric Laurent5ada82e2019-08-29 17:53:54 -07004557void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004558{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004559 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004560 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004561 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004562 }
4563}
4564
jiabin6012f912018-11-02 17:06:30 -07004565bool AudioPolicyManager::isHapticPlaybackSupported()
4566{
4567 for (const auto& hwModule : mHwModules) {
4568 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4569 for (const auto &outProfile : outputProfiles) {
4570 struct audio_port audioPort;
4571 outProfile->toAudioPort(&audioPort);
4572 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4573 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4574 return true;
4575 }
4576 }
4577 }
4578 }
4579 return false;
4580}
4581
Eric Laurent8340e672019-11-06 11:01:08 -08004582bool AudioPolicyManager::isCallScreenModeSupported()
4583{
4584 return getConfig().isCallScreenModeSupported();
4585}
4586
4587
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004588status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004589{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004590 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
François Gaffieafd4cea2019-11-18 15:50:22 +01004591 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4592 if (swOutput != 0) {
4593 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004594 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004595 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004596 }
jiabinbce0c1d2020-10-05 11:20:18 -07004597 if (releaseOutput(sourceDesc->portId())) {
4598 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4599 // no need to release audio patch here but just return NO_ERROR.
4600 return NO_ERROR;
4601 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004602 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004603 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004604 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004605 // close Hwoutput and remove from mHwOutputs
4606 } else {
4607 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4608 }
4609 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004610 return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
Eric Laurentd60560a2015-04-10 11:31:20 -07004611}
4612
François Gaffiec005e562018-11-06 15:04:49 +01004613sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4614 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004615{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004616 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004617 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004618 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004619 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004620 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4621 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004622 source = sourceDesc;
4623 break;
4624 }
4625 }
4626 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004627}
4628
Eric Laurente552edb2014-03-10 17:42:56 -07004629// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004630// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004631// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004632uint32_t AudioPolicyManager::nextAudioPortGeneration()
4633{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004634 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004635}
4636
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004637static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004638 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4639 !audioPolicyXmlConfigFile.empty()) {
4640 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4641 if (ret == NO_ERROR) {
4642 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004643 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004644 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004645 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004646 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004647}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004648
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004649AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4650 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004651 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004652 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004653 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004654 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004655 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004656 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004657 mAudioPortGeneration(1),
4658 mBeaconMuteRefCount(0),
4659 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004660 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004661 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004662 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004663 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004664{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004665}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004666
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004667AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4668 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4669{
4670 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004671}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004672
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004673void AudioPolicyManager::loadConfig() {
4674 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004675 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004676 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004677 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004678}
4679
4680status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004681 {
4682 auto engLib = EngineLibrary::load(
4683 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4684 if (!engLib) {
4685 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4686 return NO_INIT;
4687 }
4688 mEngine = engLib->createEngine();
4689 if (mEngine == nullptr) {
4690 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4691 return NO_INIT;
4692 }
François Gaffie2110e042015-03-24 08:41:51 +01004693 }
4694 mEngine->setObserver(this);
4695 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004696 if (status != NO_ERROR) {
4697 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4698 return status;
4699 }
François Gaffie2110e042015-03-24 08:41:51 +01004700
Eric Laurent1d69c872021-01-11 18:53:01 +01004701 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4702 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4703
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004704 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004705 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004706 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004707
Eric Laurent3a4311c2014-03-17 12:00:47 -07004708 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004709 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4710 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4711 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004712 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004713 }
jiabin9ff780e2018-03-19 18:19:52 -07004714 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004715 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004716 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004717 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004718 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004719 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004720 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004721 }
4722 }
4723 }
Eric Laurente552edb2014-03-10 17:42:56 -07004724
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004725 if (mPrimaryOutput == 0) {
4726 ALOGE("Failed to open primary output");
4727 status = NO_INIT;
4728 }
Eric Laurente552edb2014-03-10 17:42:56 -07004729
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004730 // Silence ALOGV statements
4731 property_set("log.tag." LOG_TAG, "D");
4732
Eric Laurente552edb2014-03-10 17:42:56 -07004733 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004734 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004735}
4736
Eric Laurente0720872014-03-11 09:30:41 -07004737AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004738{
Eric Laurente552edb2014-03-10 17:42:56 -07004739 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004740 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004741 }
4742 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004743 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004744 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004745 mAvailableOutputDevices.clear();
4746 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004747 mOutputs.clear();
4748 mInputs.clear();
4749 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004750 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004751 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004752}
4753
Eric Laurente0720872014-03-11 09:30:41 -07004754status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004755{
Eric Laurent87ffa392015-05-22 10:32:38 -07004756 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004757}
4758
Eric Laurente552edb2014-03-10 17:42:56 -07004759// ---
4760
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004761void AudioPolicyManager::onNewAudioModulesAvailable()
4762{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004763 DeviceVector newDevices;
4764 onNewAudioModulesAvailableInt(&newDevices);
4765 if (!newDevices.empty()) {
4766 nextAudioPortGeneration();
4767 mpClientInterface->onAudioPortListUpdate();
4768 }
4769}
4770
4771void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4772{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004773 for (const auto& hwModule : mHwModulesAll) {
4774 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4775 continue;
4776 }
4777 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4778 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4779 ALOGW("could not open HW module %s", hwModule->getName());
4780 continue;
4781 }
4782 mHwModules.push_back(hwModule);
4783 // open all output streams needed to access attached devices
4784 // except for direct output streams that are only opened when they are actually
4785 // required by an app.
4786 // This also validates mAvailableOutputDevices list
4787 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4788 if (!outProfile->canOpenNewIo()) {
4789 ALOGE("Invalid Output profile max open count %u for profile %s",
4790 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4791 continue;
4792 }
4793 if (!outProfile->hasSupportedDevices()) {
4794 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4795 continue;
4796 }
4797 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4798 mTtsOutputAvailable = true;
4799 }
4800
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004801 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4802 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4803 sp<DeviceDescriptor> supportedDevice = 0;
4804 if (supportedDevices.contains(mDefaultOutputDevice)) {
4805 supportedDevice = mDefaultOutputDevice;
4806 } else {
4807 // choose first device present in profile's SupportedDevices also part of
4808 // mAvailableOutputDevices.
4809 if (availProfileDevices.isEmpty()) {
4810 continue;
4811 }
4812 supportedDevice = availProfileDevices.itemAt(0);
4813 }
4814 if (!mOutputDevicesAll.contains(supportedDevice)) {
4815 continue;
4816 }
4817 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4818 mpClientInterface);
4819 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4820 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4821 AUDIO_STREAM_DEFAULT,
4822 AUDIO_OUTPUT_FLAG_NONE, &output);
4823 if (status != NO_ERROR) {
4824 ALOGW("Cannot open output stream for devices %s on hw module %s",
4825 supportedDevice->toString().c_str(), hwModule->getName());
4826 continue;
4827 }
4828 for (const auto &device : availProfileDevices) {
4829 // give a valid ID to an attached device once confirmed it is reachable
4830 if (!device->isAttached()) {
4831 device->attach(hwModule);
4832 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004833 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004834 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004835 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4836 }
4837 }
4838 if (mPrimaryOutput == 0 &&
4839 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4840 mPrimaryOutput = outputDesc;
4841 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004842 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4843 outputDesc->close();
4844 } else {
4845 addOutput(output, outputDesc);
4846 setOutputDevices(outputDesc,
4847 DeviceVector(supportedDevice),
4848 true,
4849 0,
4850 NULL);
4851 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004852 }
4853 // open input streams needed to access attached devices to validate
4854 // mAvailableInputDevices list
4855 for (const auto& inProfile : hwModule->getInputProfiles()) {
4856 if (!inProfile->canOpenNewIo()) {
4857 ALOGE("Invalid Input profile max open count %u for profile %s",
4858 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4859 continue;
4860 }
4861 if (!inProfile->hasSupportedDevices()) {
4862 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4863 continue;
4864 }
4865 // chose first device present in profile's SupportedDevices also part of
4866 // available input devices
4867 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4868 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4869 if (availProfileDevices.isEmpty()) {
4870 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4871 continue;
4872 }
4873 sp<AudioInputDescriptor> inputDesc =
4874 new AudioInputDescriptor(inProfile, mpClientInterface);
4875
4876 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4877 status_t status = inputDesc->open(nullptr,
4878 availProfileDevices.itemAt(0),
4879 AUDIO_SOURCE_MIC,
4880 AUDIO_INPUT_FLAG_NONE,
4881 &input);
4882 if (status != NO_ERROR) {
4883 ALOGW("Cannot open input stream for device %s on hw module %s",
4884 availProfileDevices.toString().c_str(),
4885 hwModule->getName());
4886 continue;
4887 }
4888 for (const auto &device : availProfileDevices) {
4889 // give a valid ID to an attached device once confirmed it is reachable
4890 if (!device->isAttached()) {
4891 device->attach(hwModule);
4892 device->importAudioPortAndPickAudioProfile(inProfile, true);
4893 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004894 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004895 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4896 }
4897 }
4898 inputDesc->close();
4899 }
4900 }
4901}
4902
Eric Laurent98e38192018-02-15 18:31:53 -08004903void AudioPolicyManager::addOutput(audio_io_handle_t output,
4904 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004905{
Eric Laurent1c333e22014-05-20 10:48:17 -07004906 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07004907 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004908 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004909 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004910 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004911}
4912
François Gaffie53615e22015-03-19 09:24:12 +01004913void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4914{
4915 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004916 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004917}
4918
Eric Laurent98e38192018-02-15 18:31:53 -08004919void AudioPolicyManager::addInput(audio_io_handle_t input,
4920 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004921{
Eric Laurent1c333e22014-05-20 10:48:17 -07004922 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004924}
Eric Laurente552edb2014-03-10 17:42:56 -07004925
François Gaffie11d30102018-11-02 16:09:09 +01004926status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004927 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004928 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004929{
François Gaffie11d30102018-11-02 16:09:09 +01004930 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07004931 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004932 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004933
François Gaffie11d30102018-11-02 16:09:09 +01004934 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004935 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004936 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004937 }
Eric Laurente552edb2014-03-10 17:42:56 -07004938
Eric Laurent3b73df72014-03-11 09:06:29 -07004939 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07004940 // first call getAudioPort to get the supported attributes from the HAL
4941 struct audio_port_v7 port = {};
4942 device->toAudioPort(&port);
4943 status_t status = mpClientInterface->getAudioPort(&port);
4944 if (status == NO_ERROR) {
4945 device->importAudioPort(port);
4946 }
4947
4948 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07004949 for (size_t i = 0; i < mOutputs.size(); i++) {
4950 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004951 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07004952 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004953 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4954 mOutputs.keyAt(i), device->toString().c_str());
4955 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004956 }
4957 }
4958 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004959 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004960 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004961 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4962 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004963 if (profile->supportsDevice(device)) {
4964 profiles.add(profile);
4965 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4966 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004967 }
4968 }
4969 }
4970
Eric Laurent7b279bb2015-12-14 10:18:23 -08004971 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004972
Eric Laurente552edb2014-03-10 17:42:56 -07004973 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004974 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004975 return BAD_VALUE;
4976 }
4977
4978 // open outputs for matching profiles if needed. Direct outputs are also opened to
4979 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4980 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004981 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004982
4983 // nothing to do if one output is already opened for this profile
4984 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004985 for (j = 0; j < outputs.size(); j++) {
4986 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004987 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004988 // matching profile: save the sample rates, format and channel masks supported
4989 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004990 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07004991 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004992 }
Eric Laurente552edb2014-03-10 17:42:56 -07004993 break;
4994 }
4995 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004996 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004997 continue;
4998 }
4999
Eric Laurent3974e3b2017-12-07 17:58:43 -08005000 if (!profile->canOpenNewIo()) {
5001 ALOGW("Max Output number %u already opened for this profile %s",
5002 profile->maxOpenCount, profile->getTagName().c_str());
5003 continue;
5004 }
5005
Eric Laurent83efe1c2017-07-09 16:51:08 -07005006 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005007 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005008 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5009 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005010 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005011 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005012 profiles.removeAt(profile_index);
5013 profile_index--;
5014 } else {
5015 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005016 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005017 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005018 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5019 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005020 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005021 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005022
François Gaffie11d30102018-11-02 16:09:09 +01005023 if (device_distinguishes_on_address(deviceType)) {
5024 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5025 device->toString().c_str());
5026 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5027 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005028 }
Eric Laurente552edb2014-03-10 17:42:56 -07005029 ALOGV("checkOutputsForDevice(): adding output %d", output);
5030 }
5031 }
5032
5033 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005034 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005035 return BAD_VALUE;
5036 }
Eric Laurentd4692962014-05-05 18:13:44 -07005037 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005038 // check if one opened output is not needed any more after disconnecting one device
5039 for (size_t i = 0; i < mOutputs.size(); i++) {
5040 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005041 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005042 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005043 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005044 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005045 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005046 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005047 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5048 mOutputs.keyAt(i));
5049 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005050 }
Eric Laurente552edb2014-03-10 17:42:56 -07005051 }
5052 }
Eric Laurentd4692962014-05-05 18:13:44 -07005053 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005054 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005055 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5056 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005057 if (!profile->supportsDevice(device)) {
5058 continue;
5059 }
5060 ALOGV("checkOutputsForDevice(): "
5061 "clearing direct output profile %zu on module %s",
5062 j, hwModule->getName());
5063 profile->clearAudioProfiles();
5064 if (!profile->hasDynamicAudioProfile()) {
5065 continue;
5066 }
5067 // When a device is disconnected, if there is an IOProfile that contains dynamic
5068 // profiles and supports the disconnected device, call getAudioPort to repopulate
5069 // the capabilities of the devices that is supported by the IOProfile.
5070 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5071 if (supportedDevice == device ||
5072 !mAvailableOutputDevices.contains(supportedDevice)) {
5073 continue;
5074 }
5075 struct audio_port_v7 port;
5076 supportedDevice->toAudioPort(&port);
5077 status_t status = mpClientInterface->getAudioPort(&port);
5078 if (status == NO_ERROR) {
5079 supportedDevice->importAudioPort(port);
5080 }
Eric Laurente552edb2014-03-10 17:42:56 -07005081 }
5082 }
5083 }
5084 }
5085 return NO_ERROR;
5086}
5087
François Gaffie11d30102018-11-02 16:09:09 +01005088status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005089 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005090{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005091 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005092
François Gaffie11d30102018-11-02 16:09:09 +01005093 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005094 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005095 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005096 }
5097
Eric Laurentd4692962014-05-05 18:13:44 -07005098 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005099 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005100 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005101 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005102 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005103 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005104 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005105 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005106
François Gaffie11d30102018-11-02 16:09:09 +01005107 if (profile->supportsDevice(device)) {
5108 profiles.add(profile);
5109 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5110 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005111 }
5112 }
5113 }
5114
Eric Laurent0dd51852019-04-19 18:18:58 -07005115 if (profiles.isEmpty()) {
5116 ALOGW("%s: No input profile available for device %s",
5117 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005118 return BAD_VALUE;
5119 }
5120
5121 // open inputs for matching profiles if needed. Direct inputs are also opened to
5122 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5123 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5124
Eric Laurent1c333e22014-05-20 10:48:17 -07005125 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005126
Eric Laurentd4692962014-05-05 18:13:44 -07005127 // nothing to do if one input is already opened for this profile
5128 size_t input_index;
5129 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5130 desc = mInputs.valueAt(input_index);
5131 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005132 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005133 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005134 }
Eric Laurentd4692962014-05-05 18:13:44 -07005135 break;
5136 }
5137 }
5138 if (input_index != mInputs.size()) {
5139 continue;
5140 }
5141
Eric Laurent3974e3b2017-12-07 17:58:43 -08005142 if (!profile->canOpenNewIo()) {
5143 ALOGW("Max Input number %u already opened for this profile %s",
5144 profile->maxOpenCount, profile->getTagName().c_str());
5145 continue;
5146 }
5147
Eric Laurentfe231122017-11-17 17:48:06 -08005148 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005149 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005150 status_t status = desc->open(nullptr,
5151 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005152 AUDIO_SOURCE_MIC,
5153 AUDIO_INPUT_FLAG_NONE,
5154 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005155
Eric Laurentcf2c0212014-07-25 16:20:43 -07005156 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005157 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005158 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005159 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005160 mpClientInterface->setParameters(input, String8(param));
5161 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005162 }
François Gaffie11d30102018-11-02 16:09:09 +01005163 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005164 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005165 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005166 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005167 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005168 }
5169
Eric Laurent0dd51852019-04-19 18:18:58 -07005170 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005171 addInput(input, desc);
5172 }
5173 } // endif input != 0
5174
Eric Laurentcf2c0212014-07-25 16:20:43 -07005175 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005176 ALOGW("%s could not open input for device %s", __func__,
5177 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005178 profiles.removeAt(profile_index);
5179 profile_index--;
5180 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005181 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005182 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005183 }
Eric Laurentd4692962014-05-05 18:13:44 -07005184 ALOGV("checkInputsForDevice(): adding input %d", input);
5185 }
5186 } // end scan profiles
5187
5188 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005189 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005190 return BAD_VALUE;
5191 }
5192 } else {
5193 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005194 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005195 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005196 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005197 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005198 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005199 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005200 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005201 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5202 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005203 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005204 }
5205 }
5206 }
5207 } // end disconnect
5208
5209 return NO_ERROR;
5210}
5211
5212
Eric Laurente0720872014-03-11 09:30:41 -07005213void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005214{
5215 ALOGV("closeOutput(%d)", output);
5216
François Gaffie1c878552018-11-22 16:53:21 +01005217 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5218 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005219 ALOGW("closeOutput() unknown output %d", output);
5220 return;
5221 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005222 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005223 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005224
Eric Laurente552edb2014-03-10 17:42:56 -07005225 // look for duplicated outputs connected to the output being removed.
5226 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005227 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5228 if (dupOutput->isDuplicated() &&
5229 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5230 sp<SwAudioOutputDescriptor> remainingOutput =
5231 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005232 // As all active tracks on duplicated output will be deleted,
5233 // and as they were also referenced on the other output, the reference
5234 // count for their stream type must be adjusted accordingly on
5235 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005236 const bool wasActive = remainingOutput->isActive();
5237 // Note: no-op on the closing output where all clients has already been set inactive
5238 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005239 // stop() will be a no op if the output is still active but is needed in case all
5240 // active streams refcounts where cleared above
5241 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005242 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005243 }
Eric Laurente552edb2014-03-10 17:42:56 -07005244 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5245 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5246
5247 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005248 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005249 }
5250 }
5251
Eric Laurent05b90f82014-08-27 15:32:29 -07005252 nextAudioPortGeneration();
5253
François Gaffie1c878552018-11-22 16:53:21 +01005254 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005255 if (index >= 0) {
5256 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005257 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5258 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005259 mAudioPatches.removeItemsAt(index);
5260 mpClientInterface->onAudioPatchListUpdate();
5261 }
5262
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005263 if (closingOutputWasActive) {
5264 closingOutput->stop();
5265 }
François Gaffie1c878552018-11-22 16:53:21 +01005266 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005267
François Gaffie53615e22015-03-19 09:24:12 +01005268 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005269 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005270
5271 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5272 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005273 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005274 bool directOutputOpen = false;
5275 for (size_t i = 0; i < mOutputs.size(); i++) {
5276 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5277 directOutputOpen = true;
5278 break;
5279 }
5280 }
5281 if (!directOutputOpen) {
5282 ALOGV("no direct outputs open, reset MSD patch");
5283 setMsdPatch();
5284 }
5285 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005286}
5287
5288void AudioPolicyManager::closeInput(audio_io_handle_t input)
5289{
5290 ALOGV("closeInput(%d)", input);
5291
5292 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5293 if (inputDesc == NULL) {
5294 ALOGW("closeInput() unknown input %d", input);
5295 return;
5296 }
5297
Eric Laurent6a94d692014-05-20 11:18:06 -07005298 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005299
François Gaffie11d30102018-11-02 16:09:09 +01005300 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005301 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005302 if (index >= 0) {
5303 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005304 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5305 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005306 mAudioPatches.removeItemsAt(index);
5307 mpClientInterface->onAudioPatchListUpdate();
5308 }
5309
Eric Laurentfe231122017-11-17 17:48:06 -08005310 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005311 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005312
François Gaffie11d30102018-11-02 16:09:09 +01005313 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5314 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005315 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005316 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005317 }
Eric Laurente552edb2014-03-10 17:42:56 -07005318}
5319
François Gaffie11d30102018-11-02 16:09:09 +01005320SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5321 const DeviceVector &devices,
5322 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005323{
5324 SortedVector<audio_io_handle_t> outputs;
5325
François Gaffie11d30102018-11-02 16:09:09 +01005326 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005327 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005328 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005329 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005330 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005331 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005332 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005333 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005334 outputs.add(openOutputs.keyAt(i));
5335 }
5336 }
5337 return outputs;
5338}
5339
Mikhail Naganov37977152018-07-11 15:54:44 -07005340void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5341{
5342 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5343 // output is suspended before any tracks are moved to it
5344 checkA2dpSuspend();
5345 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005346 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005347 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005348 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005349 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005350 setMsdPatch();
5351 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005352 // an event that changed routing likely occurred, inform upper layers
5353 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005354}
5355
François Gaffiec005e562018-11-06 15:04:49 +01005356bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5357 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005358{
François Gaffiec005e562018-11-06 15:04:49 +01005359 return mEngine->getProductStrategyForAttributes(lAttr) ==
5360 mEngine->getProductStrategyForAttributes(rAttr);
5361}
5362
5363void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5364{
5365 auto psId = mEngine->getProductStrategyForAttributes(attr);
5366
5367 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5368 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005369
François Gaffie11d30102018-11-02 16:09:09 +01005370 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5371 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005372
Eric Laurentc209fe42020-06-05 18:11:23 -07005373 uint32_t maxLatency = 0;
5374 bool invalidate = false;
5375 // take into account dynamic audio policies related changes: if a client is now associated
5376 // to a different policy mix than at creation time, invalidate corresponding stream
5377 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5378 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5379 if (desc->isDuplicated()) {
5380 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005381 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005382 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5383 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5384 continue;
5385 }
5386 sp<AudioPolicyMix> primaryMix;
5387 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5388 client->flags(), primaryMix, nullptr);
5389 if (status != OK) {
5390 continue;
5391 }
yucliuf4de36d2020-09-14 14:57:56 -07005392 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005393 invalidate = true;
5394 if (desc->isStrategyActive(psId)) {
5395 maxLatency = desc->latency();
5396 }
5397 break;
5398 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005399 }
5400 }
5401
Eric Laurentc209fe42020-06-05 18:11:23 -07005402 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005403 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5404 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005405 for (audio_io_handle_t srcOut : srcOutputs) {
5406 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005407 if (desc == nullptr) continue;
5408
5409 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005410 maxLatency = desc->latency();
5411 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005412
5413 if (invalidate) continue;
5414
5415 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005416 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005417 // a client on a non direct outputs has necessarily a linear PCM format
5418 // so we can call selectOutput() safely
5419 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5420 client->flags(),
5421 client->config().format,
5422 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005423 client->config().sample_rate,
5424 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005425 if (newOutput != srcOut) {
5426 invalidate = true;
5427 break;
5428 }
5429 } else {
5430 sp<IOProfile> profile = getProfileForOutput(newDevices,
5431 client->config().sample_rate,
5432 client->config().format,
5433 client->config().channel_mask,
5434 client->flags(),
5435 true /* directOnly */);
5436 if (profile != desc->mProfile) {
5437 invalidate = true;
5438 break;
5439 }
5440 }
5441 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005442 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005443
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005444 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005445 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005446 std::to_string(srcOutputs[0]).c_str(),
5447 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005448 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005449 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005450 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005451 if (desc == nullptr) continue;
5452
5453 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005454 setStrategyMute(psId, true, desc);
5455 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005456 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005457 }
François Gaffiec005e562018-11-06 15:04:49 +01005458 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07005459 if (source != 0){
5460 connectAudioSource(source);
5461 }
Eric Laurente552edb2014-03-10 17:42:56 -07005462 }
5463
François Gaffiec005e562018-11-06 15:04:49 +01005464 // Move effects associated to this stream from previous output to new output
5465 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005466 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005467 }
François Gaffiec005e562018-11-06 15:04:49 +01005468 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005469 if (invalidate) {
5470 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5471 mpClientInterface->invalidateStream(stream);
5472 }
Eric Laurente552edb2014-03-10 17:42:56 -07005473 }
5474 }
5475}
5476
Eric Laurente0720872014-03-11 09:30:41 -07005477void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005478{
François Gaffiec005e562018-11-06 15:04:49 +01005479 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5480 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5481 checkOutputForAttributes(attributes);
5482 }
Eric Laurente552edb2014-03-10 17:42:56 -07005483}
5484
Kevin Rocard153f92d2018-12-18 18:33:28 -08005485void AudioPolicyManager::checkSecondaryOutputs() {
5486 std::set<audio_stream_type_t> streamsToInvalidate;
5487 for (size_t i = 0; i < mOutputs.size(); i++) {
5488 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5489 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005490 sp<AudioPolicyMix> primaryMix;
5491 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005492 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005493 client->flags(), primaryMix, &secondaryMixes);
5494 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5495 for (auto &secondaryMix : secondaryMixes) {
5496 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5497 if (outputDesc != nullptr &&
5498 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5499 secondaryDescs.push_back(outputDesc);
5500 }
5501 }
5502
Kevin Rocard94114a22019-04-01 19:38:23 -07005503 if (status != OK ||
5504 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005505 client->getSecondaryOutputs().end(),
5506 secondaryDescs.begin(), secondaryDescs.end())) {
5507 streamsToInvalidate.insert(client->stream());
5508 }
5509 }
5510 }
5511 for (audio_stream_type_t stream : streamsToInvalidate) {
5512 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5513 mpClientInterface->invalidateStream(stream);
5514 }
5515}
5516
Eric Laurent2517af32020-11-25 15:31:27 +01005517bool AudioPolicyManager::isScoRequestedForComm() const {
5518 AudioDeviceTypeAddrVector devices;
5519 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5520 for (const auto &device : devices) {
5521 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5522 return true;
5523 }
5524 }
5525 return false;
5526}
5527
Eric Laurente0720872014-03-11 09:30:41 -07005528void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005529{
François Gaffie53615e22015-03-19 09:24:12 +01005530 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005531 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005532 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005533 return;
5534 }
5535
Eric Laurent3a4311c2014-03-17 12:00:47 -07005536 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005537 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5538 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005539 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005540
5541 // if suspended, restore A2DP output if:
5542 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005543 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005544 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005545 //
Eric Laurentf732e072016-08-03 19:30:28 -07005546 // if not suspended, suspend A2DP output if:
5547 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005548 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005549 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005550 //
5551 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005552 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005553 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005554 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005555 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005556
5557 mpClientInterface->restoreOutput(a2dpOutput);
5558 mA2dpSuspended = false;
5559 }
5560 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005561 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005562 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005563 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005564 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005565
5566 mpClientInterface->suspendOutput(a2dpOutput);
5567 mA2dpSuspended = true;
5568 }
5569 }
5570}
5571
François Gaffie11d30102018-11-02 16:09:09 +01005572DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5573 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005574{
François Gaffie11d30102018-11-02 16:09:09 +01005575 DeviceVector devices;
5576
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005577 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005578 if (index >= 0) {
5579 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005580 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005581 ALOGV("%s device %s forced by patch %d", __func__,
5582 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5583 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005584 }
5585 }
5586
Dean Wheatley514b4312020-06-17 21:45:00 +10005587 // Do not retrieve engine device for outputs through MSD
5588 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5589 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5590 return outputDesc->devices();
5591 }
5592
Eric Laurent97ac8712018-07-27 18:59:02 -07005593 // Honor explicit routing requests only if no client using default routing is active on this
5594 // input: a specific app can not force routing for other apps by setting a preferred device.
5595 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005596 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005597 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005598 if (device != nullptr) {
5599 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005600 }
5601
François Gaffiea807ef92018-11-05 10:44:33 +01005602 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5603 // of setForceUse / Default Bus device here
5604 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5605 if (device != nullptr) {
5606 return DeviceVector(device);
5607 }
5608
François Gaffiec005e562018-11-06 15:04:49 +01005609 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5610 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5611 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005612
François Gaffiec005e562018-11-06 15:04:49 +01005613 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005614 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5615 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005616 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005617 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5618 outputDesc->isStrategyActive(productStrategy)) {
5619 // Retrieval of devices for voice DL is done on primary output profile, cannot
5620 // check the route (would force modifying configuration file for this profile)
5621 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5622 break;
5623 }
Eric Laurente552edb2014-03-10 17:42:56 -07005624 }
François Gaffiec005e562018-11-06 15:04:49 +01005625 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005626 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005627}
5628
François Gaffie11d30102018-11-02 16:09:09 +01005629sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5630 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005631{
François Gaffie11d30102018-11-02 16:09:09 +01005632 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005633
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005634 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005635 if (index >= 0) {
5636 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005637 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005638 ALOGV("getNewInputDevice() device %s forced by patch %d",
5639 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5640 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005641 }
5642 }
5643
Eric Laurent97ac8712018-07-27 18:59:02 -07005644 // Honor explicit routing requests only if no client using default routing is active on this
5645 // input: a specific app can not force routing for other apps by setting a preferred device.
5646 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005647 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5648 if (device != nullptr) {
5649 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005650 }
5651
Eric Laurentdc95a252018-04-12 12:46:56 -07005652 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005653 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005654 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5655 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5656 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005657 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005658 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005659 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005660 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005661
Eric Laurente552edb2014-03-10 17:42:56 -07005662 return device;
5663}
5664
Eric Laurent794fde22016-03-11 09:50:45 -08005665bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5666 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005667 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005668}
5669
Eric Laurente0720872014-03-11 09:30:41 -07005670audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005671 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005672 // getOutputDevicesForStream's behavior for invalid streams.
5673 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5674 // device for music stream), but we want to return the empty set.
5675 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005676 return AUDIO_DEVICE_NONE;
5677 }
François Gaffie11d30102018-11-02 16:09:09 +01005678 DeviceVector activeDevices;
5679 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005680 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5681 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005682 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005683 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005684 }
François Gaffiec005e562018-11-06 15:04:49 +01005685 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005686 devices.merge(curDevices);
5687 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005688 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005689 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005690 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005691 }
5692 }
Eric Laurente552edb2014-03-10 17:42:56 -07005693 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005694
Eric Laurentb0688d62018-08-14 15:49:18 -07005695 // Favor devices selected on active streams if any to report correct device in case of
5696 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005697 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005698 devices = activeDevices;
5699 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005700 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5701 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005702 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005703 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005704 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005705 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005706 }
jiabin9a3361e2019-10-01 09:38:30 -07005707 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5708 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005709}
5710
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005711status_t AudioPolicyManager::getDevicesForAttributes(
5712 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5713 if (devices == nullptr) {
5714 return BAD_VALUE;
5715 }
5716 // check dynamic policies but only for primary descriptors (secondary not used for audible
5717 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005718 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005719 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005720 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005721 if (status != OK) {
5722 return status;
5723 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005724 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5725 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5726 devices->push_back(device);
5727 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005728 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005729 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5730 for (const auto& device : curDevices) {
5731 devices->push_back(device->getDeviceTypeAddr());
5732 }
5733 return NO_ERROR;
5734}
5735
Eric Laurente0720872014-03-11 09:30:41 -07005736void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005737 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005738 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005739 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005740 updateDevicesAndOutputs();
5741 break;
5742 default:
5743 break;
5744 }
5745}
5746
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005747uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005748
5749 // skip beacon mute management if a dedicated TTS output is available
5750 if (mTtsOutputAvailable) {
5751 return 0;
5752 }
5753
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005754 switch(event) {
5755 case STARTING_OUTPUT:
5756 mBeaconMuteRefCount++;
5757 break;
5758 case STOPPING_OUTPUT:
5759 if (mBeaconMuteRefCount > 0) {
5760 mBeaconMuteRefCount--;
5761 }
5762 break;
5763 case STARTING_BEACON:
5764 mBeaconPlayingRefCount++;
5765 break;
5766 case STOPPING_BEACON:
5767 if (mBeaconPlayingRefCount > 0) {
5768 mBeaconPlayingRefCount--;
5769 }
5770 break;
5771 }
5772
5773 if (mBeaconMuteRefCount > 0) {
5774 // any playback causes beacon to be muted
5775 return setBeaconMute(true);
5776 } else {
5777 // no other playback: unmute when beacon starts playing, mute when it stops
5778 return setBeaconMute(mBeaconPlayingRefCount == 0);
5779 }
5780}
5781
5782uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5783 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5784 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5785 // keep track of muted state to avoid repeating mute/unmute operations
5786 if (mBeaconMuted != mute) {
5787 // mute/unmute AUDIO_STREAM_TTS on all outputs
5788 ALOGV("\t muting %d", mute);
5789 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005790 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005791 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005792 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005793 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005794 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005795 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005796 maxLatency = latency;
5797 }
5798 }
5799 mBeaconMuted = mute;
5800 return maxLatency;
5801 }
5802 return 0;
5803}
5804
Eric Laurente0720872014-03-11 09:30:41 -07005805void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005806{
François Gaffiec005e562018-11-06 15:04:49 +01005807 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005808 mPreviousOutputs = mOutputs;
5809}
5810
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005811uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005812 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005813 uint32_t delayMs)
5814{
5815 // mute/unmute strategies using an incompatible device combination
5816 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5817 // if unmuting, unmute only after the specified delay
5818 if (outputDesc->isDuplicated()) {
5819 return 0;
5820 }
5821
5822 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005823 DeviceVector devices = outputDesc->devices();
5824 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005825
François Gaffiec005e562018-11-06 15:04:49 +01005826 auto productStrategies = mEngine->getOrderedProductStrategies();
5827 for (const auto &productStrategy : productStrategies) {
5828 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5829 DeviceVector curDevices =
5830 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5831 curDevices = curDevices.filter(outputDesc->supportedDevices());
5832 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005833 bool doMute = false;
5834
François Gaffiec005e562018-11-06 15:04:49 +01005835 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005836 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005837 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5838 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005839 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005840 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005841 }
Eric Laurent99401132014-05-07 19:48:15 -07005842 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005843 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005844 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005845 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005846 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005847 continue;
5848 }
François Gaffiec005e562018-11-06 15:04:49 +01005849 ALOGVV("%s() %s (curDevice %s)", __func__,
5850 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5851 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5852 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005853 if (mute) {
5854 // FIXME: should not need to double latency if volume could be applied
5855 // immediately by the audioflinger mixer. We must account for the delay
5856 // between now and the next time the audioflinger thread for this output
5857 // will process a buffer (which corresponds to one buffer size,
5858 // usually 1/2 or 1/4 of the latency).
5859 if (muteWaitMs < desc->latency() * 2) {
5860 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005861 }
5862 }
5863 }
5864 }
5865 }
5866 }
5867
Eric Laurent99401132014-05-07 19:48:15 -07005868 // temporary mute output if device selection changes to avoid volume bursts due to
5869 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005870 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005871 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5872 // temporary mute duration is conservatively set to 4 times the reported latency
5873 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5874 if (muteWaitMs < tempMuteWaitMs) {
5875 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005876 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005877 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5878 // make sure that we do not start the temporary mute period too early in case of
5879 // delayed device change
5880 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5881 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005882 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005883 }
5884 }
5885
Eric Laurente552edb2014-03-10 17:42:56 -07005886 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5887 if (muteWaitMs > delayMs) {
5888 muteWaitMs -= delayMs;
5889 usleep(muteWaitMs * 1000);
5890 return muteWaitMs;
5891 }
5892 return 0;
5893}
5894
François Gaffie11d30102018-11-02 16:09:09 +01005895uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5896 const DeviceVector &devices,
5897 bool force,
5898 int delayMs,
5899 audio_patch_handle_t *patchHandle,
5900 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005901{
François Gaffie11d30102018-11-02 16:09:09 +01005902 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005903 uint32_t muteWaitMs;
5904
5905 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005906 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5907 nullptr /* patchHandle */, requiresMuteCheck);
5908 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5909 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005910 return muteWaitMs;
5911 }
Eric Laurente552edb2014-03-10 17:42:56 -07005912
5913 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005914 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005915 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005916
François Gaffie11d30102018-11-02 16:09:09 +01005917 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5918
5919 if (!filteredDevices.isEmpty()) {
5920 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005921 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005922
5923 // if the outputs are not materially active, there is no need to mute.
5924 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005925 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005926 } else {
5927 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5928 muteWaitMs = 0;
5929 }
Eric Laurente552edb2014-03-10 17:42:56 -07005930
Eric Laurent79ea9582020-06-11 18:49:24 -07005931 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5932 // output profile or if new device is not supported AND previous device(s) is(are) still
5933 // available (otherwise reset device must be done on the output)
5934 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5935 !mAvailableOutputDevices.filter(prevDevices).empty()) {
5936 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5937 // restore previous device after evaluating strategy mute state
5938 outputDesc->setDevices(prevDevices);
5939 return muteWaitMs;
5940 }
5941
Eric Laurente552edb2014-03-10 17:42:56 -07005942 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005943 // the requested device is AUDIO_DEVICE_NONE
5944 // OR the requested device is the same as current device
5945 // AND force is not specified
5946 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005947 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005948 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005949 !force && outputDesc->getPatchHandle() != 0) {
5950 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5951 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005952 return muteWaitMs;
5953 }
5954
François Gaffie11d30102018-11-02 16:09:09 +01005955 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005956
Eric Laurente552edb2014-03-10 17:42:56 -07005957 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005958 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005959 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005960 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005961 PatchBuilder patchBuilder;
5962 patchBuilder.addSource(outputDesc);
5963 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5964 for (const auto &filteredDevice : filteredDevices) {
5965 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005966 }
5967
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08005968 // Add half reported latency to delayMs when muteWaitMs is null in order
5969 // to avoid disordered sequence of muting volume and changing devices.
5970 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
5971 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005972 }
Eric Laurente552edb2014-03-10 17:42:56 -07005973
5974 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005975 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005976
5977 return muteWaitMs;
5978}
5979
Eric Laurentc75307b2015-03-17 15:29:32 -07005980status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005981 int delayMs,
5982 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005983{
Eric Laurent6a94d692014-05-20 11:18:06 -07005984 ssize_t index;
5985 if (patchHandle) {
5986 index = mAudioPatches.indexOfKey(*patchHandle);
5987 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005988 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005989 }
5990 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005991 return INVALID_OPERATION;
5992 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005993 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005994 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005995 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005996 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01005997 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005998 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005999 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006000 return status;
6001}
6002
6003status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006004 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006005 bool force,
6006 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006007{
6008 status_t status = NO_ERROR;
6009
Eric Laurent1f2f2232014-06-02 12:01:23 -07006010 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006011 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6012 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006013
François Gaffie11d30102018-11-02 16:09:09 +01006014 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006015 PatchBuilder patchBuilder;
6016 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006017 // AUDIO_SOURCE_HOTWORD is for internal use only:
6018 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006019 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6020 auto result = usecase;
6021 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6022 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6023 }
6024 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006025 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006026 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006027 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006028 }
6029 }
6030 return status;
6031}
6032
Eric Laurent6a94d692014-05-20 11:18:06 -07006033status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6034 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006035{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006036 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006037 ssize_t index;
6038 if (patchHandle) {
6039 index = mAudioPatches.indexOfKey(*patchHandle);
6040 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006041 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006042 }
6043 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006044 return INVALID_OPERATION;
6045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006046 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006047 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006048 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006049 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006050 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006051 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006052 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006053 return status;
6054}
6055
François Gaffie11d30102018-11-02 16:09:09 +01006056sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006057 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006058 audio_format_t& format,
6059 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006060 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006061{
6062 // Choose an input profile based on the requested capture parameters: select the first available
6063 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006064 //
6065 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6066 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006067
Glenn Kasten730b9262018-03-29 15:01:26 -07006068 sp<IOProfile> firstInexact;
6069 uint32_t updatedSamplingRate = 0;
6070 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6071 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006072 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006073 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006074 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006075 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006076 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006077 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006078 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006079 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006080 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006081 &channelMask /*updatedChannelMask*/,
6082 // FIXME ugly cast
6083 (audio_output_flags_t) flags,
6084 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006085 return profile;
6086 }
François Gaffie11d30102018-11-02 16:09:09 +01006087 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006088 samplingRate,
6089 &updatedSamplingRate,
6090 format,
6091 &updatedFormat,
6092 channelMask,
6093 &updatedChannelMask,
6094 // FIXME ugly cast
6095 (audio_output_flags_t) flags,
6096 false /*exactMatchRequiredForInputFlags*/)) {
6097 firstInexact = profile;
6098 }
6099
Eric Laurente552edb2014-03-10 17:42:56 -07006100 }
6101 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006102 if (firstInexact != nullptr) {
6103 samplingRate = updatedSamplingRate;
6104 format = updatedFormat;
6105 channelMask = updatedChannelMask;
6106 return firstInexact;
6107 }
Eric Laurente552edb2014-03-10 17:42:56 -07006108 return NULL;
6109}
6110
François Gaffieaaac0fd2018-11-22 17:56:39 +01006111float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6112 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006113 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006114 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006115{
jiabin9a3361e2019-10-01 09:38:30 -07006116 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006117
6118 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6119 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6120 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6121 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006122 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6123 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6124 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6125 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006126 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006127
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006128 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006129 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6130 mOutputs.isActive(ringVolumeSrc, 0)) {
6131 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006132 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006133 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006134 }
6135
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006136 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006137 if ((volumeSource != callVolumeSrc && (isInCall() ||
6138 mOutputs.isActiveLocally(callVolumeSrc))) &&
6139 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6140 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6141 volumeSource == alarmVolumeSrc ||
6142 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6143 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6144 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006145 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006146 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006147 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006148 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006149 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006150 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006151 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6152 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6153 // programmatically muted.
6154 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6155 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6156 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006157 bool exemptFromCapping =
6158 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6159 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006160 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6161 volumeSource, volumeDb);
6162 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006163 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6164 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6165 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006166 }
6167 }
Eric Laurente552edb2014-03-10 17:42:56 -07006168 // if a headset is connected, apply the following rules to ring tones and notifications
6169 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006170 // - always attenuate notifications volume by 6dB
6171 // - attenuate ring tones volume by 6dB unless music is not playing and
6172 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006173 // - if music is playing, always limit the volume to current music volume,
6174 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006175 if (!Intersection(deviceTypes,
6176 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6177 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006178 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6179 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006180 ((volumeSource == alarmVolumeSrc ||
6181 volumeSource == ringVolumeSrc) ||
6182 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6183 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6184 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6185 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6186 curves.canBeMuted()) {
6187
Eric Laurente552edb2014-03-10 17:42:56 -07006188 // when the phone is ringing we must consider that music could have been paused just before
6189 // by the music application and behave as if music was active if the last music track was
6190 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006191 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006192 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006193 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006194 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006195 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6196 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006197 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006198 float musicVolDb = computeVolume(musicCurves,
6199 musicVolumeSrc,
6200 musicCurves.getVolumeIndex(musicDevice),
6201 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006202 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6203 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6204 if (volumeDb > minVolDb) {
6205 volumeDb = minVolDb;
6206 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006207 }
jiabin9a3361e2019-10-01 09:38:30 -07006208 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6209 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006210 // on A2DP, also ensure notification volume is not too low compared to media when
6211 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006212 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006213 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006214 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6215 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006216 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6217 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006218 }
6219 }
jiabin9a3361e2019-10-01 09:38:30 -07006220 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006221 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006222 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006223 }
6224 }
6225
François Gaffie43c73442018-11-08 08:21:55 +01006226 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006227}
6228
Eric Laurent3839bc02018-07-10 18:33:34 -07006229int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006230 VolumeSource fromVolumeSource,
6231 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006232{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006233 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006234 return srcIndex;
6235 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006236 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6237 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006238 float minSrc = (float)srcCurves.getVolumeIndexMin();
6239 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6240 float minDst = (float)dstCurves.getVolumeIndexMin();
6241 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006242
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006243 // preserve mute request or correct range
6244 if (srcIndex < minSrc) {
6245 if (srcIndex == 0) {
6246 return 0;
6247 }
6248 srcIndex = minSrc;
6249 } else if (srcIndex > maxSrc) {
6250 srcIndex = maxSrc;
6251 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006252 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6253}
6254
François Gaffieaaac0fd2018-11-22 17:56:39 +01006255status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6256 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006257 int index,
6258 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006259 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006260 int delayMs,
6261 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006262{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006263 // do not change actual attributes volume if the attributes is muted
6264 if (outputDesc->isMuted(volumeSource)) {
6265 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6266 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006267 return NO_ERROR;
6268 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006269 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6270 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6271 bool isVoiceVolSrc = callVolSrc == volumeSource;
6272 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6273
Eric Laurent2517af32020-11-25 15:31:27 +01006274 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006275 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006276 // if sco and call follow same curves, bypass forceUseForComm
6277 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006278 ((isVoiceVolSrc && isScoRequested) ||
6279 (isBtScoVolSrc && !isScoRequested))) {
6280 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6281 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006282 // Do not return an error here as AudioService will always set both voice call
6283 // and bluetooth SCO volumes due to stream aliasing.
6284 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006285 }
jiabin9a3361e2019-10-01 09:38:30 -07006286 if (deviceTypes.empty()) {
6287 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006288 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006289
jiabin9a3361e2019-10-01 09:38:30 -07006290 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6291 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006292 // Force VoIP volume to max for bluetooth SCO device except if muted
6293 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006294 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006295 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006296 }
jiabin9a3361e2019-10-01 09:38:30 -07006297 outputDesc->setVolume(
6298 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006299
François Gaffieaaac0fd2018-11-22 17:56:39 +01006300 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006301 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006302 // 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 +01006303 if (isVoiceVolSrc) {
6304 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006305 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006306 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006307 }
Eric Laurent18fba842016-03-31 14:41:26 -07006308 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006309 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6310 mLastVoiceVolume = voiceVolume;
6311 }
6312 }
Eric Laurente552edb2014-03-10 17:42:56 -07006313 return NO_ERROR;
6314}
6315
Eric Laurentc75307b2015-03-17 15:29:32 -07006316void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006317 const DeviceTypeSet& deviceTypes,
6318 int delayMs,
6319 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006320{
jiabincd510522020-01-22 09:40:55 -08006321 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006322 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6323 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6324 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006325 curves.getVolumeIndex(deviceTypes),
6326 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006327 }
6328}
6329
François Gaffiec005e562018-11-06 15:04:49 +01006330void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6331 bool on,
6332 const sp<AudioOutputDescriptor>& outputDesc,
6333 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006334 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006335{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006336 std::vector<VolumeSource> sourcesToMute;
6337 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6338 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6339 toString(attributes).c_str(), on, outputDesc->getId());
6340 VolumeSource source = toVolumeSource(attributes);
6341 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6342 sourcesToMute.push_back(source);
6343 }
Eric Laurente552edb2014-03-10 17:42:56 -07006344 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006345 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006346 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006347 }
6348
Eric Laurente552edb2014-03-10 17:42:56 -07006349}
6350
François Gaffieaaac0fd2018-11-22 17:56:39 +01006351void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6352 bool on,
6353 const sp<AudioOutputDescriptor>& outputDesc,
6354 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006355 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006356{
jiabin9a3361e2019-10-01 09:38:30 -07006357 if (deviceTypes.empty()) {
6358 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006359 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006360 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006361 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006362 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006363 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006364 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6365 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6366 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006367 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006368 }
6369 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006370 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6371 // ignored
6372 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006373 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006374 if (!outputDesc->isMuted(volumeSource)) {
6375 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006376 return;
6377 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006378 if (outputDesc->decMuteCount(volumeSource) == 0) {
6379 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006380 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006381 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006382 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006383 delayMs);
6384 }
6385 }
6386}
6387
François Gaffie53615e22015-03-19 09:24:12 +01006388bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6389{
François Gaffiec005e562018-11-06 15:04:49 +01006390 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006391 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6392 return true;
6393 }
6394
6395 // has known usage?
6396 switch (paa->usage) {
6397 case AUDIO_USAGE_UNKNOWN:
6398 case AUDIO_USAGE_MEDIA:
6399 case AUDIO_USAGE_VOICE_COMMUNICATION:
6400 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6401 case AUDIO_USAGE_ALARM:
6402 case AUDIO_USAGE_NOTIFICATION:
6403 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6404 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6405 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6406 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6407 case AUDIO_USAGE_NOTIFICATION_EVENT:
6408 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6409 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6410 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6411 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006412 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006413 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006414 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006415 case AUDIO_USAGE_EMERGENCY:
6416 case AUDIO_USAGE_SAFETY:
6417 case AUDIO_USAGE_VEHICLE_STATUS:
6418 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006419 break;
6420 default:
6421 return false;
6422 }
6423 return true;
6424}
6425
François Gaffie2110e042015-03-24 08:41:51 +01006426audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6427{
6428 return mEngine->getForceUse(usage);
6429}
6430
6431bool AudioPolicyManager::isInCall()
6432{
6433 return isStateInCall(mEngine->getPhoneState());
6434}
6435
6436bool AudioPolicyManager::isStateInCall(int state)
6437{
6438 return is_state_in_call(state);
6439}
6440
Eric Laurent74b71512019-11-06 17:21:57 -08006441bool AudioPolicyManager::isCallAudioAccessible()
6442{
6443 audio_mode_t mode = mEngine->getPhoneState();
6444 return (mode == AUDIO_MODE_IN_CALL)
6445 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6446 || (mode == AUDIO_MODE_CALL_SCREEN);
6447}
6448
Eric Laurentd60560a2015-04-10 11:31:20 -07006449void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6450{
6451 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006452 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6453 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
6454 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
6455 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006456 }
6457 }
6458
6459 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6460 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6461 bool release = false;
6462 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6463 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6464 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6465 source->ext.device.type == deviceDesc->type()) {
6466 release = true;
6467 }
6468 }
6469 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6470 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6471 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6472 sink->ext.device.type == deviceDesc->type()) {
6473 release = true;
6474 }
6475 }
6476 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006477 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6478 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006479 }
6480 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006481
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006482 mInputs.clearSessionRoutesForDevice(deviceDesc);
6483
Francois Gaffie716e1432019-01-14 16:58:59 +01006484 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006485}
6486
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006487void AudioPolicyManager::modifySurroundFormats(
6488 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006489 std::unordered_set<audio_format_t> enforcedSurround(
6490 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006491 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6492 for (const auto& pair : mConfig.getSurroundFormats()) {
6493 allSurround.insert(pair.first);
6494 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6495 }
Phil Burk09bc4612016-02-24 15:58:15 -08006496
6497 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6498 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006499 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006500 // This is the resulting set of formats depending on the surround mode:
6501 // 'all surround' = allSurround
6502 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6503 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6504 // 'manual surround' = mManualSurroundFormats
6505 // AUTO: formats v 'enforced surround'
6506 // ALWAYS: formats v 'all surround' v 'enforced surround'
6507 // NEVER: formats ^ 'non-surround'
6508 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006509
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006510 std::unordered_set<audio_format_t> formatSet;
6511 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6512 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006513 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006514 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006515 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006516 formatSet.insert(*formatIter);
6517 }
6518 }
6519 } else {
6520 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6521 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006522 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006523
jiabin81772902018-04-02 17:52:27 -07006524 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006525 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006526 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6527 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6528 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006529 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006530 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6531 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6532 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006533 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006534 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006535 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006536 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006537 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006538 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006539}
6540
jiabin06e4bab2019-07-29 10:13:34 -07006541void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6542 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006543 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6544 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6545
6546 // If NEVER, then remove support for channelMasks > stereo.
6547 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006548 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6549 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006550 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6551 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006552 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006553 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006554 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006555 }
6556 }
jiabin81772902018-04-02 17:52:27 -07006557 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6558 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6559 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006560 bool supports5dot1 = false;
6561 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006562 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006563 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6564 supports5dot1 = true;
6565 break;
6566 }
6567 }
6568 // If not then add 5.1 support.
6569 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006570 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006571 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006572 }
Phil Burk09bc4612016-02-24 15:58:15 -08006573 }
6574}
6575
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006576void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006577 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006578 AudioProfileVector &profiles)
6579{
6580 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006581 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006582
François Gaffie112b0af2015-11-19 16:13:25 +01006583 // Format MUST be checked first to update the list of AudioProfile
6584 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006585 reply = mpClientInterface->getParameters(
6586 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006587 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006588 AudioParameter repliedParameters(reply);
6589 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006590 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006591 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6592 return;
6593 }
Phil Burk09bc4612016-02-24 15:58:15 -08006594 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006595 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006596 if (device == AUDIO_DEVICE_OUT_HDMI
6597 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006598 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006599 }
jiabin3e277cc2019-09-10 14:27:34 -07006600 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006601 }
François Gaffie112b0af2015-11-19 16:13:25 +01006602
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006603 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006604 ChannelMaskSet channelMasks;
6605 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006606 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006607 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006608
6609 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006610 reply = mpClientInterface->getParameters(
6611 ioHandle,
6612 requestedParameters.toString() + ";" +
6613 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006614 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006615 AudioParameter repliedParameters(reply);
6616 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006617 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006618 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006619 }
6620 }
6621 if (profiles.hasDynamicChannelsFor(format)) {
6622 reply = mpClientInterface->getParameters(ioHandle,
6623 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006624 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006625 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006626 AudioParameter repliedParameters(reply);
6627 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006628 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006629 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006630 if (device == AUDIO_DEVICE_OUT_HDMI
6631 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006632 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006633 }
François Gaffie112b0af2015-11-19 16:13:25 +01006634 }
6635 }
jiabin3e277cc2019-09-10 14:27:34 -07006636 addDynamicAudioProfileAndSort(
6637 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006638 }
6639}
Eric Laurentd60560a2015-04-10 11:31:20 -07006640
Mikhail Naganovdc769682018-05-04 15:34:08 -07006641status_t AudioPolicyManager::installPatch(const char *caller,
6642 audio_patch_handle_t *patchHandle,
6643 AudioIODescriptorInterface *ioDescriptor,
6644 const struct audio_patch *patch,
6645 int delayMs)
6646{
6647 ssize_t index = mAudioPatches.indexOfKey(
6648 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6649 *patchHandle : ioDescriptor->getPatchHandle());
6650 sp<AudioPatch> patchDesc;
6651 status_t status = installPatch(
6652 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6653 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006654 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006655 }
6656 return status;
6657}
6658
6659status_t AudioPolicyManager::installPatch(const char *caller,
6660 ssize_t index,
6661 audio_patch_handle_t *patchHandle,
6662 const struct audio_patch *patch,
6663 int delayMs,
6664 uid_t uid,
6665 sp<AudioPatch> *patchDescPtr)
6666{
6667 sp<AudioPatch> patchDesc;
6668 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6669 if (index >= 0) {
6670 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006671 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006672 }
6673
6674 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6675 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6676 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6677 if (status == NO_ERROR) {
6678 if (index < 0) {
6679 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006680 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006681 } else {
6682 patchDesc->mPatch = *patch;
6683 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006684 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006685 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006686 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006687 }
6688 nextAudioPortGeneration();
6689 mpClientInterface->onAudioPatchListUpdate();
6690 }
6691 if (patchDescPtr) *patchDescPtr = patchDesc;
6692 return status;
6693}
6694
jiabinbce0c1d2020-10-05 11:20:18 -07006695bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6696{
6697 const TrackClientVector activeClients = output->getActiveClients();
6698 if (activeClients.empty()) {
6699 return true;
6700 }
6701 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6702 if (index < 0) {
6703 ALOGE("%s, no audio patch found while there are active clients on output %d",
6704 __func__, output->getId());
6705 return false;
6706 }
6707 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6708 DeviceVector routedDevices;
6709 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6710 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6711 patchDesc->mPatch.sinks[i].id);
6712 if (device == nullptr) {
6713 ALOGE("%s, no audio device found with id(%d)",
6714 __func__, patchDesc->mPatch.sinks[i].id);
6715 return false;
6716 }
6717 routedDevices.add(device);
6718 }
6719 for (const auto& client : activeClients) {
6720 // TODO: b/175343099 only travel the valid client
6721 sp<DeviceDescriptor> preferredDevice =
6722 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6723 if (mEngine->getOutputDevicesForAttributes(
6724 client->attributes(), preferredDevice, false) == routedDevices) {
6725 return false;
6726 }
6727 }
6728 return true;
6729}
6730
6731sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6732 const sp<IOProfile>& profile, const DeviceVector& devices)
6733{
6734 for (const auto& device : devices) {
6735 // TODO: This should be checking if the profile supports the device combo.
6736 if (!profile->supportsDevice(device)) {
6737 return nullptr;
6738 }
6739 }
6740 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6741 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6742 status_t status = desc->open(nullptr, devices,
6743 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6744 if (status != NO_ERROR) {
6745 return nullptr;
6746 }
6747
6748 // Here is where the out_set_parameters() for card & device gets called
6749 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6750 const audio_devices_t deviceType = device->type();
6751 const String8 &address = String8(device->address().c_str());
6752 if (!address.isEmpty()) {
6753 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6754 mpClientInterface->setParameters(output, String8(param));
6755 free(param);
6756 }
6757 updateAudioProfiles(device, output, profile->getAudioProfiles());
6758 if (!profile->hasValidAudioProfile()) {
6759 ALOGW("%s() missing param", __func__);
6760 desc->close();
6761 return nullptr;
6762 } else if (profile->hasDynamicAudioProfile()) {
6763 desc->close();
6764 output = AUDIO_IO_HANDLE_NONE;
6765 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
6766 profile->pickAudioProfile(
6767 config.sample_rate, config.channel_mask, config.format);
6768 config.offload_info.sample_rate = config.sample_rate;
6769 config.offload_info.channel_mask = config.channel_mask;
6770 config.offload_info.format = config.format;
6771
6772 status = desc->open(&config, devices,
6773 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6774 if (status != NO_ERROR) {
6775 return nullptr;
6776 }
6777 }
6778
6779 addOutput(output, desc);
6780 if (audio_is_remote_submix_device(deviceType) && address != "0") {
6781 sp<AudioPolicyMix> policyMix;
6782 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
6783 policyMix->setOutput(desc);
6784 desc->mPolicyMix = policyMix;
6785 } else {
6786 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
6787 address.string());
6788 }
6789
6790 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
6791 // no duplicated output for direct outputs and
6792 // outputs used by dynamic policy mixes
6793 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
6794
6795 //TODO: configure audio effect output stage here
6796
6797 // open a duplicating output thread for the new output and the primary output
6798 sp<SwAudioOutputDescriptor> dupOutputDesc =
6799 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
6800 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
6801 if (status == NO_ERROR) {
6802 // add duplicated output descriptor
6803 addOutput(duplicatedOutput, dupOutputDesc);
6804 } else {
6805 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
6806 mPrimaryOutput->mIoHandle, output);
6807 desc->close();
6808 removeOutput(output);
6809 nextAudioPortGeneration();
6810 return nullptr;
6811 }
6812 }
6813 return desc;
6814}
6815
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006816} // namespace android