blob: e5721ee209b8a41689882feb895f2f22e8fd5bdc [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
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
Cheney Nie5985452019-02-24 01:39:15 +080036#define AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME \
37 "audio_policy_configuration_bluetooth_legacy_hal.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010038
Eric Laurentd4692962014-05-05 18:13:44 -070039#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070040#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080041#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080042#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110043#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070044
François Gaffie2110e042015-03-24 08:41:51 +010045#include <AudioPolicyManagerInterface.h>
46#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070047#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070050#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070051#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070053#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070054#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010055#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010056#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010057#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurent3b73df72014-03-11 09:06:29 -070059namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070060
Eric Laurentdc462862016-07-19 12:29:53 -070061//FIXME: workaround for truncated touch sounds
62// to be removed when the problem is handled by system UI
63#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070064
65// Largest difference in dB on earpiece in call between the voice volume and another
66// media / notification / system volume.
67constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
68
Mikhail Naganov15be9d22017-11-08 14:18:13 +110069// Compressed formats for MSD module, ordered from most preferred to least preferred.
70static const std::vector<audio_format_t> compressedFormatsOrder = {{
71 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
72 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
73// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
74static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
75 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
76 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
77 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
78
Eric Laurente552edb2014-03-10 17:42:56 -070079// ----------------------------------------------------------------------------
80// AudioPolicyInterface implementation
81// ----------------------------------------------------------------------------
82
Eric Laurente0720872014-03-11 09:30:41 -070083status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080084 audio_policy_dev_state_t state,
85 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080086 const char *device_name,
87 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -070088{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080089 status_t status = setDeviceConnectionStateInt(device, state, device_address,
90 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080091 nextAudioPortGeneration();
92 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080093}
94
François Gaffie11d30102018-11-02 16:09:09 +010095void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
96 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +020097{
François Gaffie11d30102018-11-02 16:09:09 +010098 AudioParameter param(device->address());
François Gaffie44481e72016-04-20 07:49:57 +020099 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700100 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100101 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200102 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
103}
104
François Gaffie11d30102018-11-02 16:09:09 +0100105status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800106 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800107 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800108 const char *device_name,
109 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800111 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
112 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700113
114 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100115 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700116
François Gaffie11d30102018-11-02 16:09:09 +0100117 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800118 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100119 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
120 if (device == 0) {
121 return INVALID_OPERATION;
122 }
Paul McLeane743a472015-01-28 11:07:31 -0800123
Eric Laurente552edb2014-03-10 17:42:56 -0700124 // handle output devices
François Gaffie11d30102018-11-02 16:09:09 +0100125 if (audio_is_output_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700126 SortedVector <audio_io_handle_t> outputs;
127
François Gaffie11d30102018-11-02 16:09:09 +0100128 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129
Eric Laurente552edb2014-03-10 17:42:56 -0700130 // save a copy of the opened output descriptors before any output is opened or closed
131 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
132 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700133 switch (state)
134 {
135 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800136 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700137 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100138 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700139 return INVALID_OPERATION;
140 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800141 ALOGV("%s() connecting device %s format %x",
142 __func__, device->toString().c_str(), encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700143
Eric Laurente552edb2014-03-10 17:42:56 -0700144 // register new device as available
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800145 index = mAvailableOutputDevices.add(device);
146 if (index >= 0) {
147 sp<HwModule> module = mHwModules.getModuleForDevice(device, encodedFormat);
148 if (module == 0) {
149 ALOGD("setDeviceConnectionState() could not find HW module for device %s",
150 device->toString().c_str());
151 mAvailableOutputDevices.remove(device);
152 return INVALID_OPERATION;
153 }
154 ALOGV("setDeviceConnectionState() module name=%s", module->getName());
155 mAvailableOutputDevices[index]->attach(module);
156 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700157 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700158 }
159
François Gaffie44481e72016-04-20 07:49:57 +0200160 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
161 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100162 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200163
François Gaffie11d30102018-11-02 16:09:09 +0100164 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
165 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200166
Francois Gaffie716e1432019-01-14 16:58:59 +0100167 mHwModules.cleanUpForDevice(device);
168
François Gaffie11d30102018-11-02 16:09:09 +0100169 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700170 return INVALID_OPERATION;
171 }
François Gaffie2110e042015-03-24 08:41:51 +0100172
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700173 // outputs should never be empty here
174 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
175 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100176 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100182 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700183 return INVALID_OPERATION;
184 }
185
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100189 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100192 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100194 mOutputs.clearSessionRoutesForDevice(device);
195
François Gaffie11d30102018-11-02 16:09:09 +0100196 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100197
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800198 // Reset active device codec
199 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 } break;
202
203 default:
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return BAD_VALUE;
206 }
207
Eric Laurent736a1022019-03-27 18:28:46 -0700208 // Propagate device availability to Engine
209 setEngineDeviceConnectionState(device, state);
210
Eric Laurentae970022019-01-29 14:25:04 -0800211 // No need to evaluate playback routing when connecting a remote submix
212 // output device used by a dynamic policy of type recorder as no
213 // playback use case is affected.
214 bool doCheckForDeviceAndOutputChanges = true;
215 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX
216 && strncmp(device_address, "0", AUDIO_DEVICE_MAX_ADDRESS_LEN) != 0) {
217 for (audio_io_handle_t output : outputs) {
218 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800219 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
220 if (policyMix != nullptr
221 && policyMix->mMixType == MIX_TYPE_RECORDERS
Eric Laurentae970022019-01-29 14:25:04 -0800222 && strncmp(device_address,
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800223 policyMix->mDeviceAddress.string(),
Eric Laurentae970022019-01-29 14:25:04 -0800224 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
225 doCheckForDeviceAndOutputChanges = false;
226 break;
227 }
228 }
229 }
230
231 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700232 // outputs must be closed after checkOutputForAllStrategies() is executed
233 if (!outputs.isEmpty()) {
234 for (audio_io_handle_t output : outputs) {
235 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100236 // close unused outputs after device disconnection or direct outputs that have
237 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700238 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
239 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800240 (desc->mDirectOpenCount == 0))) {
Mikhail Naganov37977152018-07-11 15:54:44 -0700241 closeOutput(output);
242 }
Eric Laurente552edb2014-03-10 17:42:56 -0700243 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700244 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
245 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700246 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700247 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800248 };
249
250 if (doCheckForDeviceAndOutputChanges) {
251 checkForDeviceAndOutputChanges(checkCloseOutputs);
252 } else {
253 checkCloseOutputs();
254 }
Eric Laurente552edb2014-03-10 17:42:56 -0700255
Eric Laurent87ffa392015-05-22 10:32:38 -0700256 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100257 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
258 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700259 }
François Gaffie11d30102018-11-02 16:09:09 +0100260 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700261 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700262 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
263 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100264 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700265 // do not force device change on duplicated output because if device is 0, it will
266 // also force a device 0 for the two outputs it is duplicated to which may override
267 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100268 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100269 && !desc->isDuplicated()
François Gaffie11d30102018-11-02 16:09:09 +0100270 && (!device_distinguishes_on_address(deviceType)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700271 // always force when disconnecting (a non-duplicated device)
272 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100273 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700274 }
Eric Laurente552edb2014-03-10 17:42:56 -0700275 }
276
Eric Laurentd60560a2015-04-10 11:31:20 -0700277 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100278 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700279 }
280
Eric Laurent72aa32f2014-05-30 18:51:48 -0700281 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700282 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700283 } // end if is output device
284
Eric Laurente552edb2014-03-10 17:42:56 -0700285 // handle input devices
François Gaffie11d30102018-11-02 16:09:09 +0100286 if (audio_is_input_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700287 SortedVector <audio_io_handle_t> inputs;
288
François Gaffie11d30102018-11-02 16:09:09 +0100289 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700290 switch (state)
291 {
292 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700293 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700294 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100295 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700296 return INVALID_OPERATION;
297 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800298 sp<HwModule> module = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
299 if (module == NULL) {
300 ALOGW("setDeviceConnectionState(): could not find HW module for device %s",
301 device->toString().c_str());
302 return INVALID_OPERATION;
303 }
304
François Gaffie44481e72016-04-20 07:49:57 +0200305 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
306 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100307 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200308
François Gaffie11d30102018-11-02 16:09:09 +0100309 if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
310 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100311
312 mHwModules.cleanUpForDevice(device);
313
Eric Laurentd4692962014-05-05 18:13:44 -0700314 return INVALID_OPERATION;
315 }
316
Francois Gaffie716e1432019-01-14 16:58:59 +0100317 if (mAvailableInputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700318 return NO_MEMORY;
319 }
Eric Laurentd4692962014-05-05 18:13:44 -0700320 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700321
322 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700323 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100325 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700326 return INVALID_OPERATION;
327 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700328
François Gaffie11d30102018-11-02 16:09:09 +0100329 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700330
331 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100332 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700333
François Gaffie11d30102018-11-02 16:09:09 +0100334 checkInputsForDevice(device, state, inputs);
335 mAvailableInputDevices.remove(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700336 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700337
338 default:
François Gaffie11d30102018-11-02 16:09:09 +0100339 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700340 return BAD_VALUE;
341 }
342
Eric Laurent736a1022019-03-27 18:28:46 -0700343 // Propagate device availability to Engine
344 setEngineDeviceConnectionState(device, state);
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700347 // As the input device list can impact the output device selection, update
348 // getDeviceForStrategy() cache
349 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700350
Eric Laurent87ffa392015-05-22 10:32:38 -0700351 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100352 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
353 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700354 }
355
Eric Laurentd60560a2015-04-10 11:31:20 -0700356 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100357 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700358 }
359
Eric Laurentb52c1522014-05-20 11:27:36 -0700360 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700361 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700362 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700363
François Gaffie11d30102018-11-02 16:09:09 +0100364 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700365 return BAD_VALUE;
366}
367
Eric Laurent736a1022019-03-27 18:28:46 -0700368void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
369 audio_policy_dev_state_t state) {
370
371 // the Engine does not have to know about remote submix devices used by dynamic audio policies
372 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
373 return;
374 }
375 mEngine->setDeviceConnectionState(device, state);
376}
377
378
Eric Laurente0720872014-03-11 09:30:41 -0700379audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100380 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700381{
Eric Laurent634b7142016-04-20 13:48:02 -0700382 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800383 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
384 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700385 (strlen(device_address) != 0)/*matchAddress*/);
386
387 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100388 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700389 device, device_address);
390 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
391 }
François Gaffie53615e22015-03-19 09:24:12 +0100392
Eric Laurent3a4311c2014-03-17 12:00:47 -0700393 DeviceVector *deviceVector;
394
Eric Laurente552edb2014-03-10 17:42:56 -0700395 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700397 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700398 deviceVector = &mAvailableInputDevices;
399 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100400 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700401 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700402 }
Eric Laurent634b7142016-04-20 13:48:02 -0700403
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800404 return (deviceVector->getDevice(
405 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700406 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800407}
408
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800409status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
410 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800411 const char *device_name,
412 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800413{
414 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700415 String8 reply;
416 AudioParameter param;
417 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800418
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800419 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
420 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800421
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800422 // connect/disconnect only 1 device at a time
423 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
424
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800425 // Check if the device is currently connected
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800426 DeviceVector availableDevices = getAvailableOutputDevices();
427 DeviceVector deviceList = availableDevices.getDevicesFromTypeMask(device);
428 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800429 // Nothing to do: device is not connected
430 return NO_ERROR;
431 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800432 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800433
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700434 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800435 // configure codecs.
436 // Handle two specific cases by sending a set parameter to
437 // configure A2DP codecs. No need to toggle device state.
438 // Case 1: A2DP active device switches from primary to primary
439 // module
440 // Case 2: A2DP device config changes on primary module.
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700441 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800442 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(device, encodedFormat);
443 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
444 if (availablePrimaryOutputDevices().contains(devDesc) &&
445 (module != 0 && module->getHandle() == primaryHandle)) {
446 reply = mpClientInterface->getParameters(
447 AUDIO_IO_HANDLE_NONE,
448 String8(AudioParameter::keyReconfigA2dpSupported));
449 AudioParameter repliedParameters(reply);
450 repliedParameters.getInt(
451 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
452 if (isReconfigA2dpSupported) {
453 const String8 key(AudioParameter::keyReconfigA2dp);
454 param.add(key, String8("true"));
455 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
456 devDesc->setEncodedFormat(encodedFormat);
457 return NO_ERROR;
458 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700459 }
460 }
461
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800462 // Toggle the device state: UNAVAILABLE -> AVAILABLE
463 // This will force reading again the device configuration
464 status = setDeviceConnectionState(device,
465 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 device_address, device_name,
467 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800468 if (status != NO_ERROR) {
469 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
470 status);
471 return status;
472 }
473
474 status = setDeviceConnectionState(device,
475 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800476 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800477 if (status != NO_ERROR) {
478 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
479 status);
480 return status;
481 }
482
483 return NO_ERROR;
484}
485
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800486status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
487 std::vector<audio_format_t> *formats)
488{
489 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800490 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800491 std::unordered_set<audio_format_t> formatSet;
492 sp<HwModule> primaryModule =
493 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
494 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypeMask(
495 AUDIO_DEVICE_OUT_ALL_A2DP);
496 for (const auto& device : declaredDevices) {
497 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800498 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800499 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800500 return status;
501}
502
François Gaffie11d30102018-11-02 16:09:09 +0100503uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700504{
505 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100506 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700507 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700508
François Gaffie11d30102018-11-02 16:09:09 +0100509 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700510 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700511 }
François Gaffie11d30102018-11-02 16:09:09 +0100512 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
513
Francois Gaffie716e1432019-01-14 16:58:59 +0100514 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100515 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100516 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100517
518 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100519 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700520
521 // release existing RX patch if any
522 if (mCallRxPatch != 0) {
523 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
524 mCallRxPatch.clear();
525 }
526 // release TX patch if any
527 if (mCallTxPatch != 0) {
528 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
529 mCallTxPatch.clear();
530 }
531
François Gaffie9eb18552018-11-05 10:33:26 +0100532 auto telephonyRxModule =
533 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
534 auto telephonyTxModule =
535 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
536 // retrieve Rx Source and Tx Sink device descriptors
537 sp<DeviceDescriptor> rxSourceDevice =
538 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
539 String8(),
540 AUDIO_FORMAT_DEFAULT);
541 sp<DeviceDescriptor> txSinkDevice =
542 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
543 String8(),
544 AUDIO_FORMAT_DEFAULT);
545
546 // RX and TX Telephony device are declared by Primary Audio HAL
547 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
548 (telephonyRxModule->getHalVersionMajor() >= 3)) {
549 if (rxSourceDevice == 0 || txSinkDevice == 0) {
550 // RX / TX Telephony device(s) is(are) not currently available
551 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
552 return muteWaitMs;
553 }
554 // do not create a patch (aka Sw Bridging) if Primary HW module has declared supporting a
555 // route between telephony RX to Sink device and Source device to telephony TX
556 const auto &primaryModule = telephonyRxModule;
557 createRxPatch = !primaryModule->supportsPatch(rxSourceDevice, rxDevices.itemAt(0));
558 createTxPatch = !primaryModule->supportsPatch(txSourceDevice, txSinkDevice);
559 } else {
560 // If the RX device is on the primary HW module, then use legacy routing method for
561 // voice calls via setOutputDevice() on primary output.
562 // Otherwise, create two audio patches for TX and RX path.
563 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
564 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700565 // If the TX device is also on the primary HW module, setOutputDevice() will take care
566 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100567 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
568 (txSinkDevice != 0);
569 }
570 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
571 // Otherwise, create two audio patches for TX and RX path.
572 if (!createRxPatch) {
573 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700574 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100575 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800576
577 // If the TX device is on the primary HW module but RX device is
578 // on other HW module, SinkMetaData of telephony input should handle it
579 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700580 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700581 if (createTxPatch) { // create TX path audio patch
François Gaffie9eb18552018-11-05 10:33:26 +0100582 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800583 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700584
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800585 return muteWaitMs;
586}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700587
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800588sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100589 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700590 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700591
François Gaffie11d30102018-11-02 16:09:09 +0100592 if (device == nullptr) {
593 return nullptr;
594 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800595 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100596 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800597 addSource(mAvailableInputDevices.getDevice(
598 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800599 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100600 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800601 addSink(mAvailableOutputDevices.getDevice(
602 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800603 }
604
François Gaffie11d30102018-11-02 16:09:09 +0100605 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
606 const sp<DeviceDescriptor> outputDevice = isRx ?
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800607 device : mAvailableOutputDevices.getDevice(
608 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100609 SortedVector<audio_io_handle_t> outputs =
610 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
611 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800612 // request to reuse existing output stream if one is already opened to reach the target device
613 if (output != AUDIO_IO_HANDLE_NONE) {
614 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100615 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
616 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700617 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800618 }
619
620 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700621 // terminate active capture if on the same HW module as the call TX source device
622 // FIXME: would be better to refine to only inputs whose profile connects to the
623 // call TX device but this information is not in the audio patch and logic here must be
624 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800625 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100626 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700627 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700628 }
629 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700630 }
Eric Laurentdc462862016-07-19 12:29:53 -0700631
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800632 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700633 status_t status = mpClientInterface->createAudioPatch(
634 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800635 ALOGW_IF(status != NO_ERROR,
636 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
637 sp<AudioPatch> audioPatch;
638 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700639 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800640 audioPatch->mAfPatchHandle = afPatchHandle;
641 audioPatch->mUid = mUidCached;
642 }
643 return audioPatch;
644}
645
Mikhail Naganovdc769682018-05-04 15:34:08 -0700646sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100647 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700648 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800649 ALOG_ASSERT(!deviceList.isEmpty(),
650 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700651 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700652}
653
Mikhail Naganov100f0122018-11-29 11:22:16 -0800654audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
655 const DeviceVector& devices, const char *moduleId) const {
656 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
657 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
658}
659
660bool AudioPolicyManager::isDeviceOfModule(
661 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
662 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
663 if (module != 0) {
664 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
665 .indexOf(devDesc) != NAME_NOT_FOUND
666 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
667 .indexOf(devDesc) != NAME_NOT_FOUND;
668 }
669 return false;
670}
671
Eric Laurente0720872014-03-11 09:30:41 -0700672void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700673{
674 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100675 // store previous phone state for management of sonification strategy below
676 int oldState = mEngine->getPhoneState();
677
678 if (mEngine->setPhoneState(state) != NO_ERROR) {
679 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700680 return;
681 }
François Gaffie2110e042015-03-24 08:41:51 +0100682 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700683 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700684 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700685 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800686 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700687 }
688
François Gaffie2110e042015-03-24 08:41:51 +0100689 /**
690 * Switching to or from incall state or switching between telephony and VoIP lead to force
691 * routing command.
692 */
693 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
694 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700695
696 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700697 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700698
Eric Laurente552edb2014-03-10 17:42:56 -0700699 int delayMs = 0;
700 if (isStateInCall(state)) {
701 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100702 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
703 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700704 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700705 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700706 // mute media and sonification strategies and delay device switch by the largest
707 // latency of any output where either strategy is active.
708 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100709 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
710 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
711 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700712 (delayMs < (int)desc->latency()*2)) {
713 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700714 }
François Gaffiec005e562018-11-06 15:04:49 +0100715 setStrategyMute(musicStrategy, true, desc);
716 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
717 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
718 nullptr, true /*fromCache*/).types());
719 setStrategyMute(sonificationStrategy, true, desc);
720 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
721 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
722 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700723 }
724 }
725
Eric Laurent87ffa392015-05-22 10:32:38 -0700726 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100727 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700728 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100729 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700730 // force routing command to audio hardware when ending call
731 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100732 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
733 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700734 }
Eric Laurente552edb2014-03-10 17:42:56 -0700735
Eric Laurent87ffa392015-05-22 10:32:38 -0700736 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100737 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700738 } else if (oldState == AUDIO_MODE_IN_CALL) {
739 if (mCallRxPatch != 0) {
740 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
741 mCallRxPatch.clear();
742 }
743 if (mCallTxPatch != 0) {
744 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
745 mCallTxPatch.clear();
746 }
François Gaffie11d30102018-11-02 16:09:09 +0100747 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700748 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100749 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700750 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700751 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700752
753 // reevaluate routing on all outputs in case tracks have been started during the call
754 for (size_t i = 0; i < mOutputs.size(); i++) {
755 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100756 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700757 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100758 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700759 }
760 }
761
Eric Laurente552edb2014-03-10 17:42:56 -0700762 if (isStateInCall(state)) {
763 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700764 // force reevaluating accessibility routing when call starts
765 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700766 }
767
768 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100769 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
770 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700771}
772
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700773audio_mode_t AudioPolicyManager::getPhoneState() {
774 return mEngine->getPhoneState();
775}
776
Eric Laurente0720872014-03-11 09:30:41 -0700777void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100778 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700779{
François Gaffie2110e042015-03-24 08:41:51 +0100780 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700781 if (config == mEngine->getForceUse(usage)) {
782 return;
783 }
Eric Laurente552edb2014-03-10 17:42:56 -0700784
François Gaffie2110e042015-03-24 08:41:51 +0100785 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
786 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
787 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700788 }
François Gaffie2110e042015-03-24 08:41:51 +0100789 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
790 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
791 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700792
793 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700794 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800795
Eric Laurentdc462862016-07-19 12:29:53 -0700796 //FIXME: workaround for truncated touch sounds
797 // to be removed when the problem is handled by system UI
798 uint32_t delayMs = 0;
799 uint32_t waitMs = 0;
800 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
801 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
802 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700803 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100804 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
805 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700806 }
Eric Laurente552edb2014-03-10 17:42:56 -0700807 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700808 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100809 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700810 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffiea807ef92018-11-05 10:44:33 +0100811 // As done in setDeviceConnectionState, we could also fix default device issue by
812 // preventing the force re-routing in case of default dev that distinguishes on address.
813 // Let's give back to engine full device choice decision however.
François Gaffie11d30102018-11-02 16:09:09 +0100814 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700815 }
François Gaffie11d30102018-11-02 16:09:09 +0100816 if (forceVolumeReeval && !newDevices.isEmpty()) {
817 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700818 }
819 }
820
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800821 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100822 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700823 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100824 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800825 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700826 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800827 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700828 }
Eric Laurente552edb2014-03-10 17:42:56 -0700829 }
Eric Laurente552edb2014-03-10 17:42:56 -0700830}
831
Eric Laurente0720872014-03-11 09:30:41 -0700832void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700833{
834 ALOGV("setSystemProperty() property %s, value %s", property, value);
835}
836
Michael Chana94fbb22018-04-24 14:31:19 +1000837// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
838// search to profiles for direct outputs.
839sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100840 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000841 uint32_t samplingRate,
842 audio_format_t format,
843 audio_channel_mask_t channelMask,
844 audio_output_flags_t flags,
845 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700846{
Michael Chana94fbb22018-04-24 14:31:19 +1000847 if (directOnly) {
848 // only retain flags that will drive the direct output profile selection
849 // if explicitly requested
850 static const uint32_t kRelevantFlags =
851 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
852 AUDIO_OUTPUT_FLAG_VOIP_RX);
853 flags =
854 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
855 }
Eric Laurent861a6282015-05-18 15:40:16 -0700856
857 sp<IOProfile> profile;
858
Mikhail Naganovd4120142017-12-06 15:49:22 -0800859 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800860 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100861 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700862 samplingRate, NULL /*updatedSamplingRate*/,
863 format, NULL /*updatedFormat*/,
864 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700865 flags)) {
866 continue;
867 }
868 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100869 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700870 continue;
871 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800872 // reject profiles if connected device does not support codec
873 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
874 continue;
875 }
Michael Chana94fbb22018-04-24 14:31:19 +1000876 if (!directOnly) return curProfile;
877 // when searching for direct outputs, if several profiles are compatible, give priority
878 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100879 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700880 continue;
881 }
882 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100883 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700884 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700885 }
Eric Laurente552edb2014-03-10 17:42:56 -0700886 }
887 }
Eric Laurent861a6282015-05-18 15:40:16 -0700888 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700889}
890
Eric Laurentf4e63452017-11-06 19:31:46 +0000891audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700892{
François Gaffiec005e562018-11-06 15:04:49 +0100893 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800894
895 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
896 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
897 // format, flags, etc. This may result in some discrepancy for functions that utilize
898 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
899 // and AudioSystem::getOutputSamplingRate().
900
François Gaffie11d30102018-11-02 16:09:09 +0100901 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
902 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700903
François Gaffie11d30102018-11-02 16:09:09 +0100904 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
905 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000906 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700907}
908
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700909status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
910 const audio_attributes_t *srcAttr,
911 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700913 if (srcAttr != NULL) {
914 if (!isValidAttributes(srcAttr)) {
915 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
916 __func__,
917 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
918 srcAttr->tags);
919 return BAD_VALUE;
920 }
921 *dstAttr = *srcAttr;
922 } else {
923 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
924 ALOGE("%s: invalid stream type", __func__);
925 return BAD_VALUE;
926 }
François Gaffiec005e562018-11-06 15:04:49 +0100927 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700928 }
929 return NO_ERROR;
930}
931
Kevin Rocard153f92d2018-12-18 18:33:28 -0800932status_t AudioPolicyManager::getOutputForAttrInt(
933 audio_attributes_t *resultAttr,
934 audio_io_handle_t *output,
935 audio_session_t session,
936 const audio_attributes_t *attr,
937 audio_stream_type_t *stream,
938 uid_t uid,
939 const audio_config_t *config,
940 audio_output_flags_t *flags,
941 audio_port_handle_t *selectedDeviceId,
942 bool *isRequestedDeviceForExclusiveUse,
943 std::vector<sp<SwAudioOutputDescriptor>> *secondaryDescs)
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
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700951 status_t status = getAudioAttributes(resultAttr, attr, *stream);
952 if (status != NO_ERROR) {
953 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700954 }
François Gaffiec005e562018-11-06 15:04:49 +0100955 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700956
François Gaffiec005e562018-11-06 15:04:49 +0100957 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
958 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700959
Kevin Rocard153f92d2018-12-18 18:33:28 -0800960 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
961 // otherwise, fallback to the dynamic policies, if none match, query the engine.
962 // Secondary outputs are always found by dynamic policies as the engine do not support them
963 sp<SwAudioOutputDescriptor> policyDesc;
964 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, policyDesc, secondaryDescs) != NO_ERROR) {
965 policyDesc = nullptr; // reset getOutputForAttr in case of failure
966 secondaryDescs->clear();
967 }
968 // Explicit routing is higher priority then any dynamic policy primary output
969 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && policyDesc != nullptr;
970
971 // FIXME: in case of RENDER policy, the output capabilities should be checked
972 if ((usePrimaryOutputFromPolicyMixes || !secondaryDescs->empty())
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800973 && !audio_is_linear_pcm(config->format)) {
974 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800975 return BAD_VALUE;
976 }
977 if (usePrimaryOutputFromPolicyMixes) {
978 *output = policyDesc->mIoHandle;
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800979 sp<AudioPolicyMix> mix = policyDesc->mPolicyMix.promote();
François Gaffiec005e562018-11-06 15:04:49 +0100980 sp<DeviceDescriptor> deviceDesc =
981 mAvailableOutputDevices.getDevice(mix->mDeviceType,
982 mix->mDeviceAddress,
983 AUDIO_FORMAT_DEFAULT);
984 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
985 ALOGV("getOutputForAttr() returns output %d", *output);
986 return NO_ERROR;
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700987 }
François Gaffiec005e562018-11-06 15:04:49 +0100988 // Virtual sources must always be dynamicaly or explicitly routed
989 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
990 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
991 return BAD_VALUE;
992 }
993 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
994 // in order to let the choice of the order to future vendor engine
995 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700996
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700997 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200998 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700999 }
1000
Nadav Barb2f18162018-07-18 13:01:53 +03001001 // Set incall music only if device was explicitly set, and fallback to the device which is
1002 // chosen by the engine if not.
1003 // FIXME: provide a more generic approach which is not device specific and move this back
1004 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001005 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffiec005e562018-11-06 15:04:49 +01001006 if (outputDevices.types() == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
1007 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001008 audio_is_linear_pcm(config->format) &&
1009 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001010 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001011 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001012 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001013 }
1014 }
1015
François Gaffiec005e562018-11-06 15:04:49 +01001016 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1017 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1018 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001019
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001020 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001021 if (!msdDevices.isEmpty()) {
1022 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001023 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1024 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1025 ALOGV("%s() Using MSD devices %s instead of devices %s",
1026 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1027 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001028 } else {
1029 *output = AUDIO_IO_HANDLE_NONE;
1030 }
1031 }
1032 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001033 *output = getOutputForDevices(outputDevices, session, *stream, config,
1034 flags, attr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001035 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001036 if (*output == AUDIO_IO_HANDLE_NONE) {
1037 return INVALID_OPERATION;
1038 }
Paul McLeanaa981192015-03-21 09:55:15 -07001039
François Gaffiec005e562018-11-06 15:04:49 +01001040 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001041
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001042 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1043
1044 return NO_ERROR;
1045}
1046
1047status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1048 audio_io_handle_t *output,
1049 audio_session_t session,
1050 audio_stream_type_t *stream,
1051 uid_t uid,
1052 const audio_config_t *config,
1053 audio_output_flags_t *flags,
1054 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001055 audio_port_handle_t *portId,
1056 std::vector<audio_io_handle_t> *secondaryOutputs)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001057{
1058 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1059 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1060 return INVALID_OPERATION;
1061 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001062 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001063 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001064 bool isRequestedDeviceForExclusiveUse = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001065 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputDescs;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001066 const sp<DeviceDescriptor> requestedDevice =
1067 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1068
1069 // Prevent from storing invalid requested device id in clients
1070 const audio_port_handle_t sanitizedRequestedPortId =
1071 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1072 *selectedDeviceId = sanitizedRequestedPortId;
1073
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001074 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001075 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
1076 &secondaryOutputDescs);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001077 if (status != NO_ERROR) {
1078 return status;
1079 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001080 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
1081 for (auto& secondaryDesc : secondaryOutputDescs) {
1082 secondaryOutputs->push_back(secondaryDesc->mIoHandle);
1083 weakSecondaryOutputDescs.push_back(secondaryDesc);
1084 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001085
Eric Laurent8fc147b2018-07-22 19:13:55 -07001086 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1087 .format = config->format,
1088 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001089 *portId = AudioPort::getNextUniqueId();
1090
Eric Laurent8fc147b2018-07-22 19:13:55 -07001091 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001092 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001093 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001094 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001095 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001096 *flags, isRequestedDeviceForExclusiveUse,
1097 std::move(weakSecondaryOutputDescs));
Eric Laurent8fc147b2018-07-22 19:13:55 -07001098 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001099 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001100
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001101 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1102 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001103
Eric Laurente83b55d2014-11-14 10:06:21 -08001104 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001105}
1106
François Gaffie11d30102018-11-02 16:09:09 +01001107audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1108 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001109 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001110 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001111 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001112 audio_output_flags_t *flags,
1113 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001114{
Andy Hungc88b0642018-04-27 15:42:35 -07001115 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001116 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001117
jiabine375d412019-02-26 12:54:53 -08001118 // Discard haptic channel mask when forcing muting haptic channels.
1119 audio_channel_mask_t channelMask = forceMutingHaptic
1120 ? (config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL) : config->channel_mask;
1121
Eric Laurente552edb2014-03-10 17:42:56 -07001122 // open a direct output if required by specified parameters
1123 //force direct flag if offload flag is set: offloading implies a direct output stream
1124 // and all common behaviors are driven by checking only the direct flag
1125 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001126 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1127 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001128 }
Nadav Bar766fb022018-01-07 12:18:03 +02001129 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1130 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001131 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001132 // only allow deep buffering for music stream type
1133 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001134 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001135 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001136 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001137 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1138 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001139 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001140 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001141 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001142 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001143 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001144 audio_is_linear_pcm(config->format) &&
1145 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001146 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001147 AUDIO_OUTPUT_FLAG_DIRECT);
1148 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001149 }
Eric Laurente552edb2014-03-10 17:42:56 -07001150
Nadav Bar766fb022018-01-07 12:18:03 +02001151
Eric Laurentb732cf52014-09-24 19:08:21 -07001152 sp<IOProfile> profile;
1153
1154 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001155 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001156 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001157 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
jiabine375d412019-02-26 12:54:53 -08001158 audio_channel_count_from_out_mask(channelMask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001159 goto non_direct_output;
1160 }
1161
Andy Hung2ddee192015-12-18 17:34:44 -08001162 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1163 // This prevents creating an offloaded track and tearing it down immediately after start
1164 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001165 // FIXME: We should check the audio session here but we do not have it in this context.
1166 // This may prevent offloading in rare situations where effects are left active by apps
1167 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001168
Nadav Bar766fb022018-01-07 12:18:03 +02001169 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001170 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001171 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001172 config->sample_rate,
1173 config->format,
jiabine375d412019-02-26 12:54:53 -08001174 channelMask,
Michael Chana94fbb22018-04-24 14:31:19 +10001175 (audio_output_flags_t)*flags,
1176 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001177 }
1178
Eric Laurent1c333e22014-05-20 10:48:17 -07001179 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001180 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1181 for (size_t i = 0; i < mOutputs.size(); i++) {
1182 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1183 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1184 // reuse direct output if currently open by the same client
1185 // and configured with same parameters
1186 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001187 (config->format == desc->mFormat) &&
jiabine375d412019-02-26 12:54:53 -08001188 (channelMask == desc->mChannelMask) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001189 (session == desc->mDirectClientSession)) {
1190 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001191 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001192 mOutputs.keyAt(i), session);
1193 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001194 }
1195 }
1196 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001197
1198 if (!profile->canOpenNewIo()) {
1199 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001200 }
Eric Laurent861a6282015-05-18 15:40:16 -07001201
Eric Laurent3974e3b2017-12-07 17:58:43 -08001202 sp<SwAudioOutputDescriptor> outputDesc =
1203 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001204
François Gaffie11d30102018-11-02 16:09:09 +01001205 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001206
Dean Wheatley3023b382018-08-09 07:42:40 +10001207 // MSD patch may be using the only output stream that can service this request. Release
1208 // MSD patch to prioritize this request over any active output on MSD.
1209 AudioPatchCollection msdPatches = getMsdPatches();
1210 for (size_t i = 0; i < msdPatches.size(); i++) {
1211 const auto& patch = msdPatches[i];
1212 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1213 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1214 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001215 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001216 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1217 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1218 releaseAudioPatch(patch->mHandle, mUidCached);
1219 break;
1220 }
1221 }
1222 }
1223
François Gaffie11d30102018-11-02 16:09:09 +01001224 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001225
1226 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001227 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001228 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001229 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
jiabine375d412019-02-26 12:54:53 -08001230 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001231 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1232 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001233 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
jiabine375d412019-02-26 12:54:53 -08001234 channelMask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001235 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001236 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001237 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001238 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001239 if (audio_is_linear_pcm(config->format) &&
1240 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001241 goto non_direct_output;
1242 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001243 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001244 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001245 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001246 outputDesc->mDirectClientSession = session;
1247
Eric Laurente552edb2014-03-10 17:42:56 -07001248 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001250 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001251 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001252 return output;
1253 }
1254
Eric Laurentb732cf52014-09-24 19:08:21 -07001255non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001256
1257 // A request for HW A/V sync cannot fallback to a mixed output because time
1258 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001259 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001260 return AUDIO_IO_HANDLE_NONE;
1261 }
1262
Eric Laurente552edb2014-03-10 17:42:56 -07001263 // ignoring channel mask due to downmix capability in mixer
1264
1265 // open a non direct output
1266
1267 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001268 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001269 // get which output is suitable for the specified stream. The actual
1270 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001271 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001272
Eric Laurent8838a382014-09-08 16:44:28 -07001273 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001274 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabine375d412019-02-26 12:54:53 -08001275 output = selectOutput(outputs, *flags, config->format, channelMask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001276 }
François Gaffie11d30102018-11-02 16:09:09 +01001277 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001278 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001279 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001280
Eric Laurente552edb2014-03-10 17:42:56 -07001281 return output;
1282}
1283
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001284sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001285 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1286 mAvailableInputDevices);
1287 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1288}
1289
1290DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1291 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1292 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001293}
1294
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001295const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1296 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001297 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1298 if (msdModule != 0) {
1299 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1300 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1301 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1302 const struct audio_port_config *source = &patch->mPatch.sources[j];
1303 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1304 source->ext.device.hw_module == msdModule->getHandle()) {
1305 msdPatches.addAudioPatch(patch->mHandle, patch);
1306 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001307 }
1308 }
1309 }
1310 return msdPatches;
1311}
1312
François Gaffie11d30102018-11-02 16:09:09 +01001313status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001314 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1315{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001316 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001317 if (msdModule == nullptr) {
1318 ALOGE("%s() unable to get MSD module", __func__);
1319 return NO_INIT;
1320 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001321 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001322 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001323 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001324 return NO_INIT;
1325 }
1326 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1327 if (inputProfiles.isEmpty()) {
1328 ALOGE("%s() no input profiles for MSD module", __func__);
1329 return NO_INIT;
1330 }
1331 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1332 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001333 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001334 return NO_INIT;
1335 }
1336 AudioProfileVector msdProfiles;
1337 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1338 for (const auto &inProfile : inputProfiles) {
1339 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1340 msdProfiles.appendVector(inProfile->getAudioProfiles());
1341 }
1342 }
1343 AudioProfileVector deviceProfiles;
1344 for (const auto &outProfile : outputProfiles) {
1345 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1346 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1347 }
1348 }
1349 struct audio_config_base bestSinkConfig;
1350 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1351 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1352 &bestSinkConfig);
1353 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001354 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1355 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001356 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001357 }
1358 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1359 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1360 sinkConfig->format = bestSinkConfig.format;
1361 // For encoded streams force direct flag to prevent downstream mixing.
1362 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1363 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1364 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1365 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1366 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1367 sourceConfig->format = bestSinkConfig.format;
1368 // Copy input stream directly without any processing (e.g. resampling).
1369 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1370 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1371 if (hwAvSync) {
1372 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1373 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1374 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1375 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1376 }
1377 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1378 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1379 sinkConfig->config_mask |= config_mask;
1380 sourceConfig->config_mask |= config_mask;
1381 return NO_ERROR;
1382}
1383
François Gaffie11d30102018-11-02 16:09:09 +01001384PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001385{
1386 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001387 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001388 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1389 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1390 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1391 // For now, we just forcefully try with HwAvSync first.
1392 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1393 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1394 getBestMsdAudioProfileFor(
1395 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1396 if (res == NO_ERROR) {
1397 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1398 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1399 }
1400 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1401 " supporting PCM format conversion.", __func__);
1402 return patchBuilder;
1403}
1404
François Gaffie11d30102018-11-02 16:09:09 +01001405status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1406 sp<DeviceDescriptor> device = outputDevice;
1407 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001408 // Use media strategy for unspecified output device. This should only
1409 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1410 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001411 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1412 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001413 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1414 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001415 }
François Gaffie11d30102018-11-02 16:09:09 +01001416 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1417 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001418 const struct audio_patch* patch = patchBuilder.patch();
1419 const AudioPatchCollection msdPatches = getMsdPatches();
1420 if (!msdPatches.isEmpty()) {
1421 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1422 "The current MSD prototype only supports one output patch");
1423 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1424 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1425 return NO_ERROR;
1426 }
1427 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1428 }
1429 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1430 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1431 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1432 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001433 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1434 device->toString().c_str(), patch->sources[0].format,
1435 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001436 return status;
1437}
1438
Eric Laurente0720872014-03-11 09:30:41 -07001439audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001440 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001441 audio_format_t format,
1442 audio_channel_mask_t channelMask,
1443 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001444{
1445 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001446 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001447 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001448 // 1: the output supporting haptic playback when requesting haptic playback
1449 // 2: the output with the highest number of requested policy flags
1450 // 3: the output with the bit depth the closest to the requested one
1451 // 4: the primary output
1452 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001453
1454 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001455 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001456 }
1457 if (outputs.size() == 1) {
1458 return outputs[0];
1459 }
1460
1461 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001462 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1463 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001464 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1465 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1466 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001467 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1468 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001469
Eric Laurente78b6762018-12-19 16:29:01 -08001470 // Flags which must be present on both the request and the selected output
1471 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1472 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1473
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001474 for (audio_io_handle_t output : outputs) {
1475 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001476 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001477 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1478 continue;
1479 }
jiabin40573322018-11-08 12:08:02 -08001480 // If haptic channel is specified, use the haptic output if present.
1481 // When using haptic output, same audio format and sample rate are required.
1482 if (hapticChannelCount > 0) {
1483 // If haptic channel is specified, use the first output that
1484 // support haptic playback.
1485 if (audio_channel_count_from_out_mask(
1486 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1487 && format == outputDesc->mFormat
1488 && samplingRate == outputDesc->mSamplingRate) {
1489 return output;
1490 }
1491 } else {
1492 // When haptic channel is not specified, skip haptic output.
1493 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1494 continue;
1495 }
1496 }
Eric Laurente78b6762018-12-19 16:29:01 -08001497 if ((kMandatedFlags & flags) !=
1498 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1499 continue;
1500 }
jiabin40573322018-11-08 12:08:02 -08001501
Eric Laurent8838a382014-09-08 16:44:28 -07001502 // if a valid format is specified, skip output if not compatible
1503 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001504 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001505 continue;
1506 }
Eric Laurente6930022016-02-11 10:20:40 -08001507 if (AudioPort::isBetterFormatMatch(
1508 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001509 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001510 bestFormat = outputDesc->mFormat;
1511 }
Eric Laurent8838a382014-09-08 16:44:28 -07001512 }
1513
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001514 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001515 if (commonFlags >= maxCommonFlags) {
1516 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001517 if (format != AUDIO_FORMAT_INVALID
1518 && AudioPort::isBetterFormatMatch(
1519 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001520 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001521 bestFormatForFlags = outputDesc->mFormat;
1522 }
1523 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001524 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001525 maxCommonFlags = commonFlags;
1526 bestFormatForFlags = outputDesc->mFormat;
1527 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001528 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001529 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001530 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001531 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001532 }
1533 }
1534 }
1535
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001536 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001537 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001538 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001539 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001540 return outputForFormat;
1541 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001542 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001543 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001544 }
1545
1546 return outputs[0];
1547}
1548
Eric Laurent8fc147b2018-07-22 19:13:55 -07001549status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001550{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001551 ALOGV("%s portId %d", __FUNCTION__, portId);
1552
1553 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1554 if (outputDesc == 0) {
1555 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001556 return BAD_VALUE;
1557 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001558 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001559
Eric Laurent8fc147b2018-07-22 19:13:55 -07001560 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001561 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001562
Eric Laurent733ce942017-12-07 12:18:25 -08001563 status_t status = outputDesc->start();
1564 if (status != NO_ERROR) {
1565 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001566 }
1567
Eric Laurent97ac8712018-07-27 18:59:02 -07001568 uint32_t delayMs;
1569 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001570
1571 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001572 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001573 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001574 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001575 if (delayMs != 0) {
1576 usleep(delayMs * 1000);
1577 }
1578
1579 return status;
1580}
1581
Eric Laurent97ac8712018-07-27 18:59:02 -07001582status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1583 const sp<TrackClientDescriptor>& client,
1584 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001585{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001586 // cannot start playback of STREAM_TTS if any other output is being used
1587 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001588
1589 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001590 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001591 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001592 auto clientStrategy = client->strategy();
1593 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001594 if (stream == AUDIO_STREAM_TTS) {
1595 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001596 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
1597 streamToVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001598 return INVALID_OPERATION;
1599 } else {
1600 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1601 }
1602 } else {
1603 // some playback other than beacon starts
1604 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1605 }
1606
Eric Laurent77305a62016-07-25 16:39:22 -07001607 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001608 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001609 bool force = !outputDesc->isActive() &&
1610 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001611
François Gaffie11d30102018-11-02 16:09:09 +01001612 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001613 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001614 const char *address = NULL;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001615 if (policyMix != NULL) {
François Gaffie11d30102018-11-02 16:09:09 +01001616 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001617 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001618 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001619 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001620 } else {
1621 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001622 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001623 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1624 AUDIO_FORMAT_DEFAULT);
1625 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1626 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001627 }
1628
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001629 // requiresMuteCheck is false when we can bypass mute strategy.
1630 // It covers a common case when there is no materially active audio
1631 // and muting would result in unnecessary delay and dropped audio.
1632 const uint32_t outputLatencyMs = outputDesc->latency();
1633 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1634
Eric Laurente552edb2014-03-10 17:42:56 -07001635 // increment usage count for this stream on the requested output:
1636 // NOTE that the usage count is the same for duplicated output and hardware output which is
1637 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001638 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001639
1640 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001641 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1642 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001643 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001644 }
1645 }
Eric Laurente552edb2014-03-10 17:42:56 -07001646
François Gaffiec005e562018-11-06 15:04:49 +01001647 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001648 selectOutputForMusicEffects();
1649 }
1650
François Gaffie1c878552018-11-22 16:53:21 +01001651 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001652 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001653 if (devices.isEmpty()) {
1654 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001655 }
François Gaffiec005e562018-11-06 15:04:49 +01001656 bool shouldWait =
1657 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1658 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1659 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001660 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001661 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001662 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001663 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001664 // An output has a shared device if
1665 // - managed by the same hw module
1666 // - supports the currently selected device
1667 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001668 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001669
Eric Laurent77305a62016-07-25 16:39:22 -07001670 // force a device change if any other output is:
1671 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001672 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001673 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001674 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001675 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001676 // change the device currently selected by the other output.
1677 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001678 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001679 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001680 force = true;
1681 }
1682 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001683 // a notification so that audio focus effect can propagate, or that a mute/unmute
1684 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001685 const uint32_t latencyMs = desc->latency();
1686 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1687
1688 if (shouldWait && isActive && (waitMs < latencyMs)) {
1689 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001690 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001691
1692 // Require mute check if another output is on a shared device
1693 // and currently active to have proper drain and avoid pops.
1694 // Note restoring AudioTracks onto this output needs to invoke
1695 // a volume ramp if there is no mute.
1696 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001697 }
1698 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001699
1700 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001701 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001702
Eric Laurente552edb2014-03-10 17:42:56 -07001703 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001704 auto &curves = getVolumeCurves(client->attributes());
1705 checkAndSetVolume(curves, client->volumeSource(),
1706 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001707 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001708 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001709
1710 // update the outputs if starting an output with a stream that can affect notification
1711 // routing
1712 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001713
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001714 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001715 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001716 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1717 }
Eric Laurentdc462862016-07-19 12:29:53 -07001718
1719 if (waitMs > muteWaitMs) {
1720 *delayMs = waitMs - muteWaitMs;
1721 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001722
1723 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1724 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1725 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1726 // change occurs after the MixerThread starts and causes a stream volume
1727 // glitch.
1728 //
1729 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001730 }
Eric Laurentdc462862016-07-19 12:29:53 -07001731
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001732 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1733 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001734 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001735 }
1736
Eric Laurent97ac8712018-07-27 18:59:02 -07001737 // Automatically enable the remote submix input when output is started on a re routing mix
1738 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001739 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001740 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1741 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1742 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1743 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001744 "remote-submix",
1745 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001746 }
1747
Eric Laurente552edb2014-03-10 17:42:56 -07001748 return NO_ERROR;
1749}
1750
Eric Laurent8fc147b2018-07-22 19:13:55 -07001751status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001752{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001753 ALOGV("%s portId %d", __FUNCTION__, portId);
1754
1755 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1756 if (outputDesc == 0) {
1757 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001758 return BAD_VALUE;
1759 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001760 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001761
Eric Laurent97ac8712018-07-27 18:59:02 -07001762 ALOGV("stopOutput() output %d, stream %d, session %d",
1763 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001764
Eric Laurent97ac8712018-07-27 18:59:02 -07001765 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001766
Eric Laurent733ce942017-12-07 12:18:25 -08001767 if (status == NO_ERROR ) {
1768 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001769 }
1770 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001771}
1772
Eric Laurent97ac8712018-07-27 18:59:02 -07001773status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1774 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001775{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001776 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001777 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001778 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001779
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001780 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1781
François Gaffie1c878552018-11-22 16:53:21 +01001782 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1783 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001784 // Automatically disable the remote submix input when output is stopped on a
1785 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001786 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
François Gaffie11d30102018-11-02 16:09:09 +01001787 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001788 policyMix != NULL &&
1789 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001790 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1791 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001792 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001793 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001794 }
1795 }
1796 bool forceDeviceUpdate = false;
1797 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001798 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001799 forceDeviceUpdate = true;
1800 }
1801
Eric Laurente552edb2014-03-10 17:42:56 -07001802 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001803 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001804
Eric Laurente552edb2014-03-10 17:42:56 -07001805 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001806 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001807 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001808 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001809 // delay the device switch by twice the latency because stopOutput() is executed when
1810 // the track stop() command is received and at that time the audio track buffer can
1811 // still contain data that needs to be drained. The latency only covers the audio HAL
1812 // and kernel buffers. Also the latency does not always include additional delay in the
1813 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001814 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001815
1816 // force restoring the device selection on other active outputs if it differs from the
1817 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001818 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001819 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001820 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001821 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001822 desc->isActive() &&
1823 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001824 (newDevices != desc->devices())) {
1825 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1826 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001827
François Gaffie11d30102018-11-02 16:09:09 +01001828 setOutputDevices(desc, newDevices2, force, delayMs);
1829
Eric Laurent57de36c2016-09-28 16:59:11 -07001830 // re-apply device specific volume if not done by setOutputDevice()
1831 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001832 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001833 }
Eric Laurente552edb2014-03-10 17:42:56 -07001834 }
1835 }
1836 // update the outputs if stopping one with a stream that can affect notification routing
1837 handleNotificationRoutingForStream(stream);
1838 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001839
1840 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1841 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001842 setStrategyMute(streamToStrategy(AUDIO_STREAM_RING), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001843 }
1844
François Gaffiec005e562018-11-06 15:04:49 +01001845 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001846 selectOutputForMusicEffects();
1847 }
Eric Laurente552edb2014-03-10 17:42:56 -07001848 return NO_ERROR;
1849 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001850 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001851 return INVALID_OPERATION;
1852 }
1853}
1854
Eric Laurent8fc147b2018-07-22 19:13:55 -07001855void AudioPolicyManager::releaseOutput(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) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001861 // If an output descriptor is closed due to a device routing change,
1862 // then there are race conditions with releaseOutput from tracks
1863 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1864 // destroyed shortly thereafter.
1865 //
1866 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001867 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001868 return;
1869 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001870
1871 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001872
Eric Laurent8fc147b2018-07-22 19:13:55 -07001873 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1874 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001875 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001876 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001877 return;
1878 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001879 if (--outputDesc->mDirectOpenCount == 0) {
1880 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001881 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001882 }
1883 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001884 // stopOutput() needs to be successfully called before releaseOutput()
1885 // otherwise there may be inaccurate stream reference counts.
1886 // This is checked in outputDesc->removeClient below.
1887 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001888}
1889
Eric Laurentcaf7f482014-11-25 17:50:47 -08001890status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1891 audio_io_handle_t *input,
1892 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001893 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001894 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001895 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001896 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001897 input_type_t *inputType,
1898 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001899{
François Gaffiec005e562018-11-06 15:04:49 +01001900 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1901 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1902 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001903
Eric Laurentad2e7b92017-09-14 20:06:42 -07001904 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001905 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001906 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001907 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001908 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001909 sp<AudioInputDescriptor> inputDesc;
1910 sp<RecordClientDescriptor> clientDesc;
1911 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001912 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001913
1914 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1915 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1916 return INVALID_OPERATION;
1917 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001918
Francois Gaffie716e1432019-01-14 16:58:59 +01001919 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1920 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001921 }
1922
Paul McLean466dc8e2015-04-17 13:15:36 -06001923 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001924 sp<DeviceDescriptor> explicitRoutingDevice =
1925 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001926
Eric Laurentad2e7b92017-09-14 20:06:42 -07001927 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1928 // possible
1929 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1930 *input != AUDIO_IO_HANDLE_NONE) {
1931 ssize_t index = mInputs.indexOfKey(*input);
1932 if (index < 0) {
1933 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1934 status = BAD_VALUE;
1935 goto error;
1936 }
1937 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001938 RecordClientVector clients = inputDesc->getClientsForSession(session);
1939 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001940 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1941 status = BAD_VALUE;
1942 goto error;
1943 }
1944 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1945 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001946 // corresponds to a new client and is only permitted from the same UID.
1947 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001948 if (clients.size() > 1) {
1949 for (const auto& client : clients) {
1950 // The client map is ordered by key values (portId) and portIds are allocated
1951 // incrementaly. So the first client in this list is the one opened by audio flinger
1952 // when the mmap stream is created and should be ignored as it does not correspond
1953 // to an actual client
1954 if (client == *clients.cbegin()) {
1955 continue;
1956 }
1957 if (uid != client->uid() && !client->isSilenced()) {
1958 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1959 uid, client->portId(), client->uid());
1960 status = INVALID_OPERATION;
1961 goto error;
1962 }
Eric Laurent331679c2018-04-16 17:03:16 -07001963 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001964 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001965 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001966 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001967
Eric Laurent8f42ea12018-08-08 09:08:25 -07001968 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001969 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001970 }
1971
1972 *input = AUDIO_IO_HANDLE_NONE;
1973 *inputType = API_INPUT_INVALID;
1974
Francois Gaffie716e1432019-01-14 16:58:59 +01001975 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001976
Francois Gaffie716e1432019-01-14 16:58:59 +01001977 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1978 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1979 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001980 if (status != NO_ERROR) {
1981 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001982 }
Kevin Rocard25f9b052019-02-27 15:08:54 -08001983 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
1984 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
1985 } else {
1986 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1987 }
François Gaffie11d30102018-11-02 16:09:09 +01001988 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001989 String8(attr->tags + strlen("addr=")),
1990 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001991 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001992 if (explicitRoutingDevice != nullptr) {
1993 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001994 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001995 // Prevent from storing invalid requested device id in clients
1996 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01001997 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001998 }
François Gaffie11d30102018-11-02 16:09:09 +01001999 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002000 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002001 status = BAD_VALUE;
2002 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002003 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002004 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002005 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2006 // there is an external policy, but this input is attached to a mix of recorders,
2007 // meaning it receives audio injected into the framework, so the recorder doesn't
2008 // know about it and is therefore considered "legacy"
2009 *inputType = API_INPUT_LEGACY;
2010 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002011 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002012 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002013 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002014 } else {
2015 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002016 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002017
Eric Laurent599c7582015-12-07 18:05:55 -08002018 }
2019
François Gaffiec005e562018-11-06 15:04:49 +01002020 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002021 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002022 status = INVALID_OPERATION;
2023 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002024 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002025
Eric Laurent8f42ea12018-08-08 09:08:25 -07002026exit:
2027
François Gaffiec005e562018-11-06 15:04:49 +01002028 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2029 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002030
Francois Gaffie716e1432019-01-14 16:58:59 +01002031 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002032 mSoundTriggerSessions.indexOfKey(session) > 0;
2033 *portId = AudioPort::getNextUniqueId();
2034
Eric Laurentf5d25e62019-03-25 16:33:26 -07002035 clientDesc = new RecordClientDescriptor(*portId, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002036 requestedDeviceId, attributes.source, flags,
2037 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002038 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002039 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002040
2041 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2042 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002043
Eric Laurent599c7582015-12-07 18:05:55 -08002044 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002045
2046error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002047 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002048}
2049
2050
François Gaffie11d30102018-11-02 16:09:09 +01002051audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002052 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002053 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002054 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002055 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002056 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002057{
2058 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002059 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002060 bool isSoundTrigger = false;
2061
François Gaffiec005e562018-11-06 15:04:49 +01002062 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002063 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2064 if (index >= 0) {
2065 input = mSoundTriggerSessions.valueFor(session);
2066 isSoundTrigger = true;
2067 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2068 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2069 } else {
2070 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002071 }
François Gaffiec005e562018-11-06 15:04:49 +01002072 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002073 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002074 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002075 }
2076
Andy Hungf129b032015-04-07 13:45:50 -07002077 // find a compatible input profile (not necessarily identical in parameters)
2078 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002079 // sampling rate and flags may be updated by getInputProfile
2080 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2081 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002082 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002083 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002084 audio_input_flags_t profileFlags = flags;
2085 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002086 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002087 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002088 profileFlags);
2089 if (profile != 0) {
2090 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002091 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2092 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002093 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2094 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2095 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002096 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2097 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2098 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002099 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002100 }
Eric Laurente552edb2014-03-10 17:42:56 -07002101 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002102 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002103 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002104 if (samplingRate == 0) {
2105 samplingRate = profileSamplingRate;
2106 }
Eric Laurente552edb2014-03-10 17:42:56 -07002107
Eric Laurent322b4d22015-04-03 15:57:54 -07002108 if (profile->getModuleHandle() == 0) {
2109 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002110 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002111 }
2112
Eric Laurent3974e3b2017-12-07 17:58:43 -08002113 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002114 for (size_t i = 0; i < mInputs.size(); ) {
2115 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2116 if (desc->mProfile != profile) {
2117 continue;
2118 }
2119 // if sound trigger, reuse input if used by other sound trigger on same session
2120 // else
2121 // reuse input if active client app is not in IDLE state
2122 //
2123 RecordClientVector clients = desc->clientsList();
2124 bool doClose = false;
2125 for (const auto& client : clients) {
2126 if (isSoundTrigger != client->isSoundTrigger()) {
2127 continue;
2128 }
2129 if (client->isSoundTrigger()) {
2130 if (session == client->session()) {
2131 return desc->mIoHandle;
2132 }
2133 continue;
2134 }
2135 if (client->active() && client->appState() != APP_STATE_IDLE) {
2136 return desc->mIoHandle;
2137 }
2138 doClose = true;
2139 }
2140 if (doClose) {
2141 closeInput(desc->mIoHandle);
2142 } else {
2143 i++;
2144 }
2145 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002146 }
2147
Eric Laurentfe231122017-11-17 17:48:06 -08002148 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002149
Eric Laurentfe231122017-11-17 17:48:06 -08002150 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2151 lConfig.sample_rate = profileSamplingRate;
2152 lConfig.channel_mask = profileChannelMask;
2153 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002154
François Gaffie11d30102018-11-02 16:09:09 +01002155 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002156
2157 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002158 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002159 (profileSamplingRate != lConfig.sample_rate) ||
2160 !audio_formats_match(profileFormat, lConfig.format) ||
2161 (profileChannelMask != lConfig.channel_mask)) {
2162 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002163 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002164 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002165 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002166 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002167 }
Eric Laurent599c7582015-12-07 18:05:55 -08002168 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002169 }
2170
Eric Laurentc722f302014-12-10 11:21:49 -08002171 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002172
Eric Laurent599c7582015-12-07 18:05:55 -08002173 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002174 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002175
Eric Laurent599c7582015-12-07 18:05:55 -08002176 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002177}
2178
Eric Laurent4eb58f12018-12-07 16:41:02 -08002179status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002180{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002181 ALOGV("%s portId %d", __FUNCTION__, portId);
2182
2183 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2184 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002185 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002186 return BAD_VALUE;
2187 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002188 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002189 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002190 if (client->active()) {
2191 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2192 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002193 }
2194
Eric Laurent8f42ea12018-08-08 09:08:25 -07002195 audio_session_t session = client->session();
2196
Eric Laurent4eb58f12018-12-07 16:41:02 -08002197 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002198
Eric Laurent4eb58f12018-12-07 16:41:02 -08002199 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002200
Eric Laurent4eb58f12018-12-07 16:41:02 -08002201 status_t status = inputDesc->start();
2202 if (status != NO_ERROR) {
2203 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002204 }
Eric Laurente552edb2014-03-10 17:42:56 -07002205
Eric Laurent4eb58f12018-12-07 16:41:02 -08002206 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002207 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002209
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 // indicate active capture to sound trigger service if starting capture from a mic on
2211 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002212 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002213 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002214
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 if (inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002216 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002217 // if input maps to a dynamic policy with an activity listener, notify of state change
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002218 if ((policyMix != NULL)
2219 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2220 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002221 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002222 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002223
François Gaffie11d30102018-11-02 16:09:09 +01002224 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2225 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002226 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2227 SoundTrigger::setCaptureState(true);
2228 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002229
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230 // automatically enable the remote submix output when input is started if not
2231 // used by a policy mix of type MIX_TYPE_RECORDERS
2232 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002233 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002234 String8 address = String8("");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002235 if (policyMix == NULL) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002236 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002237 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2238 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002239 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002240 if (address != "") {
2241 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2242 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002243 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002244 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002245 }
Eric Laurente552edb2014-03-10 17:42:56 -07002246 }
2247
Eric Laurent8f42ea12018-08-08 09:08:25 -07002248 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002249
Eric Laurente552edb2014-03-10 17:42:56 -07002250 return NO_ERROR;
2251}
2252
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002254{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002255 ALOGV("%s portId %d", __FUNCTION__, portId);
2256
2257 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2258 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002259 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002260 return BAD_VALUE;
2261 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002262 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002263 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002264 if (!client->active()) {
2265 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002266 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002267 }
2268
Eric Laurent8f42ea12018-08-08 09:08:25 -07002269 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002270
Eric Laurent8f42ea12018-08-08 09:08:25 -07002271 inputDesc->stop();
2272 if (inputDesc->isActive()) {
2273 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2274 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002275 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002276 // if input maps to a dynamic policy with an activity listener, notify of state change
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002277 if ((policyMix != NULL)
2278 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2279 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002280 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002281 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002282
2283 // automatically disable the remote submix output when input is stopped if not
2284 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002285 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002286 String8 address = String8("");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002287 if (policyMix == NULL) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002288 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002289 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2290 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002291 }
2292 if (address != "") {
2293 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2294 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002295 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002296 }
2297 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002298 resetInputDevice(input);
2299
2300 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2301 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002302 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2303 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002304 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2305 SoundTrigger::setCaptureState(false);
2306 }
2307 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002308 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002309 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002310}
2311
Eric Laurent8fc147b2018-07-22 19:13:55 -07002312void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002313{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002314 ALOGV("%s portId %d", __FUNCTION__, portId);
2315
2316 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2317 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002318 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002319 return;
2320 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002321 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002322 audio_io_handle_t input = inputDesc->mIoHandle;
2323
Eric Laurent8f42ea12018-08-08 09:08:25 -07002324 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002325
Andy Hung39efb7a2018-09-26 15:39:28 -07002326 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002327
Andy Hung39efb7a2018-09-26 15:39:28 -07002328 if (inputDesc->getClientCount() > 0) {
2329 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002330 return;
2331 }
2332
Eric Laurent05b90f82014-08-27 15:32:29 -07002333 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002334 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002335 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002336}
2337
Eric Laurent8f42ea12018-08-08 09:08:25 -07002338void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002339{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002340 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002341
2342 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002343 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002344 }
2345}
2346
Eric Laurent8f42ea12018-08-08 09:08:25 -07002347void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2348{
2349 stopInput(portId);
2350 releaseInput(portId);
2351}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002352
Eric Laurentd4692962014-05-05 18:13:44 -07002353void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002354 bool patchRemoved = false;
2355
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002356 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002357 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002358 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002359 if (patch_index >= 0) {
2360 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002361 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002362 mAudioPatches.removeItemsAt(patch_index);
2363 patchRemoved = true;
2364 }
Eric Laurentfe231122017-11-17 17:48:06 -08002365 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002366 }
2367 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002368 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002369 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002370
2371 if (patchRemoved) {
2372 mpClientInterface->onAudioPatchListUpdate();
2373 }
Eric Laurentd4692962014-05-05 18:13:44 -07002374}
2375
François Gaffie251c7f02018-11-07 10:41:08 +01002376void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002377{
2378 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002379 if (indexMin < 0 || indexMax < 0) {
2380 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2381 return;
2382 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002383 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002384
2385 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002386 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2387 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002388 continue;
2389 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002390 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002391 }
Eric Laurente552edb2014-03-10 17:42:56 -07002392}
2393
Eric Laurente0720872014-03-11 09:30:41 -07002394status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002395 int index,
2396 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002397{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002398 auto attributes = mEngine->getAttributesForStreamType(stream);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002399 ALOGV("%s: stream %s attributes=%s", __func__,
2400 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002401 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002402}
2403
Eric Laurente0720872014-03-11 09:30:41 -07002404status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002405 int *index,
2406 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002407{
François Gaffiec005e562018-11-06 15:04:49 +01002408 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2409 // stream by the engine.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002410 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
François Gaffiec005e562018-11-06 15:04:49 +01002411 device = mEngine->getOutputDevicesForStream(stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002412 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002413 return getVolumeIndex(getVolumeCurves(stream), *index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002414}
2415
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002416status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002417 int index,
2418 audio_devices_t device)
2419{
2420 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002421 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2422 if (group == VOLUME_GROUP_NONE) {
2423 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002424 return BAD_VALUE;
2425 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002426 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002427 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002428 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002429 VolumeSource vs = toVolumeSource(group);
2430 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2431
2432 status = setVolumeCurveIndex(index, device, curves);
2433 if (status != NO_ERROR) {
2434 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2435 return status;
2436 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002437
2438 audio_devices_t curSrcDevice;
2439 auto curCurvAttrs = curves.getAttributes();
2440 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2441 auto attr = curCurvAttrs.front();
2442 curSrcDevice = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
2443 } else if (!curves.getStreamTypes().empty()) {
2444 auto stream = curves.getStreamTypes().front();
2445 curSrcDevice = mEngine->getOutputDevicesForStream(stream, false).types();
2446 } else {
2447 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2448 return BAD_VALUE;
2449 }
2450 curSrcDevice = Volume::getDeviceForVolume(curSrcDevice);
2451
François Gaffiecfe17322018-11-07 13:41:29 +01002452 // update volume on all outputs and streams matching the following:
2453 // - The requested stream (or a stream matching for volume control) is active on the output
2454 // - The device (or devices) selected by the engine for this stream includes
2455 // the requested device
2456 // - For non default requested device, currently selected device on the output is either the
2457 // requested device or one of the devices selected by the engine for this stream
2458 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2459 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002460 for (size_t i = 0; i < mOutputs.size(); i++) {
2461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002462 audio_devices_t curDevice = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002463
2464 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2465 // If a higher priority strategy is active, and the output is routed to a device with a
2466 // HW Gain management, do not change the volume
2467 bool applyVolume = false;
2468 if (desc->useHwGain()) {
2469 if (!(desc->isActive(group) || isInCall())) {
2470 continue;
2471 }
2472 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2473 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2474 false /*preferredDevice*/);
2475 if (activeClients.empty()) {
2476 continue;
2477 }
2478 bool isPreempted = false;
2479 bool isHigherPriority = productStrategy < strategy;
2480 for (const auto &client : activeClients) {
2481 if (isHigherPriority && (client->volumeSource() != vs)) {
2482 ALOGV("%s: Strategy=%d (\nrequester:\n"
2483 " group %d, volumeGroup=%d attributes=%s)\n"
2484 " higher priority source active:\n"
2485 " volumeGroup=%d attributes=%s) \n"
2486 " on output %zu, bailing out", __func__, productStrategy,
2487 group, group, toString(attributes).c_str(),
2488 client->volumeSource(), toString(client->attributes()).c_str(), i);
2489 applyVolume = false;
2490 isPreempted = true;
2491 break;
2492 }
2493 // However, continue for loop to ensure no higher prio clients running on output
2494 if (client->volumeSource() == vs) {
2495 applyVolume = true;
2496 }
2497 }
2498 if (isPreempted || applyVolume) {
2499 break;
2500 }
2501 }
2502 if (!applyVolume) {
2503 continue; // next output
2504 }
2505 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevice,
2506 (vs == toVolumeSource(AUDIO_STREAM_SYSTEM)?
2507 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2508 if (volStatus != NO_ERROR) {
2509 status = volStatus;
2510 }
2511 continue;
2512 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002513 if (!(desc->isActive(vs) || isInCall())) {
2514 continue;
2515 }
2516 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) && ((curDevice & device) == 0)) {
2517 continue;
2518 }
2519 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2520 curSrcDevice |= device;
2521 applyVolume = (Volume::getDeviceForVolume(curDevice) & curSrcDevice) != 0;
2522 } else {
2523 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2524 }
2525 if (applyVolume) {
2526 //FIXME: workaround for truncated touch sounds
2527 // delayed volume change for system stream to be removed when the problem is
2528 // handled by system UI
2529 status_t volStatus = checkAndSetVolume(
2530 curves, vs, index, desc, curDevice,
2531 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2532 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2533 if (volStatus != NO_ERROR) {
2534 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002535 }
2536 }
2537 }
François Gaffiecfe17322018-11-07 13:41:29 +01002538 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2539 return status;
2540}
2541
François Gaffieaaac0fd2018-11-22 17:56:39 +01002542status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002543 audio_devices_t device,
2544 IVolumeCurves &volumeCurves)
2545{
2546 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2547 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002548 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2549 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002550 (index > volumeCurves.getVolumeIndexMax())) {
2551 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2552 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2553 return BAD_VALUE;
2554 }
2555 if (!audio_is_output_device(device)) {
2556 return BAD_VALUE;
2557 }
2558
2559 // Force max volume if stream cannot be muted
2560 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2561
François Gaffieaaac0fd2018-11-22 17:56:39 +01002562 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002563 volumeCurves.addCurrentVolumeIndex(device, index);
2564 return NO_ERROR;
2565}
2566
2567status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2568 int &index,
2569 audio_devices_t device)
2570{
2571 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2572 // stream by the engine.
2573 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2574 device = mEngine->getOutputDevicesForAttributes(attr, nullptr, true /*fromCache*/).types();
2575 }
2576 return getVolumeIndex(getVolumeCurves(attr), index, device);
2577}
2578
2579status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2580 int &index,
2581 audio_devices_t device) const
2582{
2583 if (!audio_is_output_device(device)) {
2584 return BAD_VALUE;
2585 }
2586 device = Volume::getDeviceForVolume(device);
2587 index = curves.getVolumeIndex(device);
2588 ALOGV("%s: device %08x index %d", __FUNCTION__, device, index);
2589 return NO_ERROR;
2590}
2591
2592status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2593 int &index)
2594{
2595 index = getVolumeCurves(attr).getVolumeIndexMin();
2596 return NO_ERROR;
2597}
2598
2599status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2600 int &index)
2601{
2602 index = getVolumeCurves(attr).getVolumeIndexMax();
2603 return NO_ERROR;
2604}
2605
Eric Laurent36829f92017-04-07 19:04:42 -07002606audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002607{
2608 // select one output among several suitable for global effects.
2609 // The priority is as follows:
2610 // 1: An offloaded output. If the effect ends up not being offloadable,
2611 // AudioFlinger will invalidate the track and the offloaded output
2612 // will be closed causing the effect to be moved to a PCM output.
2613 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002614 // 3: The primary output
2615 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002616
François Gaffiec005e562018-11-06 15:04:49 +01002617 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2618 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002619 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002620
Eric Laurent36829f92017-04-07 19:04:42 -07002621 if (outputs.size() == 0) {
2622 return AUDIO_IO_HANDLE_NONE;
2623 }
Eric Laurente552edb2014-03-10 17:42:56 -07002624
Eric Laurent36829f92017-04-07 19:04:42 -07002625 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2626 bool activeOnly = true;
2627
2628 while (output == AUDIO_IO_HANDLE_NONE) {
2629 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2630 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2631 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2632
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002633 for (audio_io_handle_t output : outputs) {
2634 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie1c878552018-11-22 16:53:21 +01002635 if (activeOnly && !desc->isActive(streamToVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002636 continue;
2637 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002638 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2639 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002640 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002641 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002642 }
2643 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002644 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002645 }
2646 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002647 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002648 }
2649 }
2650 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2651 output = outputOffloaded;
2652 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2653 output = outputDeepBuffer;
2654 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2655 output = outputPrimary;
2656 } else {
2657 output = outputs[0];
2658 }
2659 activeOnly = false;
2660 }
2661
2662 if (output != mMusicEffectOutput) {
2663 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2664 mMusicEffectOutput = output;
2665 }
2666
2667 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002668 return output;
2669}
2670
Eric Laurent36829f92017-04-07 19:04:42 -07002671audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2672{
2673 return selectOutputForMusicEffects();
2674}
2675
Eric Laurente0720872014-03-11 09:30:41 -07002676status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002677 audio_io_handle_t io,
2678 uint32_t strategy,
2679 int session,
2680 int id)
2681{
2682 ssize_t index = mOutputs.indexOfKey(io);
2683 if (index < 0) {
2684 index = mInputs.indexOfKey(io);
2685 if (index < 0) {
2686 ALOGW("registerEffect() unknown io %d", io);
2687 return INVALID_OPERATION;
2688 }
2689 }
François Gaffiec005e562018-11-06 15:04:49 +01002690 return mEffects.registerEffect(desc, io, session, id,
2691 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2692 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002693}
2694
Eric Laurentc241b0d2018-11-28 09:08:49 -08002695status_t AudioPolicyManager::unregisterEffect(int id)
2696{
2697 if (mEffects.getEffect(id) == nullptr) {
2698 return INVALID_OPERATION;
2699 }
2700
2701 if (mEffects.isEffectEnabled(id)) {
2702 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2703 setEffectEnabled(id, false);
2704 }
2705 return mEffects.unregisterEffect(id);
2706}
2707
2708status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2709{
2710 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2711 if (effect == nullptr) {
2712 return INVALID_OPERATION;
2713 }
2714
2715 status_t status = mEffects.setEffectEnabled(id, enabled);
2716 if (status == NO_ERROR) {
2717 mInputs.trackEffectEnabled(effect, enabled);
2718 }
2719 return status;
2720}
2721
Eric Laurentc75307b2015-03-17 15:29:32 -07002722bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2723{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002724 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002725}
2726
2727bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2728{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002729 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002730}
2731
Eric Laurente0720872014-03-11 09:30:41 -07002732bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002733{
2734 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002735 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002736 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002737 return true;
2738 }
2739 }
2740 return false;
2741}
2742
Eric Laurent275e8e92014-11-30 15:14:47 -08002743// Register a list of custom mixes with their attributes and format.
2744// When a mix is registered, corresponding input and output profiles are
2745// added to the remote submix hw module. The profile contains only the
2746// parameters (sampling rate, format...) specified by the mix.
2747// The corresponding input remote submix device is also connected.
2748//
2749// When a remote submix device is connected, the address is checked to select the
2750// appropriate profile and the corresponding input or output stream is opened.
2751//
2752// When capture starts, getInputForAttr() will:
2753// - 1 look for a mix matching the address passed in attribtutes tags if any
2754// - 2 if none found, getDeviceForInputSource() will:
2755// - 2.1 look for a mix matching the attributes source
2756// - 2.2 if none found, default to device selection by policy rules
2757// At this time, the corresponding output remote submix device is also connected
2758// and active playback use cases can be transferred to this mix if needed when reconnecting
2759// after AudioTracks are invalidated
2760//
2761// When playback starts, getOutputForAttr() will:
2762// - 1 look for a mix matching the address passed in attribtutes tags if any
2763// - 2 if none found, look for a mix matching the attributes usage
2764// - 3 if none found, default to device and output selection by policy rules.
2765
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002766status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002767{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002768 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2769 status_t res = NO_ERROR;
2770
2771 sp<HwModule> rSubmixModule;
2772 // examine each mix's route type
2773 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002774 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002775 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2776 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2777 ALOGE("Unsupported Policy Mix %zu of %zu: "
2778 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2779 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002780 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002781 break;
2782 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002783 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2784 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002785 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002786 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2787 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002788 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002789 rSubmixModule = mHwModules.getModuleFromName(
2790 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2791 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002792 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002793 i);
2794 res = INVALID_OPERATION;
2795 break;
2796 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002797 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002798
Eric Laurent97ac8712018-07-27 18:59:02 -07002799 String8 address = mix.mDeviceAddress;
2800 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2801 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2802 } else {
2803 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2804 }
François Gaffie036e1e92015-03-19 10:16:24 +01002805
Eric Laurent97ac8712018-07-27 18:59:02 -07002806 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002807 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002808 res = INVALID_OPERATION;
2809 break;
2810 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002811 audio_config_t outputConfig = mix.mFormat;
2812 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002813 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2814 // stereo and let audio flinger do the channel conversion if needed.
2815 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2816 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2817 rSubmixModule->addOutputProfile(address, &outputConfig,
2818 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2819 rSubmixModule->addInputProfile(address, &inputConfig,
2820 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002821
Eric Laurent97ac8712018-07-27 18:59:02 -07002822 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002823 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2824 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002825 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002826 } else {
2827 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2828 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002829 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002830 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002831 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2832 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002833 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002834 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002835 i, mixes.size(), type, address.string());
2836
2837 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2838 mix.mDeviceType, mix.mDeviceAddress,
2839 String8(), AUDIO_FORMAT_DEFAULT);
2840 if (device == nullptr) {
2841 res = INVALID_OPERATION;
2842 break;
2843 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002844
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002845 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002846 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2847 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002848
2849 if (desc->supportedDevices().contains(device)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002850 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002851 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2852 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002853 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002854 } else {
2855 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002856 }
2857 break;
2858 }
2859 }
2860
2861 if (res != NO_ERROR) {
2862 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002863 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002864 res = INVALID_OPERATION;
2865 break;
2866 } else if (!foundOutput) {
2867 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002868 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002869 res = INVALID_OPERATION;
2870 break;
2871 }
Eric Laurentc722f302014-12-10 11:21:49 -08002872 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002873 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002874 if (res != NO_ERROR) {
2875 unregisterPolicyMixes(mixes);
2876 }
2877 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002878}
2879
2880status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2881{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002882 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002883 status_t res = NO_ERROR;
2884 sp<HwModule> rSubmixModule;
2885 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002886 for (const auto& mix : mixes) {
2887 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002888
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002889 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002890 rSubmixModule = mHwModules.getModuleFromName(
2891 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2892 if (rSubmixModule == 0) {
2893 res = INVALID_OPERATION;
2894 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002895 }
2896 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002897
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002898 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002899
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002900 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2901 res = INVALID_OPERATION;
2902 continue;
2903 }
2904
2905 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2906 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2907 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2908 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002909 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002910 }
2911 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2912 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2913 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2914 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002915 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002916 }
2917 rSubmixModule->removeOutputProfile(address);
2918 rSubmixModule->removeInputProfile(address);
2919
Kevin Rocard153f92d2018-12-18 18:33:28 -08002920 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002921 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002922 res = INVALID_OPERATION;
2923 continue;
2924 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002925 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002926 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002927 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002928}
2929
Mikhail Naganov100f0122018-11-29 11:22:16 -08002930void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2931{
2932 size_t i = 0;
2933 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2934 for (const auto& fmt : mManualSurroundFormats) {
2935 if (i++ != 0) dst->append(", ");
2936 std::string sfmt;
2937 FormatConverter::toString(fmt, sfmt);
2938 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2939 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2940 }
2941}
2942
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002943status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2944 const Vector<AudioDeviceTypeAddr>& devices) {
2945 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2946 // uid/device affinity is only for output devices
2947 for (size_t i = 0; i < devices.size(); i++) {
2948 if (!audio_is_output_device(devices[i].mType)) {
2949 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2950 devices[i].mType);
2951 return BAD_VALUE;
2952 }
2953 }
2954 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2955 if (res == NO_ERROR) {
2956 // reevaluate outputs for all given devices
2957 for (size_t i = 0; i < devices.size(); i++) {
2958 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002959 devices[i].mType, devices[i].mAddress, String8(),
2960 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002961 SortedVector<audio_io_handle_t> outputs;
2962 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002963 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002964 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2965 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2966 return INVALID_OPERATION;
2967 }
2968 }
2969 }
2970 return res;
2971}
2972
2973status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2974 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2975 Vector<AudioDeviceTypeAddr> devices;
2976 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2977 if (res == NO_ERROR) {
2978 // reevaluate outputs for all found devices
2979 for (size_t i = 0; i < devices.size(); i++) {
2980 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002981 devices[i].mType, devices[i].mAddress, String8(),
2982 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002983 SortedVector<audio_io_handle_t> outputs;
2984 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002985 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002986 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2987 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2988 return INVALID_OPERATION;
2989 }
2990 }
2991 }
2992
2993 return res;
2994}
2995
Andy Hungc29d82b2018-10-05 12:23:17 -07002996void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002997{
Andy Hungc29d82b2018-10-05 12:23:17 -07002998 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2999 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003000 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003001 std::string stateLiteral;
3002 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003003 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003004 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3005 "communications", "media", "record", "dock", "system",
3006 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3007 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3008 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003009 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3010 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3011 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3012 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3013 dst->append(" (MANUAL: ");
3014 dumpManualSurroundFormats(dst);
3015 dst->append(")");
3016 }
3017 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003018 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003019 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3020 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
3021 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
3022 mAvailableOutputDevices.dump(dst, String8("Available output"));
3023 mAvailableInputDevices.dump(dst, String8("Available input"));
3024 mHwModulesAll.dump(dst);
3025 mOutputs.dump(dst);
3026 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003027 mEffects.dump(dst);
3028 mAudioPatches.dump(dst);
3029 mPolicyMixes.dump(dst);
3030 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003031
3032 dst->appendFormat("\nPolicy Engine dump:\n");
3033 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003034}
3035
3036status_t AudioPolicyManager::dump(int fd)
3037{
3038 String8 result;
3039 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003040 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003041 return NO_ERROR;
3042}
3043
3044// This function checks for the parameters which can be offloaded.
3045// This can be enhanced depending on the capability of the DSP and policy
3046// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07003047bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003048{
3049 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003050 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07003051 offloadInfo.sample_rate, offloadInfo.channel_mask,
3052 offloadInfo.format,
3053 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3054 offloadInfo.has_video);
3055
Andy Hung2ddee192015-12-18 17:34:44 -08003056 if (mMasterMono) {
3057 return false; // no offloading if mono is set.
3058 }
3059
Eric Laurente552edb2014-03-10 17:42:56 -07003060 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003061 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3062 ALOGV("offload disabled by audio.offload.disable");
3063 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07003064 }
3065
3066 // Check if stream type is music, then only allow offload as of now.
3067 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3068 {
3069 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
3070 return false;
3071 }
3072
3073 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003074 const bool allowOffloadWithVideo =
3075 property_get_bool("audio.offload.video", false /* default_value */);
3076 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07003077 ALOGV("isOffloadSupported: has_video == true, returning false");
3078 return false;
3079 }
3080
3081 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003082 const int min_duration_secs = property_get_int32(
3083 "audio.offload.min.duration.secs", -1 /* default_value */);
3084 if (min_duration_secs >= 0) {
3085 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3086 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3087 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07003088 return false;
3089 }
3090 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3091 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3092 return false;
3093 }
3094
3095 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3096 // creating an offloaded track and tearing it down immediately after start when audioflinger
3097 // detects there is an active non offloadable effect.
3098 // FIXME: We should check the audio session here but we do not have it in this context.
3099 // This may prevent offloading in rare situations where effects are left active by apps
3100 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003101 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003102 return false;
3103 }
3104
3105 // See if there is a profile to support this.
3106 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003107 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003108 offloadInfo.sample_rate,
3109 offloadInfo.format,
3110 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003111 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3112 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07003113 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
3114 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003115}
3116
Michael Chana94fbb22018-04-24 14:31:19 +10003117bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3118 const audio_attributes_t& attributes) {
3119 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003120 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003121 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003122 config.sample_rate,
3123 config.format,
3124 config.channel_mask,
3125 output_flags,
3126 true /* directOnly */);
3127 ALOGV("%s() profile %sfound with name: %s, "
3128 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3129 __FUNCTION__, profile != 0 ? "" : "NOT ",
3130 (profile != 0 ? profile->getTagName().string() : "null"),
3131 config.sample_rate, config.format, config.channel_mask, output_flags);
3132 return (profile != 0);
3133}
3134
Eric Laurent6a94d692014-05-20 11:18:06 -07003135status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3136 audio_port_type_t type,
3137 unsigned int *num_ports,
3138 struct audio_port *ports,
3139 unsigned int *generation)
3140{
3141 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3142 generation == NULL) {
3143 return BAD_VALUE;
3144 }
3145 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3146 if (ports == NULL) {
3147 *num_ports = 0;
3148 }
3149
3150 size_t portsWritten = 0;
3151 size_t portsMax = *num_ports;
3152 *num_ports = 0;
3153 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003154 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3155 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003156 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003157 for (const auto& dev : mAvailableOutputDevices) {
3158 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003159 continue;
3160 }
3161 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003162 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003163 }
3164 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003165 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003166 }
3167 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003168 for (const auto& dev : mAvailableInputDevices) {
3169 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003170 continue;
3171 }
3172 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003173 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003174 }
3175 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003177 }
3178 }
3179 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3180 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3181 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3182 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3183 }
3184 *num_ports += mInputs.size();
3185 }
3186 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003187 size_t numOutputs = 0;
3188 for (size_t i = 0; i < mOutputs.size(); i++) {
3189 if (!mOutputs[i]->isDuplicated()) {
3190 numOutputs++;
3191 if (portsWritten < portsMax) {
3192 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3193 }
3194 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003195 }
Eric Laurent84c70242014-06-23 08:46:27 -07003196 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 }
3198 }
3199 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003200 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003201 return NO_ERROR;
3202}
3203
Eric Laurent99fcae42018-05-17 16:59:18 -07003204status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003205{
Eric Laurent99fcae42018-05-17 16:59:18 -07003206 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3207 return BAD_VALUE;
3208 }
3209 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3210 if (dev != 0) {
3211 dev->toAudioPort(port);
3212 return NO_ERROR;
3213 }
3214 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3215 if (dev != 0) {
3216 dev->toAudioPort(port);
3217 return NO_ERROR;
3218 }
3219 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3220 if (out != 0) {
3221 out->toAudioPort(port);
3222 return NO_ERROR;
3223 }
3224 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3225 if (in != 0) {
3226 in->toAudioPort(port);
3227 return NO_ERROR;
3228 }
3229 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003230}
3231
Eric Laurent6a94d692014-05-20 11:18:06 -07003232status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3233 audio_patch_handle_t *handle,
3234 uid_t uid)
3235{
3236 ALOGV("createAudioPatch()");
3237
3238 if (handle == NULL || patch == NULL) {
3239 return BAD_VALUE;
3240 }
3241 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3242
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003243 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003244 return BAD_VALUE;
3245 }
3246 // only one source per audio patch supported for now
3247 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003248 return INVALID_OPERATION;
3249 }
Eric Laurent874c42872014-08-08 15:13:39 -07003250
3251 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003252 return INVALID_OPERATION;
3253 }
Eric Laurent874c42872014-08-08 15:13:39 -07003254 for (size_t i = 0; i < patch->num_sinks; i++) {
3255 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3256 return INVALID_OPERATION;
3257 }
3258 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003259
3260 sp<AudioPatch> patchDesc;
3261 ssize_t index = mAudioPatches.indexOfKey(*handle);
3262
Eric Laurent6a94d692014-05-20 11:18:06 -07003263 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3264 patch->sources[0].role,
3265 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003266#if LOG_NDEBUG == 0
3267 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003268 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003269 patch->sinks[i].role,
3270 patch->sinks[i].type);
3271 }
3272#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003273
3274 if (index >= 0) {
3275 patchDesc = mAudioPatches.valueAt(index);
3276 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3277 mUidCached, patchDesc->mUid, uid);
3278 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3279 return INVALID_OPERATION;
3280 }
3281 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003282 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003283 }
3284
3285 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003286 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003287 if (outputDesc == NULL) {
3288 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3289 return BAD_VALUE;
3290 }
Eric Laurent84c70242014-06-23 08:46:27 -07003291 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3292 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003293 if (patchDesc != 0) {
3294 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3295 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3296 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3297 return BAD_VALUE;
3298 }
3299 }
Eric Laurent874c42872014-08-08 15:13:39 -07003300 DeviceVector devices;
3301 for (size_t i = 0; i < patch->num_sinks; i++) {
3302 // Only support mix to devices connection
3303 // TODO add support for mix to mix connection
3304 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3305 ALOGV("createAudioPatch() source mix but sink is not a device");
3306 return INVALID_OPERATION;
3307 }
3308 sp<DeviceDescriptor> devDesc =
3309 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3310 if (devDesc == 0) {
3311 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3312 return BAD_VALUE;
3313 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003314
François Gaffie11d30102018-11-02 16:09:09 +01003315 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003316 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003317 NULL, // updatedSamplingRate
3318 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003319 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003320 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003321 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003322 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003323 ALOGV("createAudioPatch() profile not supported for device %08x",
3324 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003325 return INVALID_OPERATION;
3326 }
3327 devices.add(devDesc);
3328 }
3329 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003330 return INVALID_OPERATION;
3331 }
Eric Laurent874c42872014-08-08 15:13:39 -07003332
Eric Laurent6a94d692014-05-20 11:18:06 -07003333 // TODO: reconfigure output format and channels here
3334 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003335 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003336 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003337 index = mAudioPatches.indexOfKey(*handle);
3338 if (index >= 0) {
3339 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3340 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3341 }
3342 patchDesc = mAudioPatches.valueAt(index);
3343 patchDesc->mUid = uid;
3344 ALOGV("createAudioPatch() success");
3345 } else {
3346 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3347 return INVALID_OPERATION;
3348 }
3349 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3350 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3351 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003352 // only one sink supported when connecting an input device to a mix
3353 if (patch->num_sinks > 1) {
3354 return INVALID_OPERATION;
3355 }
François Gaffie53615e22015-03-19 09:24:12 +01003356 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003357 if (inputDesc == NULL) {
3358 return BAD_VALUE;
3359 }
3360 if (patchDesc != 0) {
3361 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3362 return BAD_VALUE;
3363 }
3364 }
François Gaffie11d30102018-11-02 16:09:09 +01003365 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003366 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003367 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003368 return BAD_VALUE;
3369 }
3370
François Gaffie11d30102018-11-02 16:09:09 +01003371 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003372 patch->sinks[0].sample_rate,
3373 NULL, /*updatedSampleRate*/
3374 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003375 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003376 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003377 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003378 // FIXME for the parameter type,
3379 // and the NONE
3380 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003381 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003382 return INVALID_OPERATION;
3383 }
3384 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003385 ALOGV("%s() setting device %s on output %d", __func__,
3386 device->toString().c_str(), inputDesc->mIoHandle);
3387 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003388 index = mAudioPatches.indexOfKey(*handle);
3389 if (index >= 0) {
3390 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3391 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3392 }
3393 patchDesc = mAudioPatches.valueAt(index);
3394 patchDesc->mUid = uid;
3395 ALOGV("createAudioPatch() success");
3396 } else {
3397 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3398 return INVALID_OPERATION;
3399 }
3400 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3401 // device to device connection
3402 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003403 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003404 return BAD_VALUE;
3405 }
3406 }
François Gaffie11d30102018-11-02 16:09:09 +01003407 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003408 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003409 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003410 return BAD_VALUE;
3411 }
Eric Laurent874c42872014-08-08 15:13:39 -07003412
Eric Laurent6a94d692014-05-20 11:18:06 -07003413 //update source and sink with our own data as the data passed in the patch may
3414 // be incomplete.
3415 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003416 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003417
Eric Laurent874c42872014-08-08 15:13:39 -07003418 for (size_t i = 0; i < patch->num_sinks; i++) {
3419 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3420 ALOGV("createAudioPatch() source device but one sink is not a device");
3421 return INVALID_OPERATION;
3422 }
3423
François Gaffie11d30102018-11-02 16:09:09 +01003424 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003425 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003426 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003427 return BAD_VALUE;
3428 }
François Gaffie11d30102018-11-02 16:09:09 +01003429 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003430
Eric Laurent3bcf8592015-04-03 12:13:24 -07003431 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003432 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003433 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003434 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003435 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3436 (srcDevice->getModuleVersionMajor() < 3) ||
3437 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003438 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003439 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003440 return INVALID_OPERATION;
3441 }
Eric Laurent874c42872014-08-08 15:13:39 -07003442 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003443 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003444 // if the sink device is reachable via an opened output stream, request to go via
3445 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003446 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003447 if (output != AUDIO_IO_HANDLE_NONE) {
3448 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3449 if (outputDesc->isDuplicated()) {
3450 return INVALID_OPERATION;
3451 }
3452 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003453 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003454 newPatch.num_sources = 2;
3455 }
Eric Laurent83b88082014-06-20 18:31:16 -07003456 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003457 }
3458 // TODO: check from routing capabilities in config file and other conflicting patches
3459
Mikhail Naganovdc769682018-05-04 15:34:08 -07003460 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3461 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003462 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3463 status);
3464 return INVALID_OPERATION;
3465 }
3466 } else {
3467 return BAD_VALUE;
3468 }
3469 } else {
3470 return BAD_VALUE;
3471 }
3472 return NO_ERROR;
3473}
3474
3475status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3476 uid_t uid)
3477{
3478 ALOGV("releaseAudioPatch() patch %d", handle);
3479
3480 ssize_t index = mAudioPatches.indexOfKey(handle);
3481
3482 if (index < 0) {
3483 return BAD_VALUE;
3484 }
3485 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3486 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3487 mUidCached, patchDesc->mUid, uid);
3488 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3489 return INVALID_OPERATION;
3490 }
3491
3492 struct audio_patch *patch = &patchDesc->mPatch;
3493 patchDesc->mUid = mUidCached;
3494 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003495 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003496 if (outputDesc == NULL) {
3497 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3498 return BAD_VALUE;
3499 }
3500
François Gaffie11d30102018-11-02 16:09:09 +01003501 setOutputDevices(outputDesc,
3502 getNewOutputDevices(outputDesc, true /*fromCache*/),
3503 true,
3504 0,
3505 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003506 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3507 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003508 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003509 if (inputDesc == NULL) {
3510 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3511 return BAD_VALUE;
3512 }
3513 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003514 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003515 true,
3516 NULL);
3517 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003518 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3519 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3520 status, patchDesc->mAfPatchHandle);
3521 removeAudioPatch(patchDesc->mHandle);
3522 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003523 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003524 } else {
3525 return BAD_VALUE;
3526 }
3527 } else {
3528 return BAD_VALUE;
3529 }
3530 return NO_ERROR;
3531}
3532
3533status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3534 struct audio_patch *patches,
3535 unsigned int *generation)
3536{
François Gaffie53615e22015-03-19 09:24:12 +01003537 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003538 return BAD_VALUE;
3539 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003540 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003541 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003542}
3543
Eric Laurente1715a42014-05-20 11:30:42 -07003544status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003545{
Eric Laurente1715a42014-05-20 11:30:42 -07003546 ALOGV("setAudioPortConfig()");
3547
3548 if (config == NULL) {
3549 return BAD_VALUE;
3550 }
3551 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3552 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003553 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3554 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003555 }
3556
Eric Laurenta121f902014-06-03 13:32:54 -07003557 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003558 if (config->type == AUDIO_PORT_TYPE_MIX) {
3559 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003560 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003561 if (outputDesc == NULL) {
3562 return BAD_VALUE;
3563 }
Eric Laurent84c70242014-06-23 08:46:27 -07003564 ALOG_ASSERT(!outputDesc->isDuplicated(),
3565 "setAudioPortConfig() called on duplicated output %d",
3566 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003567 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003568 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003569 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003570 if (inputDesc == NULL) {
3571 return BAD_VALUE;
3572 }
Eric Laurenta121f902014-06-03 13:32:54 -07003573 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003574 } else {
3575 return BAD_VALUE;
3576 }
3577 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3578 sp<DeviceDescriptor> deviceDesc;
3579 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3580 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3581 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3582 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3583 } else {
3584 return BAD_VALUE;
3585 }
3586 if (deviceDesc == NULL) {
3587 return BAD_VALUE;
3588 }
Eric Laurenta121f902014-06-03 13:32:54 -07003589 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003590 } else {
3591 return BAD_VALUE;
3592 }
3593
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003594 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003595 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3596 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003597 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003598 audioPortConfig->toAudioPortConfig(&newConfig, config);
3599 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003600 }
Eric Laurenta121f902014-06-03 13:32:54 -07003601 if (status != NO_ERROR) {
3602 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003603 }
Eric Laurente1715a42014-05-20 11:30:42 -07003604
3605 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003606}
3607
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003608void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3609{
Eric Laurentd60560a2015-04-10 11:31:20 -07003610 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003611 clearAudioPatches(uid);
3612 clearSessionRoutes(uid);
3613}
3614
Eric Laurent6a94d692014-05-20 11:18:06 -07003615void AudioPolicyManager::clearAudioPatches(uid_t uid)
3616{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003617 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003618 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3619 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003620 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003621 }
3622 }
3623}
3624
François Gaffiec005e562018-11-06 15:04:49 +01003625void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003626{
François Gaffiec005e562018-11-06 15:04:49 +01003627 // Take the first attributes following the product strategy as it is used to retrieve the routed
3628 // device. All attributes wihin a strategy follows the same "routing strategy"
3629 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
3630 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01003631 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003632 for (size_t j = 0; j < mOutputs.size(); j++) {
3633 if (mOutputs.keyAt(j) == ouptutToSkip) {
3634 continue;
3635 }
3636 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01003637 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003638 continue;
3639 }
3640 // If the default device for this strategy is on another output mix,
3641 // invalidate all tracks in this strategy to force re connection.
3642 // Otherwise select new device on the output mix.
3643 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01003644 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
3645 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003646 }
3647 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003648 setOutputDevices(
3649 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003650 }
3651 }
3652}
3653
3654void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3655{
3656 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01003657 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003658 for (size_t i = 0; i < mOutputs.size(); i++) {
3659 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003660 for (const auto& client : outputDesc->getClientIterable()) {
3661 if (client->hasPreferredDevice() && client->uid() == uid) {
3662 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01003663 auto clientStrategy = client->strategy();
3664 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
3665 end(affectedStrategies)) {
3666 continue;
3667 }
3668 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003669 }
3670 }
3671 }
3672 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003673 for (const auto& strategy : affectedStrategies) {
3674 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003675 }
3676
3677 // remove input routes associated with this uid
3678 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003679 for (size_t i = 0; i < mInputs.size(); i++) {
3680 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003681 for (const auto& client : inputDesc->getClientIterable()) {
3682 if (client->hasPreferredDevice() && client->uid() == uid) {
3683 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3684 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003685 }
3686 }
3687 }
3688 // reroute inputs if necessary
3689 SortedVector<audio_io_handle_t> inputsToClose;
3690 for (size_t i = 0; i < mInputs.size(); i++) {
3691 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003692 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003693 inputsToClose.add(inputDesc->mIoHandle);
3694 }
3695 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003696 for (const auto& input : inputsToClose) {
3697 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003698 }
3699}
3700
Eric Laurentd60560a2015-04-10 11:31:20 -07003701void AudioPolicyManager::clearAudioSources(uid_t uid)
3702{
3703 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003704 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3705 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003706 stopAudioSource(mAudioSources.keyAt(i));
3707 }
3708 }
3709}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003710
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003711status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3712 audio_io_handle_t *ioHandle,
3713 audio_devices_t *device)
3714{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003715 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3716 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003717 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01003718 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003719
François Gaffiedf372692015-03-19 10:43:27 +01003720 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003721}
3722
Eric Laurentd60560a2015-04-10 11:31:20 -07003723status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003724 const audio_attributes_t *attributes,
3725 audio_port_handle_t *portId,
3726 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003727{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003728 ALOGV("%s", __FUNCTION__);
3729 *portId = AUDIO_PORT_HANDLE_NONE;
3730
3731 if (source == NULL || attributes == NULL || portId == NULL) {
3732 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3733 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003734 return BAD_VALUE;
3735 }
3736
Eric Laurentd60560a2015-04-10 11:31:20 -07003737 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3738 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003739 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3740 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003741 return INVALID_OPERATION;
3742 }
3743
François Gaffie11d30102018-11-02 16:09:09 +01003744 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003745 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003746 String8(source->ext.device.address),
3747 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003748 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003749 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003750 return BAD_VALUE;
3751 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003752
3753 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003754
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003755 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003756 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003757
François Gaffieaaac0fd2018-11-22 17:56:39 +01003758 sp<SourceClientDescriptor> sourceDesc =
3759 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
3760 mEngine->getStreamTypeForAttributes(*attributes),
3761 mEngine->getProductStrategyForAttributes(*attributes),
3762 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003763
3764 status_t status = connectAudioSource(sourceDesc);
3765 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003766 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003767 }
3768 return status;
3769}
3770
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003771status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003772{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003773 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003774
3775 // make sure we only have one patch per source.
3776 disconnectAudioSource(sourceDesc);
3777
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003778 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003779 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003780 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003781
François Gaffiec005e562018-11-06 15:04:49 +01003782 DeviceVector sinkDevices =
3783 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
3784 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01003785 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3786 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3787 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003788
3789 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003790
François Gaffie11d30102018-11-02 16:09:09 +01003791 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3792 srcDevice->getModuleVersionMajor() >= 3 &&
3793 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3794 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003795 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003796 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003797 // create patch between src device and output device
3798 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003799 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003800 audio_attributes_t resultAttr;
3801 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3802 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3803 config.sample_rate = sourceDesc->config().sample_rate;
3804 config.channel_mask = sourceDesc->config().channel_mask;
3805 config.format = sourceDesc->config().format;
3806 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3807 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffief579db52018-11-13 11:25:16 +01003808 bool isRequestedDeviceForExclusiveUse = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08003809 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputs;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003810 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
François Gaffief579db52018-11-13 11:25:16 +01003811 &attributes, &stream, sourceDesc->uid(), &config, &flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -08003812 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3813 &secondaryOutputs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003814 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003815 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003816 return INVALID_OPERATION;
3817 }
3818 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3819 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003820 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003821 return INVALID_OPERATION;
3822 }
Eric Laurent733ce942017-12-07 12:18:25 -08003823 status_t status = outputDesc->start();
3824 if (status != NO_ERROR) {
3825 return status;
3826 }
3827
Eric Laurentd60560a2015-04-10 11:31:20 -07003828 // create a special patch with no sink and two sources:
3829 // - the second source indicates to PatchPanel through which output mix this patch should
3830 // be connected as well as the stream type for volume control
3831 // - the sink is defined by whatever output device is currently selected for the output
3832 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003833 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003834 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003835 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003836 &afPatchHandle,
3837 0);
3838 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3839 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003840 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003841 if (status != NO_ERROR) {
3842 ALOGW("%s patch panel could not connect device patch, error %d",
3843 __FUNCTION__, status);
3844 return INVALID_OPERATION;
3845 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003846
3847 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3848 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3849 return INVALID_OPERATION;
3850 }
3851 outputDesc->addClient(sourceDesc);
3852
Eric Laurentd60560a2015-04-10 11:31:20 -07003853 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003854 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003855
3856 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003857 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003858 return status;
3859 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003860 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003861 if (delayMs != 0) {
3862 usleep(delayMs * 1000);
3863 }
3864 }
3865
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003866 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3867 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003868
3869 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003870}
3871
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003872status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003873{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003874 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3875 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003876 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003877 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003878 return BAD_VALUE;
3879 }
3880 status_t status = disconnectAudioSource(sourceDesc);
3881
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003882 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003883 return status;
3884}
3885
Andy Hung2ddee192015-12-18 17:34:44 -08003886status_t AudioPolicyManager::setMasterMono(bool mono)
3887{
3888 if (mMasterMono == mono) {
3889 return NO_ERROR;
3890 }
3891 mMasterMono = mono;
3892 // if enabling mono we close all offloaded devices, which will invalidate the
3893 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3894 // for recreating the new AudioTrack as non-offloaded PCM.
3895 //
3896 // If disabling mono, we leave all tracks as is: we don't know which clients
3897 // and tracks are able to be recreated as offloaded. The next "song" should
3898 // play back offloaded.
3899 if (mMasterMono) {
3900 Vector<audio_io_handle_t> offloaded;
3901 for (size_t i = 0; i < mOutputs.size(); ++i) {
3902 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3903 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3904 offloaded.push(desc->mIoHandle);
3905 }
3906 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003907 for (const auto& handle : offloaded) {
3908 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003909 }
3910 }
3911 // update master mono for all remaining outputs
3912 for (size_t i = 0; i < mOutputs.size(); ++i) {
3913 updateMono(mOutputs.keyAt(i));
3914 }
3915 return NO_ERROR;
3916}
3917
3918status_t AudioPolicyManager::getMasterMono(bool *mono)
3919{
3920 *mono = mMasterMono;
3921 return NO_ERROR;
3922}
3923
Eric Laurentac9cef52017-06-09 15:46:26 -07003924float AudioPolicyManager::getStreamVolumeDB(
3925 audio_stream_type_t stream, int index, audio_devices_t device)
3926{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003927 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, device);
Eric Laurentac9cef52017-06-09 15:46:26 -07003928}
3929
jiabin81772902018-04-02 17:52:27 -07003930status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3931 audio_format_t *surroundFormats,
3932 bool *surroundFormatsEnabled,
3933 bool reported)
3934{
3935 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3936 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3937 return BAD_VALUE;
3938 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003939 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3940 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003941
3942 size_t formatsWritten = 0;
3943 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003944 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003945 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003946 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003947 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003948 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3949 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3950 FormatVector supportedFormats =
3951 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3952 for (size_t j = 0; j < supportedFormats.size(); j++) {
3953 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3954 formats.insert(supportedFormats[j]);
3955 } else {
3956 for (const auto& pair : mConfig.getSurroundFormats()) {
3957 if (pair.second.count(supportedFormats[j]) != 0) {
3958 formats.insert(pair.first);
3959 break;
3960 }
3961 }
3962 }
3963 }
jiabin81772902018-04-02 17:52:27 -07003964 }
3965 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003966 for (const auto& pair : mConfig.getSurroundFormats()) {
3967 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003968 }
3969 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003970 *numSurroundFormats = formats.size();
3971 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3972 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003973 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003974 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003975 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003976 bool formatEnabled = true;
3977 switch (forceUse) {
3978 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3979 formatEnabled = mManualSurroundFormats.count(format) != 0;
3980 break;
3981 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3982 formatEnabled = false;
3983 break;
3984 default: // AUTO or ALWAYS => true
3985 break;
jiabin81772902018-04-02 17:52:27 -07003986 }
3987 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3988 }
jiabin81772902018-04-02 17:52:27 -07003989 }
3990 return NO_ERROR;
3991}
3992
3993status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3994{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003995 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003996 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3997 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003998 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003999 return BAD_VALUE;
4000 }
4001
Mikhail Naganov100f0122018-11-29 11:22:16 -08004002 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4003 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004004 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004005 return INVALID_OPERATION;
4006 }
4007
Mikhail Naganov100f0122018-11-29 11:22:16 -08004008 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004009 return NO_ERROR;
4010 }
4011
Mikhail Naganov100f0122018-11-29 11:22:16 -08004012 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004013 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004014 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004015 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004016 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004017 }
4018 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004019 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004020 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004021 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004022 }
4023 }
4024
4025 sp<SwAudioOutputDescriptor> outputDesc;
4026 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07004027 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07004028 AUDIO_DEVICE_OUT_HDMI);
4029 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4030 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02004031 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07004032 String8 name = hdmiOutputDevices[i]->getName();
4033 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4034 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4035 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004036 name.c_str(),
4037 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004038 if (status != NO_ERROR) {
4039 continue;
4040 }
4041 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4042 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4043 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004044 name.c_str(),
4045 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004046 profileUpdated |= (status == NO_ERROR);
4047 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004048 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07004049 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07004050 AUDIO_DEVICE_IN_HDMI);
4051 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4052 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02004053 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07004054 String8 name = hdmiInputDevices[i]->getName();
4055 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4056 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4057 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004058 name.c_str(),
4059 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004060 if (status != NO_ERROR) {
4061 continue;
4062 }
4063 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4064 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4065 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004066 name.c_str(),
4067 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004068 profileUpdated |= (status == NO_ERROR);
4069 }
4070
jiabin81772902018-04-02 17:52:27 -07004071 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004072 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004073 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004074 }
4075
4076 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4077}
4078
Eric Laurentf32108e2018-10-04 17:22:04 -07004079void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004080{
Eric Laurent4eb58f12018-12-07 16:41:02 -08004081 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004082
Eric Laurenta9f86652018-11-28 17:23:11 -08004083 for (size_t i = 0; i < mInputs.size(); i++) {
4084 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
4085 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07004086 for (const auto& client : clients) {
4087 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08004088 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004089 }
4090 }
4091 }
4092}
4093
jiabin6012f912018-11-02 17:06:30 -07004094bool AudioPolicyManager::isHapticPlaybackSupported()
4095{
4096 for (const auto& hwModule : mHwModules) {
4097 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4098 for (const auto &outProfile : outputProfiles) {
4099 struct audio_port audioPort;
4100 outProfile->toAudioPort(&audioPort);
4101 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4102 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4103 return true;
4104 }
4105 }
4106 }
4107 }
4108 return false;
4109}
4110
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004111status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004112{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004113 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004114
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004115 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07004116 if (patchDesc == 0) {
4117 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004118 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07004119 return BAD_VALUE;
4120 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004121 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07004122
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004123 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004124 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004125 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004126 if (status == NO_ERROR) {
4127 swOutputDesc->stop();
4128 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004129 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4130 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004131 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004132 if (hwOutputDesc != 0) {
4133 // release patch between src device and output device
4134 // close Hwoutput and remove from mHwOutputs
4135 } else {
4136 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4137 }
4138 }
4139 return NO_ERROR;
4140}
4141
François Gaffiec005e562018-11-06 15:04:49 +01004142sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4143 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004144{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004145 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004146 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004147 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004148 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004149 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4150 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004151 source = sourceDesc;
4152 break;
4153 }
4154 }
4155 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004156}
4157
Eric Laurente552edb2014-03-10 17:42:56 -07004158// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004159// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004160// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004161uint32_t AudioPolicyManager::nextAudioPortGeneration()
4162{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004163 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004164}
4165
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004166// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
4167static const char *kConfigLocationList[] =
4168 {"/odm/etc", "/vendor/etc", "/system/etc"};
4169static const int kConfigLocationListSize =
4170 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
4171
4172static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4173 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004174 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004175 status_t ret;
4176
Cheney Ni00ce33d2018-11-01 06:30:37 +08004177 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
Cheney Nie5985452019-02-24 01:39:15 +08004178 if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false) &&
4179 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4180 // Both BluetoothAudio@2.0 and BluetoothA2dp@1.0 (Offlaod) are disabled, and uses
4181 // the legacy hardware module for A2DP and hearing aid.
4182 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
4183 } else if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4184 // A2DP offload supported but disabled: try to use special XML file
Cheney Ni6851adb2018-11-01 06:30:37 +08004185 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4186 }
Cheney Nie5985452019-02-24 01:39:15 +08004187 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false)) {
4188 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
Petri Gyntherf497f292018-04-17 18:46:10 -07004189 }
4190 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4191
4192 for (const char* fileName : fileNames) {
4193 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004194 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4195 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004196 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004197 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004198 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004199 return ret;
4200 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004201 }
4202 }
4203 return ret;
4204}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004205
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004206AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4207 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004208 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004209 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004210 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004211 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004212 mA2dpSuspended(false),
Eric Laurentf5aa58d2019-02-22 18:20:11 -08004213 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004214 mAudioPortGeneration(1),
4215 mBeaconMuteRefCount(0),
4216 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004217 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004218 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004219 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004220 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004221{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004222}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004223
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004224AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4225 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4226{
4227 loadConfig();
4228 initialize();
4229}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004230
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004231// This check is to catch any legacy platform updating to Q without having
4232// switched to XML since its deprecation on O.
4233// TODO: after Q release, remove this check and flag as XML is now the only
4234// option and all legacy platform should have transitioned to XML.
4235#ifndef USE_XML_AUDIO_POLICY_CONF
4236#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004237#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004238
4239void AudioPolicyManager::loadConfig() {
4240 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004241 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004242 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004243 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004244}
4245
4246status_t AudioPolicyManager::initialize() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004247 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004248 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4249 if (!engineInstance) {
4250 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004251 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004252 }
4253 // Retrieve the Policy Manager Interface
4254 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4255 if (mEngine == NULL) {
4256 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004257 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004258 }
4259 mEngine->setObserver(this);
4260 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004261 if (status != NO_ERROR) {
4262 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4263 return status;
4264 }
François Gaffie2110e042015-03-24 08:41:51 +01004265
Eric Laurent3a4311c2014-03-17 12:00:47 -07004266 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004267 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004268 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004269 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004270 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4271 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004272 continue;
4273 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004274 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004275 // open all output streams needed to access attached devices
4276 // except for direct output streams that are only opened when they are actually
4277 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004278 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004279 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004280 if (!outProfile->canOpenNewIo()) {
4281 ALOGE("Invalid Output profile max open count %u for profile %s",
4282 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4283 continue;
4284 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004285 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004286 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004287 continue;
4288 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004289 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004290 mTtsOutputAvailable = true;
4291 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004292
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004293 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004294 continue;
4295 }
François Gaffie11d30102018-11-02 16:09:09 +01004296 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4297 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4298 sp<DeviceDescriptor> supportedDevice = 0;
4299 if (supportedDevices.contains(mDefaultOutputDevice)) {
4300 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004301 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004302 // choose first device present in profile's SupportedDevices also part of
4303 // mAvailableOutputDevices.
4304 if (availProfileDevices.isEmpty()) {
4305 continue;
4306 }
4307 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004308 }
François Gaffie11d30102018-11-02 16:09:09 +01004309 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004310 continue;
4311 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004312 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4313 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004314 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004315 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4316 AUDIO_STREAM_DEFAULT,
4317 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004318 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004319 ALOGW("Cannot open output stream for devices %s on hw module %s",
4320 supportedDevice->toString().c_str(), hwModule->getName());
4321 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004322 }
François Gaffie11d30102018-11-02 16:09:09 +01004323 for (const auto &device : availProfileDevices) {
4324 // give a valid ID to an attached device once confirmed it is reachable
4325 if (!device->isAttached()) {
4326 device->attach(hwModule);
4327 }
4328 }
4329 if (mPrimaryOutput == 0 &&
4330 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4331 mPrimaryOutput = outputDesc;
4332 }
4333 addOutput(output, outputDesc);
4334 setOutputDevices(outputDesc,
4335 DeviceVector(supportedDevice),
4336 true,
4337 0,
4338 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004339 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004340 // open input streams needed to access attached devices to validate
4341 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004342 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004343 if (!inProfile->canOpenNewIo()) {
4344 ALOGE("Invalid Input profile max open count %u for profile %s",
4345 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4346 continue;
4347 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004348 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004349 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004350 continue;
4351 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004352 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004353 // available input devices
4354 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4355 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4356 if (availProfileDevices.isEmpty()) {
4357 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004358 continue;
4359 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004360 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004361 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004362
Eric Laurentd78f1532014-09-16 16:38:20 -07004363 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004364 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004365 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004366 AUDIO_SOURCE_MIC,
4367 AUDIO_INPUT_FLAG_NONE,
4368 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004369 if (status != NO_ERROR) {
4370 ALOGW("Cannot open input stream for device %s on hw module %s",
4371 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004372 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004373 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004374 }
François Gaffie11d30102018-11-02 16:09:09 +01004375 for (const auto &device : availProfileDevices) {
4376 // give a valid ID to an attached device once confirmed it is reachable
4377 if (!device->isAttached()) {
4378 device->attach(hwModule);
4379 device->importAudioPort(inProfile, true);
4380 }
4381 }
4382 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004383 }
4384 }
4385 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004386 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004387 for (size_t i = 0; i < devices.size();) {
4388 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004389 if (!device->isAttached()) {
4390 ALOGW("device %s is unreachable", device->toString().c_str());
4391 devices.remove(device);
4392 continue;
4393 }
4394 // Device is now validated and can be appended to the available devices of the engine
Eric Laurent736a1022019-03-27 18:28:46 -07004395 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004396 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004397 }
François Gaffie11d30102018-11-02 16:09:09 +01004398 };
4399 checkAndSetAvailable(mAvailableOutputDevices);
4400 checkAndSetAvailable(mAvailableInputDevices);
4401
Eric Laurent3a4311c2014-03-17 12:00:47 -07004402 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004403 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4404 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4405 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004406 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004407 }
jiabin9ff780e2018-03-19 18:19:52 -07004408 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004409 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004410 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004411 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004412 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004413 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004414 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004415 }
4416 }
4417 }
Eric Laurente552edb2014-03-10 17:42:56 -07004418
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004419 if (mPrimaryOutput == 0) {
4420 ALOGE("Failed to open primary output");
4421 status = NO_INIT;
4422 }
Eric Laurente552edb2014-03-10 17:42:56 -07004423
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004424 // Silence ALOGV statements
4425 property_set("log.tag." LOG_TAG, "D");
4426
Eric Laurente552edb2014-03-10 17:42:56 -07004427 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004428 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004429}
4430
Eric Laurente0720872014-03-11 09:30:41 -07004431AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004432{
Eric Laurente552edb2014-03-10 17:42:56 -07004433 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004434 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004435 }
4436 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004437 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004438 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004439 mAvailableOutputDevices.clear();
4440 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004441 mOutputs.clear();
4442 mInputs.clear();
4443 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004444 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004445 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004446}
4447
Eric Laurente0720872014-03-11 09:30:41 -07004448status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004449{
Eric Laurent87ffa392015-05-22 10:32:38 -07004450 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004451}
4452
Eric Laurente552edb2014-03-10 17:42:56 -07004453// ---
4454
Eric Laurent98e38192018-02-15 18:31:53 -08004455void AudioPolicyManager::addOutput(audio_io_handle_t output,
4456 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004457{
Eric Laurent1c333e22014-05-20 10:48:17 -07004458 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004459 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004460 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004461 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004462 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004463}
4464
François Gaffie53615e22015-03-19 09:24:12 +01004465void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4466{
4467 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004468 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004469}
4470
Eric Laurent98e38192018-02-15 18:31:53 -08004471void AudioPolicyManager::addInput(audio_io_handle_t input,
4472 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004473{
Eric Laurent1c333e22014-05-20 10:48:17 -07004474 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004475 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004476}
Eric Laurente552edb2014-03-10 17:42:56 -07004477
François Gaffie11d30102018-11-02 16:09:09 +01004478status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004479 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004480 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004481{
François Gaffie11d30102018-11-02 16:09:09 +01004482 audio_devices_t deviceType = device->type();
4483 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004484 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004485
François Gaffie11d30102018-11-02 16:09:09 +01004486 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004487 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004488 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004489 }
Eric Laurente552edb2014-03-10 17:42:56 -07004490
Eric Laurent3b73df72014-03-11 09:06:29 -07004491 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004492 // first list already open outputs that can be routed to this device
4493 for (size_t i = 0; i < mOutputs.size(); i++) {
4494 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004495 if (!desc->isDuplicated() && desc->supportsDevice(device)
4496 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004497 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4498 mOutputs.keyAt(i), device->toString().c_str());
4499 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004500 }
4501 }
4502 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004503 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004504 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004505 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4506 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004507 if (profile->supportsDevice(device)) {
4508 profiles.add(profile);
4509 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4510 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004511 }
4512 }
4513 }
4514
Eric Laurent7b279bb2015-12-14 10:18:23 -08004515 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004516
Eric Laurente552edb2014-03-10 17:42:56 -07004517 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004518 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004519 return BAD_VALUE;
4520 }
4521
4522 // open outputs for matching profiles if needed. Direct outputs are also opened to
4523 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4524 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004525 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004526
4527 // nothing to do if one output is already opened for this profile
4528 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004529 for (j = 0; j < outputs.size(); j++) {
4530 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004531 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004532 // matching profile: save the sample rates, format and channel masks supported
4533 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004534 if (audio_device_is_digital(deviceType)) {
4535 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004536 }
Eric Laurente552edb2014-03-10 17:42:56 -07004537 break;
4538 }
4539 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004540 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004541 continue;
4542 }
4543
Eric Laurent3974e3b2017-12-07 17:58:43 -08004544 if (!profile->canOpenNewIo()) {
4545 ALOGW("Max Output number %u already opened for this profile %s",
4546 profile->maxOpenCount, profile->getTagName().c_str());
4547 continue;
4548 }
4549
Eric Laurent83efe1c2017-07-09 16:51:08 -07004550 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004551 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004552 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004553 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004554 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004555 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004556
Eric Laurentfe231122017-11-17 17:48:06 -08004557 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004558 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004559 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004560 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004561 mpClientInterface->setParameters(output, String8(param));
4562 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004563 }
François Gaffie11d30102018-11-02 16:09:09 +01004564 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004565 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004566 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004567 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004568 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004569 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004570 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004571 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004572 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4573 profile->pickAudioProfile(
4574 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004575 config.offload_info.sample_rate = config.sample_rate;
4576 config.offload_info.channel_mask = config.channel_mask;
4577 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004578
François Gaffie11d30102018-11-02 16:09:09 +01004579 status_t status = desc->open(&config, DeviceVector(device),
4580 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004581 AUDIO_OUTPUT_FLAG_NONE, &output);
4582 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004583 output = AUDIO_IO_HANDLE_NONE;
4584 }
Eric Laurentd4692962014-05-05 18:13:44 -07004585 }
4586
Eric Laurentcf2c0212014-07-25 16:20:43 -07004587 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004588 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004589 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004590 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004591 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4592 policyMix->setOutput(desc);
Mikhail Naganovbfac5832019-03-05 16:55:28 -08004593 desc->mPolicyMix = policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004594 } else {
4595 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004596 address.string());
4597 }
François Gaffie036e1e92015-03-19 10:16:24 +01004598
Eric Laurent87ffa392015-05-22 10:32:38 -07004599 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4600 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004601 // no duplicated output for direct outputs and
4602 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004603 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004604
Eric Laurentd4692962014-05-05 18:13:44 -07004605 //TODO: configure audio effect output stage here
4606
4607 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004608 sp<SwAudioOutputDescriptor> dupOutputDesc =
4609 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4610 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4611 &duplicatedOutput);
4612 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004613 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004614 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004615 } else {
4616 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004617 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004618 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004619 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004620 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004621 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004622 }
Eric Laurente552edb2014-03-10 17:42:56 -07004623 }
4624 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004625 } else {
4626 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004627 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004628 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004629 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004630 profiles.removeAt(profile_index);
4631 profile_index--;
4632 } else {
4633 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004634 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004635 if (audio_device_is_digital(deviceType)) {
4636 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004637 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004638
François Gaffie11d30102018-11-02 16:09:09 +01004639 if (device_distinguishes_on_address(deviceType)) {
4640 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4641 device->toString().c_str());
4642 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4643 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004644 }
Eric Laurente552edb2014-03-10 17:42:56 -07004645 ALOGV("checkOutputsForDevice(): adding output %d", output);
4646 }
4647 }
4648
4649 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004650 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004651 return BAD_VALUE;
4652 }
Eric Laurentd4692962014-05-05 18:13:44 -07004653 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004654 // check if one opened output is not needed any more after disconnecting one device
4655 for (size_t i = 0; i < mOutputs.size(); i++) {
4656 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004657 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004658 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004659 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4660 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004661 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004662 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004663 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4664 mOutputs.keyAt(i));
4665 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004666 }
Eric Laurente552edb2014-03-10 17:42:56 -07004667 }
4668 }
Eric Laurentd4692962014-05-05 18:13:44 -07004669 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004670 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004671 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4672 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004673 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004674 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004675 "clearing direct output profile %zu on module %s",
4676 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004677 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004678 }
4679 }
4680 }
4681 }
4682 return NO_ERROR;
4683}
4684
François Gaffie11d30102018-11-02 16:09:09 +01004685status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004686 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004687 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004688{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004689 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004690
François Gaffie11d30102018-11-02 16:09:09 +01004691 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004692 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004693 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004694 }
4695
Eric Laurentd4692962014-05-05 18:13:44 -07004696 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4697 // first list already open inputs that can be routed to this device
4698 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4699 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004700 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004701 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4702 inputs.add(mInputs.keyAt(input_index));
4703 }
4704 }
4705
4706 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004707 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004708 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004709 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004710 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004711 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004712 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004713
François Gaffie11d30102018-11-02 16:09:09 +01004714 if (profile->supportsDevice(device)) {
4715 profiles.add(profile);
4716 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4717 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004718 }
4719 }
4720 }
4721
4722 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004723 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004724 return BAD_VALUE;
4725 }
4726
4727 // open inputs for matching profiles if needed. Direct inputs are also opened to
4728 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4729 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4730
Eric Laurent1c333e22014-05-20 10:48:17 -07004731 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004732
Eric Laurentd4692962014-05-05 18:13:44 -07004733 // nothing to do if one input is already opened for this profile
4734 size_t input_index;
4735 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4736 desc = mInputs.valueAt(input_index);
4737 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004738 if (audio_device_is_digital(device->type())) {
4739 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004740 }
Eric Laurentd4692962014-05-05 18:13:44 -07004741 break;
4742 }
4743 }
4744 if (input_index != mInputs.size()) {
4745 continue;
4746 }
4747
Eric Laurent3974e3b2017-12-07 17:58:43 -08004748 if (!profile->canOpenNewIo()) {
4749 ALOGW("Max Input number %u already opened for this profile %s",
4750 profile->maxOpenCount, profile->getTagName().c_str());
4751 continue;
4752 }
4753
Eric Laurentfe231122017-11-17 17:48:06 -08004754 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004755 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004756 status_t status = desc->open(nullptr,
4757 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004758 AUDIO_SOURCE_MIC,
4759 AUDIO_INPUT_FLAG_NONE,
4760 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004761
Eric Laurentcf2c0212014-07-25 16:20:43 -07004762 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004763 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004764 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004765 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004766 mpClientInterface->setParameters(input, String8(param));
4767 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004768 }
François Gaffie11d30102018-11-02 16:09:09 +01004769 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004770 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004771 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004772 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004773 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004774 }
4775
4776 if (input != 0) {
4777 addInput(input, desc);
4778 }
4779 } // endif input != 0
4780
Eric Laurentcf2c0212014-07-25 16:20:43 -07004781 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004782 ALOGW("%s could not open input for device %s", __func__,
4783 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004784 profiles.removeAt(profile_index);
4785 profile_index--;
4786 } else {
4787 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004788 if (audio_device_is_digital(device->type())) {
4789 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004790 }
Eric Laurentd4692962014-05-05 18:13:44 -07004791 ALOGV("checkInputsForDevice(): adding input %d", input);
4792 }
4793 } // end scan profiles
4794
4795 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004796 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004797 return BAD_VALUE;
4798 }
4799 } else {
4800 // Disconnect
4801 // check if one opened input is not needed any more after disconnecting one device
4802 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4803 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004804 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004805 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4806 mInputs.keyAt(input_index));
4807 inputs.add(mInputs.keyAt(input_index));
4808 }
4809 }
4810 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004811 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004812 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004813 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004814 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004815 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004816 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004817 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4818 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004819 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004820 }
4821 }
4822 }
4823 } // end disconnect
4824
4825 return NO_ERROR;
4826}
4827
4828
Eric Laurente0720872014-03-11 09:30:41 -07004829void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004830{
4831 ALOGV("closeOutput(%d)", output);
4832
François Gaffie1c878552018-11-22 16:53:21 +01004833 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
4834 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004835 ALOGW("closeOutput() unknown output %d", output);
4836 return;
4837 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07004838 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01004839 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08004840
Eric Laurente552edb2014-03-10 17:42:56 -07004841 // look for duplicated outputs connected to the output being removed.
4842 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01004843 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
4844 if (dupOutput->isDuplicated() &&
4845 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
4846 sp<SwAudioOutputDescriptor> remainingOutput =
4847 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07004848 // As all active tracks on duplicated output will be deleted,
4849 // and as they were also referenced on the other output, the reference
4850 // count for their stream type must be adjusted accordingly on
4851 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01004852 const bool wasActive = remainingOutput->isActive();
4853 // Note: no-op on the closing output where all clients has already been set inactive
4854 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08004855 // stop() will be a no op if the output is still active but is needed in case all
4856 // active streams refcounts where cleared above
4857 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01004858 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004859 }
Eric Laurente552edb2014-03-10 17:42:56 -07004860 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4861 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4862
4863 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004864 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004865 }
4866 }
4867
Eric Laurent05b90f82014-08-27 15:32:29 -07004868 nextAudioPortGeneration();
4869
François Gaffie1c878552018-11-22 16:53:21 +01004870 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004871 if (index >= 0) {
4872 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004873 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004874 mAudioPatches.removeItemsAt(index);
4875 mpClientInterface->onAudioPatchListUpdate();
4876 }
4877
Mikhail Naganov32ebca32019-03-22 15:42:52 -07004878 if (closingOutputWasActive) {
4879 closingOutput->stop();
4880 }
François Gaffie1c878552018-11-22 16:53:21 +01004881 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004882
François Gaffie53615e22015-03-19 09:24:12 +01004883 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004884 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004885
4886 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4887 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004888 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004889 bool directOutputOpen = false;
4890 for (size_t i = 0; i < mOutputs.size(); i++) {
4891 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4892 directOutputOpen = true;
4893 break;
4894 }
4895 }
4896 if (!directOutputOpen) {
4897 ALOGV("no direct outputs open, reset MSD patch");
4898 setMsdPatch();
4899 }
4900 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004901}
4902
4903void AudioPolicyManager::closeInput(audio_io_handle_t input)
4904{
4905 ALOGV("closeInput(%d)", input);
4906
4907 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4908 if (inputDesc == NULL) {
4909 ALOGW("closeInput() unknown input %d", input);
4910 return;
4911 }
4912
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004914
François Gaffie11d30102018-11-02 16:09:09 +01004915 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004916 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004917 if (index >= 0) {
4918 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004919 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004920 mAudioPatches.removeItemsAt(index);
4921 mpClientInterface->onAudioPatchListUpdate();
4922 }
4923
Eric Laurentfe231122017-11-17 17:48:06 -08004924 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004925 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004926
François Gaffie11d30102018-11-02 16:09:09 +01004927 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4928 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004929 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4930 SoundTrigger::setCaptureState(false);
4931 }
Eric Laurente552edb2014-03-10 17:42:56 -07004932}
4933
François Gaffie11d30102018-11-02 16:09:09 +01004934SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4935 const DeviceVector &devices,
4936 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004937{
4938 SortedVector<audio_io_handle_t> outputs;
4939
François Gaffie11d30102018-11-02 16:09:09 +01004940 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004941 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004942 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004943 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004944 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004945 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4946 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004947 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004948 outputs.add(openOutputs.keyAt(i));
4949 }
4950 }
4951 return outputs;
4952}
4953
Mikhail Naganov37977152018-07-11 15:54:44 -07004954void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4955{
4956 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4957 // output is suspended before any tracks are moved to it
4958 checkA2dpSuspend();
4959 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08004960 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004961 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004962 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004963 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004964 setMsdPatch();
4965 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004966}
4967
François Gaffiec005e562018-11-06 15:04:49 +01004968bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
4969 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07004970{
François Gaffiec005e562018-11-06 15:04:49 +01004971 return mEngine->getProductStrategyForAttributes(lAttr) ==
4972 mEngine->getProductStrategyForAttributes(rAttr);
4973}
4974
4975void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
4976{
4977 auto psId = mEngine->getProductStrategyForAttributes(attr);
4978
4979 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
4980 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01004981 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4982 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004983
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004984 // also take into account external policy-related changes: add all outputs which are
4985 // associated with policies in the "before" and "after" output vectors
François Gaffiec005e562018-11-06 15:04:49 +01004986 ALOGVV("%s(): policy related outputs", __func__);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004987 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004988 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004989 if (desc != 0 && desc->mPolicyMix != NULL) {
4990 srcOutputs.add(desc->mIoHandle);
4991 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4992 }
4993 }
4994 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004995 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004996 if (desc != 0 && desc->mPolicyMix != NULL) {
4997 dstOutputs.add(desc->mIoHandle);
4998 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4999 }
5000 }
5001
François Gaffiec005e562018-11-06 15:04:49 +01005002 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005003 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5004 // audio from invalidated tracks will be rendered when unmuting
5005 uint32_t maxLatency = 0;
5006 for (audio_io_handle_t srcOut : srcOutputs) {
5007 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
5008 if (desc != 0 && maxLatency < desc->latency()) {
5009 maxLatency = desc->latency();
5010 }
5011 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005012 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005013 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005014 std::to_string(srcOutputs[0]).c_str(),
5015 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005016 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005017 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005018 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
François Gaffiec005e562018-11-06 15:04:49 +01005019 if (desc != 0 && desc->isStrategyActive(psId)) {
5020 setStrategyMute(psId, true, desc);
5021 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005022 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005023 }
François Gaffiec005e562018-11-06 15:04:49 +01005024 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07005025 if (source != 0){
5026 connectAudioSource(source);
5027 }
Eric Laurente552edb2014-03-10 17:42:56 -07005028 }
5029
François Gaffiec005e562018-11-06 15:04:49 +01005030 // Move effects associated to this stream from previous output to new output
5031 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005032 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005033 }
François Gaffiec005e562018-11-06 15:04:49 +01005034 // Move tracks associated to this stream (and linked) from previous output to new output
5035 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5036 mpClientInterface->invalidateStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005037 }
5038 }
5039}
5040
Eric Laurente0720872014-03-11 09:30:41 -07005041void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005042{
François Gaffiec005e562018-11-06 15:04:49 +01005043 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5044 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5045 checkOutputForAttributes(attributes);
5046 }
Eric Laurente552edb2014-03-10 17:42:56 -07005047}
5048
Kevin Rocard153f92d2018-12-18 18:33:28 -08005049void AudioPolicyManager::checkSecondaryOutputs() {
5050 std::set<audio_stream_type_t> streamsToInvalidate;
5051 for (size_t i = 0; i < mOutputs.size(); i++) {
5052 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5053 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
5054 // FIXME code duplicated from getOutputForAttrInt
5055 sp<SwAudioOutputDescriptor> desc;
5056 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5057 mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(), desc,
5058 &secondaryDescs);
5059 if (!std::equal(client->getSecondaryOutputs().begin(),
5060 client->getSecondaryOutputs().end(),
5061 secondaryDescs.begin(), secondaryDescs.end())) {
5062 streamsToInvalidate.insert(client->stream());
5063 }
5064 }
5065 }
5066 for (audio_stream_type_t stream : streamsToInvalidate) {
5067 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5068 mpClientInterface->invalidateStream(stream);
5069 }
5070}
5071
Eric Laurente0720872014-03-11 09:30:41 -07005072void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005073{
François Gaffie53615e22015-03-19 09:24:12 +01005074 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005075 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005076 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005077 return;
5078 }
5079
Eric Laurent3a4311c2014-03-17 12:00:47 -07005080 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08005081 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
5082 ~AUDIO_DEVICE_BIT_IN) != 0) ||
5083 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07005084
5085 // if suspended, restore A2DP output if:
5086 // ((SCO device is NOT connected) ||
5087 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
5088 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005089 //
Eric Laurentf732e072016-08-03 19:30:28 -07005090 // if not suspended, suspend A2DP output if:
5091 // (SCO device is connected) &&
5092 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
5093 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005094 //
5095 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005096 if (!isScoConnected ||
5097 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
5098 AUDIO_POLICY_FORCE_BT_SCO) &&
5099 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
5100 AUDIO_POLICY_FORCE_BT_SCO) &&
5101 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005102 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005103
5104 mpClientInterface->restoreOutput(a2dpOutput);
5105 mA2dpSuspended = false;
5106 }
5107 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005108 if (isScoConnected &&
5109 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
5110 AUDIO_POLICY_FORCE_BT_SCO) ||
5111 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
5112 AUDIO_POLICY_FORCE_BT_SCO) ||
5113 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005114 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005115
5116 mpClientInterface->suspendOutput(a2dpOutput);
5117 mA2dpSuspended = true;
5118 }
5119 }
5120}
5121
François Gaffie11d30102018-11-02 16:09:09 +01005122DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5123 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005124{
François Gaffie11d30102018-11-02 16:09:09 +01005125 DeviceVector devices;
5126
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005127 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005128 if (index >= 0) {
5129 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5130 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005131 ALOGV("%s device %s forced by patch %d", __func__,
5132 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5133 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005134 }
5135 }
5136
Eric Laurent97ac8712018-07-27 18:59:02 -07005137 // Honor explicit routing requests only if no client using default routing is active on this
5138 // input: a specific app can not force routing for other apps by setting a preferred device.
5139 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005140 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005141 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005142 if (device != nullptr) {
5143 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005144 }
5145
François Gaffiea807ef92018-11-05 10:44:33 +01005146 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5147 // of setForceUse / Default Bus device here
5148 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5149 if (device != nullptr) {
5150 return DeviceVector(device);
5151 }
5152
François Gaffiec005e562018-11-06 15:04:49 +01005153 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5154 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5155 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005156
François Gaffiec005e562018-11-06 15:04:49 +01005157 if ((hasVoiceStream(streams) &&
5158 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005159 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005160 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5161 outputDesc->isStrategyActive(productStrategy)) {
5162 // Retrieval of devices for voice DL is done on primary output profile, cannot
5163 // check the route (would force modifying configuration file for this profile)
5164 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5165 break;
5166 }
Eric Laurente552edb2014-03-10 17:42:56 -07005167 }
François Gaffiec005e562018-11-06 15:04:49 +01005168 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005169 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005170}
5171
François Gaffie11d30102018-11-02 16:09:09 +01005172sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5173 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005174{
François Gaffie11d30102018-11-02 16:09:09 +01005175 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005176
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005177 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005178 if (index >= 0) {
5179 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5180 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005181 ALOGV("getNewInputDevice() device %s forced by patch %d",
5182 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5183 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 }
5185 }
5186
Eric Laurent97ac8712018-07-27 18:59:02 -07005187 // Honor explicit routing requests only if no client using default routing is active on this
5188 // input: a specific app can not force routing for other apps by setting a preferred device.
5189 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005190 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5191 if (device != nullptr) {
5192 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005193 }
5194
Eric Laurentdc95a252018-04-12 12:46:56 -07005195 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005196 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005197 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5198 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5199 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005200 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005201 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005202 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005203 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005204
Eric Laurente552edb2014-03-10 17:42:56 -07005205 return device;
5206}
5207
Eric Laurent794fde22016-03-11 09:50:45 -08005208bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5209 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005210 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005211}
5212
Eric Laurente0720872014-03-11 09:30:41 -07005213audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005214 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005215 // getOutputDevicesForStream's behavior for invalid streams.
5216 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5217 // device for music stream), but we want to return the empty set.
5218 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 return AUDIO_DEVICE_NONE;
5220 }
François Gaffie11d30102018-11-02 16:09:09 +01005221 DeviceVector activeDevices;
5222 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01005223 for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
5224 curStream = (audio_stream_type_t) (curStream + 1)) {
5225 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005226 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005227 }
François Gaffiec005e562018-11-06 15:04:49 +01005228 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005229 devices.merge(curDevices);
5230 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005231 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie1c878552018-11-22 16:53:21 +01005232 if (outputDesc->isActive(streamToVolumeSource((audio_stream_type_t)curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005233 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005234 }
5235 }
Eric Laurente552edb2014-03-10 17:42:56 -07005236 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005237
Eric Laurentb0688d62018-08-14 15:49:18 -07005238 // Favor devices selected on active streams if any to report correct device in case of
5239 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005240 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005241 devices = activeDevices;
5242 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005243 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5244 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005245 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5246 if (!speakerSafeDevices.isEmpty()) {
5247 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5248 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005249 }
François Gaffie11d30102018-11-02 16:09:09 +01005250 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005251}
5252
Eric Laurente0720872014-03-11 09:30:41 -07005253void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005254 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005255 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005256 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005257 updateDevicesAndOutputs();
5258 break;
5259 default:
5260 break;
5261 }
5262}
5263
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005264uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005265
5266 // skip beacon mute management if a dedicated TTS output is available
5267 if (mTtsOutputAvailable) {
5268 return 0;
5269 }
5270
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005271 switch(event) {
5272 case STARTING_OUTPUT:
5273 mBeaconMuteRefCount++;
5274 break;
5275 case STOPPING_OUTPUT:
5276 if (mBeaconMuteRefCount > 0) {
5277 mBeaconMuteRefCount--;
5278 }
5279 break;
5280 case STARTING_BEACON:
5281 mBeaconPlayingRefCount++;
5282 break;
5283 case STOPPING_BEACON:
5284 if (mBeaconPlayingRefCount > 0) {
5285 mBeaconPlayingRefCount--;
5286 }
5287 break;
5288 }
5289
5290 if (mBeaconMuteRefCount > 0) {
5291 // any playback causes beacon to be muted
5292 return setBeaconMute(true);
5293 } else {
5294 // no other playback: unmute when beacon starts playing, mute when it stops
5295 return setBeaconMute(mBeaconPlayingRefCount == 0);
5296 }
5297}
5298
5299uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5300 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5301 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5302 // keep track of muted state to avoid repeating mute/unmute operations
5303 if (mBeaconMuted != mute) {
5304 // mute/unmute AUDIO_STREAM_TTS on all outputs
5305 ALOGV("\t muting %d", mute);
5306 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005307 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005308 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005309 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005310 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, AUDIO_DEVICE_NONE);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005311 const uint32_t latency = desc->latency() * 2;
5312 if (latency > maxLatency) {
5313 maxLatency = latency;
5314 }
5315 }
5316 mBeaconMuted = mute;
5317 return maxLatency;
5318 }
5319 return 0;
5320}
5321
Eric Laurente0720872014-03-11 09:30:41 -07005322void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005323{
François Gaffiec005e562018-11-06 15:04:49 +01005324 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005325 mPreviousOutputs = mOutputs;
5326}
5327
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005328uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005329 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005330 uint32_t delayMs)
5331{
5332 // mute/unmute strategies using an incompatible device combination
5333 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5334 // if unmuting, unmute only after the specified delay
5335 if (outputDesc->isDuplicated()) {
5336 return 0;
5337 }
5338
5339 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005340 DeviceVector devices = outputDesc->devices();
5341 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005342
François Gaffiec005e562018-11-06 15:04:49 +01005343 auto productStrategies = mEngine->getOrderedProductStrategies();
5344 for (const auto &productStrategy : productStrategies) {
5345 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5346 DeviceVector curDevices =
5347 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5348 curDevices = curDevices.filter(outputDesc->supportedDevices());
5349 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005350 bool doMute = false;
5351
François Gaffiec005e562018-11-06 15:04:49 +01005352 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005353 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005354 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5355 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005356 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005357 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005358 }
Eric Laurent99401132014-05-07 19:48:15 -07005359 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005360 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005361 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005362 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005363 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005364 continue;
5365 }
François Gaffiec005e562018-11-06 15:04:49 +01005366 ALOGVV("%s() %s (curDevice %s)", __func__,
5367 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5368 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5369 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005370 if (mute) {
5371 // FIXME: should not need to double latency if volume could be applied
5372 // immediately by the audioflinger mixer. We must account for the delay
5373 // between now and the next time the audioflinger thread for this output
5374 // will process a buffer (which corresponds to one buffer size,
5375 // usually 1/2 or 1/4 of the latency).
5376 if (muteWaitMs < desc->latency() * 2) {
5377 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005378 }
5379 }
5380 }
5381 }
5382 }
5383 }
5384
Eric Laurent99401132014-05-07 19:48:15 -07005385 // temporary mute output if device selection changes to avoid volume bursts due to
5386 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005387 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005388 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5389 // temporary mute duration is conservatively set to 4 times the reported latency
5390 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5391 if (muteWaitMs < tempMuteWaitMs) {
5392 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005393 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005394 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5395 // make sure that we do not start the temporary mute period too early in case of
5396 // delayed device change
5397 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5398 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005399 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005400 }
5401 }
5402
Eric Laurente552edb2014-03-10 17:42:56 -07005403 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5404 if (muteWaitMs > delayMs) {
5405 muteWaitMs -= delayMs;
5406 usleep(muteWaitMs * 1000);
5407 return muteWaitMs;
5408 }
5409 return 0;
5410}
5411
François Gaffie11d30102018-11-02 16:09:09 +01005412uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5413 const DeviceVector &devices,
5414 bool force,
5415 int delayMs,
5416 audio_patch_handle_t *patchHandle,
5417 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005418{
François Gaffie11d30102018-11-02 16:09:09 +01005419 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005420 uint32_t muteWaitMs;
5421
5422 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005423 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5424 nullptr /* patchHandle */, requiresMuteCheck);
5425 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5426 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005427 return muteWaitMs;
5428 }
Eric Laurente552edb2014-03-10 17:42:56 -07005429
5430 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005431 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005432 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005433
François Gaffie11d30102018-11-02 16:09:09 +01005434 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005435 // output profile or if new device is not supported AND previous device(s) is(are) still
5436 // available (otherwise reset device must be done on the output)
5437 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5438 !mAvailableOutputDevices.filter(prevDevices).empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005439 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5440 return 0;
5441 }
Eric Laurente552edb2014-03-10 17:42:56 -07005442
François Gaffie11d30102018-11-02 16:09:09 +01005443 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5444
5445 if (!filteredDevices.isEmpty()) {
5446 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005447 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005448
5449 // if the outputs are not materially active, there is no need to mute.
5450 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005451 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005452 } else {
5453 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5454 muteWaitMs = 0;
5455 }
Eric Laurente552edb2014-03-10 17:42:56 -07005456
5457 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005458 // the requested device is AUDIO_DEVICE_NONE
5459 // OR the requested device is the same as current device
5460 // AND force is not specified
5461 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005462 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005463 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005464 !force && outputDesc->getPatchHandle() != 0) {
5465 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5466 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005467 return muteWaitMs;
5468 }
5469
François Gaffie11d30102018-11-02 16:09:09 +01005470 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005471
Eric Laurente552edb2014-03-10 17:42:56 -07005472 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005473 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005474 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005475 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005476 PatchBuilder patchBuilder;
5477 patchBuilder.addSource(outputDesc);
5478 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5479 for (const auto &filteredDevice : filteredDevices) {
5480 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005481 }
5482
François Gaffie11d30102018-11-02 16:09:09 +01005483 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005484 }
Eric Laurente552edb2014-03-10 17:42:56 -07005485
5486 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005487 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005488
5489 return muteWaitMs;
5490}
5491
Eric Laurentc75307b2015-03-17 15:29:32 -07005492status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005493 int delayMs,
5494 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005495{
Eric Laurent6a94d692014-05-20 11:18:06 -07005496 ssize_t index;
5497 if (patchHandle) {
5498 index = mAudioPatches.indexOfKey(*patchHandle);
5499 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005500 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 }
5502 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005503 return INVALID_OPERATION;
5504 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005505 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5506 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005507 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005508 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005509 removeAudioPatch(patchDesc->mHandle);
5510 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005511 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005512 return status;
5513}
5514
5515status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005516 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005517 bool force,
5518 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005519{
5520 status_t status = NO_ERROR;
5521
Eric Laurent1f2f2232014-06-02 12:01:23 -07005522 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005523 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5524 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005525
François Gaffie11d30102018-11-02 16:09:09 +01005526 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005527 PatchBuilder patchBuilder;
5528 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005529 // AUDIO_SOURCE_HOTWORD is for internal use only:
5530 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005531 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5532 auto result = usecase;
5533 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5534 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5535 }
5536 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005537 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005538 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005539 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005540 }
5541 }
5542 return status;
5543}
5544
Eric Laurent6a94d692014-05-20 11:18:06 -07005545status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5546 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005547{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005548 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005549 ssize_t index;
5550 if (patchHandle) {
5551 index = mAudioPatches.indexOfKey(*patchHandle);
5552 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005553 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005554 }
5555 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005556 return INVALID_OPERATION;
5557 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005558 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5559 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005560 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005561 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005562 removeAudioPatch(patchDesc->mHandle);
5563 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005564 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005565 return status;
5566}
5567
François Gaffie11d30102018-11-02 16:09:09 +01005568sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005569 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005570 audio_format_t& format,
5571 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005572 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005573{
5574 // Choose an input profile based on the requested capture parameters: select the first available
5575 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005576 //
5577 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5578 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005579
Glenn Kasten730b9262018-03-29 15:01:26 -07005580 sp<IOProfile> firstInexact;
5581 uint32_t updatedSamplingRate = 0;
5582 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5583 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005584 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005585 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005586 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005587 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005588 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005589 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005590 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005591 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005592 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005593 &channelMask /*updatedChannelMask*/,
5594 // FIXME ugly cast
5595 (audio_output_flags_t) flags,
5596 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005597 return profile;
5598 }
François Gaffie11d30102018-11-02 16:09:09 +01005599 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005600 samplingRate,
5601 &updatedSamplingRate,
5602 format,
5603 &updatedFormat,
5604 channelMask,
5605 &updatedChannelMask,
5606 // FIXME ugly cast
5607 (audio_output_flags_t) flags,
5608 false /*exactMatchRequiredForInputFlags*/)) {
5609 firstInexact = profile;
5610 }
5611
Eric Laurente552edb2014-03-10 17:42:56 -07005612 }
5613 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005614 if (firstInexact != nullptr) {
5615 samplingRate = updatedSamplingRate;
5616 format = updatedFormat;
5617 channelMask = updatedChannelMask;
5618 return firstInexact;
5619 }
Eric Laurente552edb2014-03-10 17:42:56 -07005620 return NULL;
5621}
5622
François Gaffieaaac0fd2018-11-22 17:56:39 +01005623float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
5624 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005625 int index,
5626 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005627{
François Gaffie43c73442018-11-08 08:21:55 +01005628 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005629
5630 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5631 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5632 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5633 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01005634 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5635 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
5636 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
5637 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
5638
5639 if (volumeSource == toVolumeSource(AUDIO_STREAM_ACCESSIBILITY)
5640 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
5641 mOutputs.isActive(ringVolumeSrc, 0)) {
5642 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
5643 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, device);
5644 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005645 }
5646
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005647 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01005648 if ((volumeSource != callVolumeSrc && (isInCall() ||
5649 mOutputs.isActiveLocally(callVolumeSrc))) &&
5650 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
5651 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
5652 volumeSource == alarmVolumeSrc ||
5653 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
5654 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5655 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
5656 volumeSource == toVolumeSource(AUDIO_STREAM_ACCESSIBILITY))) {
5657 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
5658 int voiceVolumeIndex = voiceCurves.getVolumeIndex(device);
5659 const float maxVoiceVolDb =
5660 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005661 + IN_CALL_EARPIECE_HEADROOM_DB;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005662 if (volumeDb > maxVoiceVolDb) {
5663 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
5664 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
5665 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005666 }
5667 }
Eric Laurente552edb2014-03-10 17:42:56 -07005668 // if a headset is connected, apply the following rules to ring tones and notifications
5669 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005670 // - always attenuate notifications volume by 6dB
5671 // - attenuate ring tones volume by 6dB unless music is not playing and
5672 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005673 // - if music is playing, always limit the volume to current music volume,
5674 // with a minimum threshold at -36dB so that notification is always perceived.
François Gaffieaaac0fd2018-11-22 17:56:39 +01005675 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5676 AUDIO_DEVICE_OUT_WIRED_HEADSET | AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5677 AUDIO_DEVICE_OUT_USB_HEADSET | AUDIO_DEVICE_OUT_HEARING_AID)) &&
5678 ((volumeSource == alarmVolumeSrc ||
5679 volumeSource == ringVolumeSrc) ||
5680 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
5681 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
5682 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5683 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
5684 curves.canBeMuted()) {
5685
Eric Laurente552edb2014-03-10 17:42:56 -07005686 // when the phone is ringing we must consider that music could have been paused just before
5687 // by the music application and behave as if music was active if the last music track was
5688 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005689 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005690 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01005691 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
François Gaffiec005e562018-11-06 15:04:49 +01005692 audio_devices_t musicDevice =
5693 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
5694 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01005695 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
5696 float musicVolDb = computeVolume(musicCurves, musicVolumeSrc,
5697 musicCurves.getVolumeIndex(musicDevice), musicDevice);
5698 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5699 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
5700 if (volumeDb > minVolDb) {
5701 volumeDb = minVolDb;
5702 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07005703 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005704 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
François Gaffieaaac0fd2018-11-22 17:56:39 +01005705 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005706 // on A2DP, also ensure notification volume is not too low compared to media when
5707 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01005708 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01005709 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
5710 ALOGV("%s increasing volume for volume source=%d device=0x%X from %f to %f",
5711 __func__, volumeSource, device, volumeDb,
5712 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5713 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005714 }
5715 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005716 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01005717 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01005718 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005719 }
5720 }
5721
François Gaffie43c73442018-11-08 08:21:55 +01005722 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07005723}
5724
Eric Laurent3839bc02018-07-10 18:33:34 -07005725int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005726 VolumeSource fromVolumeSource,
5727 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07005728{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005729 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005730 return srcIndex;
5731 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005732 auto &srcCurves = getVolumeCurves(fromVolumeSource);
5733 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005734 float minSrc = (float)srcCurves.getVolumeIndexMin();
5735 float maxSrc = (float)srcCurves.getVolumeIndexMax();
5736 float minDst = (float)dstCurves.getVolumeIndexMin();
5737 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07005738
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005739 // preserve mute request or correct range
5740 if (srcIndex < minSrc) {
5741 if (srcIndex == 0) {
5742 return 0;
5743 }
5744 srcIndex = minSrc;
5745 } else if (srcIndex > maxSrc) {
5746 srcIndex = maxSrc;
5747 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005748 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5749}
5750
François Gaffieaaac0fd2018-11-22 17:56:39 +01005751status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
5752 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005753 int index,
5754 const sp<AudioOutputDescriptor>& outputDesc,
5755 audio_devices_t device,
5756 int delayMs,
5757 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005758{
François Gaffieaaac0fd2018-11-22 17:56:39 +01005759 // do not change actual attributes volume if the attributes is muted
5760 if (outputDesc->isMuted(volumeSource)) {
5761 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
5762 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07005763 return NO_ERROR;
5764 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005765 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5766 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
5767 bool isVoiceVolSrc = callVolSrc == volumeSource;
5768 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
5769
François Gaffie2110e042015-03-24 08:41:51 +01005770 audio_policy_forced_cfg_t forceUseForComm =
5771 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005772 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01005773 // if sco and call follow same curves, bypass forceUseForComm
5774 if ((callVolSrc != btScoVolSrc) &&
5775 ((isVoiceVolSrc && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5776 (isBtScoVolSrc && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO))) {
5777 ALOGV("%s cannot set volume group %d volume with force use = %d for comm", __func__,
5778 volumeSource, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005779 return INVALID_OPERATION;
5780 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005781 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005782 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005783 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005784
François Gaffieaaac0fd2018-11-22 17:56:39 +01005785 float volumeDb = computeVolume(curves, volumeSource, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005786 if (outputDesc->isFixedVolume(device) ||
5787 // Force VoIP volume to max for bluetooth SCO
François Gaffieaaac0fd2018-11-22 17:56:39 +01005788 ((isVoiceVolSrc || isBtScoVolSrc) && (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005789 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005790 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005791 outputDesc->setVolume(volumeDb, volumeSource, curves.getStreamTypes(), device, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07005792
François Gaffieaaac0fd2018-11-22 17:56:39 +01005793 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07005794 float voiceVolume;
5795 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
François Gaffieaaac0fd2018-11-22 17:56:39 +01005796 if (isVoiceVolSrc) {
5797 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07005798 } else {
5799 voiceVolume = 1.0;
5800 }
Eric Laurent18fba842016-03-31 14:41:26 -07005801 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005802 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5803 mLastVoiceVolume = voiceVolume;
5804 }
5805 }
Eric Laurente552edb2014-03-10 17:42:56 -07005806 return NO_ERROR;
5807}
5808
Eric Laurentc75307b2015-03-17 15:29:32 -07005809void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5810 audio_devices_t device,
5811 int delayMs,
5812 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005813{
Eric Laurentc75307b2015-03-17 15:29:32 -07005814 ALOGVV("applyStreamVolumes() for device %08x", device);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005815 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
5816 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
5817 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
5818 curves.getVolumeIndex(device), outputDesc, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005819 }
5820}
5821
François Gaffiec005e562018-11-06 15:04:49 +01005822void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
5823 bool on,
5824 const sp<AudioOutputDescriptor>& outputDesc,
5825 int delayMs,
5826 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005827{
François Gaffieaaac0fd2018-11-22 17:56:39 +01005828 std::vector<VolumeSource> sourcesToMute;
5829 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
5830 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
5831 toString(attributes).c_str(), on, outputDesc->getId());
5832 VolumeSource source = toVolumeSource(attributes);
5833 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
5834 sourcesToMute.push_back(source);
5835 }
Eric Laurente552edb2014-03-10 17:42:56 -07005836 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005837 for (auto source : sourcesToMute) {
5838 setVolumeSourceMute(source, on, outputDesc, delayMs, device);
5839 }
5840
Eric Laurente552edb2014-03-10 17:42:56 -07005841}
5842
François Gaffieaaac0fd2018-11-22 17:56:39 +01005843void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
5844 bool on,
5845 const sp<AudioOutputDescriptor>& outputDesc,
5846 int delayMs,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005847 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005848{
Eric Laurente552edb2014-03-10 17:42:56 -07005849 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005850 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005851 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005852 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005853 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01005854 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005855 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01005856 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5857 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
5858 AUDIO_POLICY_FORCE_NONE))) {
5859 checkAndSetVolume(curves, volumeSource, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005860 }
5861 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005862 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
5863 // ignored
5864 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005865 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01005866 if (!outputDesc->isMuted(volumeSource)) {
5867 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07005868 return;
5869 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005870 if (outputDesc->decMuteCount(volumeSource) == 0) {
5871 checkAndSetVolume(curves, volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005872 curves.getVolumeIndex(device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005873 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005874 device,
5875 delayMs);
5876 }
5877 }
5878}
5879
François Gaffie53615e22015-03-19 09:24:12 +01005880bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5881{
François Gaffiec005e562018-11-06 15:04:49 +01005882 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08005883 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5884 return true;
5885 }
5886
5887 // has known usage?
5888 switch (paa->usage) {
5889 case AUDIO_USAGE_UNKNOWN:
5890 case AUDIO_USAGE_MEDIA:
5891 case AUDIO_USAGE_VOICE_COMMUNICATION:
5892 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5893 case AUDIO_USAGE_ALARM:
5894 case AUDIO_USAGE_NOTIFICATION:
5895 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5896 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5897 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5898 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5899 case AUDIO_USAGE_NOTIFICATION_EVENT:
5900 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5901 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5902 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5903 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005904 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005905 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005906 break;
5907 default:
5908 return false;
5909 }
5910 return true;
5911}
5912
François Gaffie2110e042015-03-24 08:41:51 +01005913audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5914{
5915 return mEngine->getForceUse(usage);
5916}
5917
5918bool AudioPolicyManager::isInCall()
5919{
5920 return isStateInCall(mEngine->getPhoneState());
5921}
5922
5923bool AudioPolicyManager::isStateInCall(int state)
5924{
5925 return is_state_in_call(state);
5926}
5927
Eric Laurentd60560a2015-04-10 11:31:20 -07005928void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5929{
5930 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005931 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5932 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5933 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5934 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005935 }
5936 }
5937
5938 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5939 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5940 bool release = false;
5941 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5942 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5943 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5944 source->ext.device.type == deviceDesc->type()) {
5945 release = true;
5946 }
5947 }
5948 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5949 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5950 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5951 sink->ext.device.type == deviceDesc->type()) {
5952 release = true;
5953 }
5954 }
5955 if (release) {
5956 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5957 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5958 }
5959 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005960
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005961 mInputs.clearSessionRoutesForDevice(deviceDesc);
5962
Francois Gaffie716e1432019-01-14 16:58:59 +01005963 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005964}
5965
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005966void AudioPolicyManager::modifySurroundFormats(
5967 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005968 std::unordered_set<audio_format_t> enforcedSurround(
5969 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005970 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5971 for (const auto& pair : mConfig.getSurroundFormats()) {
5972 allSurround.insert(pair.first);
5973 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5974 }
Phil Burk09bc4612016-02-24 15:58:15 -08005975
5976 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5977 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005978 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005979 // This is the resulting set of formats depending on the surround mode:
5980 // 'all surround' = allSurround
5981 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5982 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5983 // 'manual surround' = mManualSurroundFormats
5984 // AUTO: formats v 'enforced surround'
5985 // ALWAYS: formats v 'all surround' v 'enforced surround'
5986 // NEVER: formats ^ 'non-surround'
5987 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005988
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005989 std::unordered_set<audio_format_t> formatSet;
5990 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5991 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005992 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005993 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005994 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005995 formatSet.insert(*formatIter);
5996 }
5997 }
5998 } else {
5999 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6000 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006001 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006002
jiabin81772902018-04-02 17:52:27 -07006003 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006004 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006005 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6006 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6007 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006008 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006009 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6010 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6011 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006012 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006013 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006014 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006015 for (const auto& format : formatSet) {
6016 formatsPtr->push(format);
6017 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006018}
6019
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006020void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006021 ChannelsVector &channelMasks = *channelMasksPtr;
6022 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6023 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6024
6025 // If NEVER, then remove support for channelMasks > stereo.
6026 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6027 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6028 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6029 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6030 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6031 channelMasks.removeAt(maskIndex);
6032 } else {
6033 maskIndex++;
6034 }
6035 }
jiabin81772902018-04-02 17:52:27 -07006036 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6037 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6038 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006039 bool supports5dot1 = false;
6040 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006041 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006042 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6043 supports5dot1 = true;
6044 break;
6045 }
6046 }
6047 // If not then add 5.1 support.
6048 if (!supports5dot1) {
6049 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006050 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006051 }
Phil Burk09bc4612016-02-24 15:58:15 -08006052 }
6053}
6054
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006055void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006056 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006057 AudioProfileVector &profiles)
6058{
6059 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006060 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006061
François Gaffie112b0af2015-11-19 16:13:25 +01006062 // Format MUST be checked first to update the list of AudioProfile
6063 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006064 reply = mpClientInterface->getParameters(
6065 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006066 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006067 AudioParameter repliedParameters(reply);
6068 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006069 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006070 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6071 return;
6072 }
Phil Burk09bc4612016-02-24 15:58:15 -08006073 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006074 if (device == AUDIO_DEVICE_OUT_HDMI
6075 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006076 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006077 }
Phil Burk09bc4612016-02-24 15:58:15 -08006078 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006079 }
François Gaffie112b0af2015-11-19 16:13:25 +01006080
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006081 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006082 ChannelsVector channelMasks;
6083 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006084 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006085 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006086
6087 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006088 reply = mpClientInterface->getParameters(
6089 ioHandle,
6090 requestedParameters.toString() + ";" +
6091 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006092 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006093 AudioParameter repliedParameters(reply);
6094 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006095 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006096 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006097 }
6098 }
6099 if (profiles.hasDynamicChannelsFor(format)) {
6100 reply = mpClientInterface->getParameters(ioHandle,
6101 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006102 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006103 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006104 AudioParameter repliedParameters(reply);
6105 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006106 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006107 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006108 if (device == AUDIO_DEVICE_OUT_HDMI
6109 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006110 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006111 }
François Gaffie112b0af2015-11-19 16:13:25 +01006112 }
6113 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006114 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006115 }
6116}
Eric Laurentd60560a2015-04-10 11:31:20 -07006117
Mikhail Naganovdc769682018-05-04 15:34:08 -07006118status_t AudioPolicyManager::installPatch(const char *caller,
6119 audio_patch_handle_t *patchHandle,
6120 AudioIODescriptorInterface *ioDescriptor,
6121 const struct audio_patch *patch,
6122 int delayMs)
6123{
6124 ssize_t index = mAudioPatches.indexOfKey(
6125 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6126 *patchHandle : ioDescriptor->getPatchHandle());
6127 sp<AudioPatch> patchDesc;
6128 status_t status = installPatch(
6129 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6130 if (status == NO_ERROR) {
6131 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6132 }
6133 return status;
6134}
6135
6136status_t AudioPolicyManager::installPatch(const char *caller,
6137 ssize_t index,
6138 audio_patch_handle_t *patchHandle,
6139 const struct audio_patch *patch,
6140 int delayMs,
6141 uid_t uid,
6142 sp<AudioPatch> *patchDescPtr)
6143{
6144 sp<AudioPatch> patchDesc;
6145 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6146 if (index >= 0) {
6147 patchDesc = mAudioPatches.valueAt(index);
6148 afPatchHandle = patchDesc->mAfPatchHandle;
6149 }
6150
6151 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6152 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6153 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6154 if (status == NO_ERROR) {
6155 if (index < 0) {
6156 patchDesc = new AudioPatch(patch, uid);
6157 addAudioPatch(patchDesc->mHandle, patchDesc);
6158 } else {
6159 patchDesc->mPatch = *patch;
6160 }
6161 patchDesc->mAfPatchHandle = afPatchHandle;
6162 if (patchHandle) {
6163 *patchHandle = patchDesc->mHandle;
6164 }
6165 nextAudioPortGeneration();
6166 mpClientInterface->onAudioPatchListUpdate();
6167 }
6168 if (patchDescPtr) *patchDescPtr = patchDesc;
6169 return status;
6170}
6171
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006172} // namespace android