blob: a03e20d276ad084e34586715d25ea696c11d535c [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"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080084 const char *device_name,
85 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -070086{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080087 status_t status = setDeviceConnectionStateInt(device, state, device_address,
88 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080089 nextAudioPortGeneration();
90 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080091}
92
François Gaffie11d30102018-11-02 16:09:09 +010093void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
94 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +020095{
François Gaffie11d30102018-11-02 16:09:09 +010096 AudioParameter param(device->address());
François Gaffie44481e72016-04-20 07:49:57 +020097 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070098 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +010099 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200100 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
101}
102
François Gaffie11d30102018-11-02 16:09:09 +0100103status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800104 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800105 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 const char *device_name,
107 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800109 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
110 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700111
112 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100113 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700114
François Gaffie11d30102018-11-02 16:09:09 +0100115 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800116 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100117 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
118 if (device == 0) {
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // handle output devices
François Gaffie11d30102018-11-02 16:09:09 +0100123 if (audio_is_output_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700124 SortedVector <audio_io_handle_t> outputs;
125
François Gaffie11d30102018-11-02 16:09:09 +0100126 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127
Eric Laurente552edb2014-03-10 17:42:56 -0700128 // save a copy of the opened output descriptors before any output is opened or closed
129 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
130 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 switch (state)
132 {
133 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800134 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100136 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700137 return INVALID_OPERATION;
138 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800139 ALOGV("%s() connecting device %s format %x",
140 __func__, device->toString().c_str(), encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700141
Eric Laurente552edb2014-03-10 17:42:56 -0700142 // register new device as available
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800143 index = mAvailableOutputDevices.add(device);
144 if (index >= 0) {
145 sp<HwModule> module = mHwModules.getModuleForDevice(device, encodedFormat);
146 if (module == 0) {
147 ALOGD("setDeviceConnectionState() could not find HW module for device %s",
148 device->toString().c_str());
149 mAvailableOutputDevices.remove(device);
150 return INVALID_OPERATION;
151 }
152 ALOGV("setDeviceConnectionState() module name=%s", module->getName());
153 mAvailableOutputDevices[index]->attach(module);
154 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100160 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200161
François Gaffie11d30102018-11-02 16:09:09 +0100162 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
163 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200164
Francois Gaffie716e1432019-01-14 16:58:59 +0100165 mHwModules.cleanUpForDevice(device);
166
François Gaffie11d30102018-11-02 16:09:09 +0100167 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700168 return INVALID_OPERATION;
169 }
François Gaffie2110e042015-03-24 08:41:51 +0100170 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100171 mEngine->setDeviceConnectionState(device, state);
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
François Gaffie11d30102018-11-02 16:09:09 +0100194 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100195
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800196 // Reset active device codec
197 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
198
François Gaffie2110e042015-03-24 08:41:51 +0100199 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100200 mEngine->setDeviceConnectionState(device, state);
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
Mikhail Naganov37977152018-07-11 15:54:44 -0700208 checkForDeviceAndOutputChanges([&]() {
209 // outputs must be closed after checkOutputForAllStrategies() is executed
210 if (!outputs.isEmpty()) {
211 for (audio_io_handle_t output : outputs) {
212 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100213 // close unused outputs after device disconnection or direct outputs that have
214 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700215 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
216 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
217 (desc->mDirectOpenCount == 0))) {
218 closeOutput(output);
219 }
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
222 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700223 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700224 return false;
225 });
Eric Laurente552edb2014-03-10 17:42:56 -0700226
Eric Laurent87ffa392015-05-22 10:32:38 -0700227 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100228 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
229 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 }
François Gaffie11d30102018-11-02 16:09:09 +0100231 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700232 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700233 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
234 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100235 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700236 // do not force device change on duplicated output because if device is 0, it will
237 // also force a device 0 for the two outputs it is duplicated to which may override
238 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100239 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100240 && !desc->isDuplicated()
François Gaffie11d30102018-11-02 16:09:09 +0100241 && (!device_distinguishes_on_address(deviceType)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700242 // always force when disconnecting (a non-duplicated device)
243 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100244 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700245 }
Eric Laurente552edb2014-03-10 17:42:56 -0700246 }
247
Eric Laurentd60560a2015-04-10 11:31:20 -0700248 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100249 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700250 }
251
Eric Laurent72aa32f2014-05-30 18:51:48 -0700252 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700253 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700254 } // end if is output device
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // handle input devices
François Gaffie11d30102018-11-02 16:09:09 +0100257 if (audio_is_input_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700258 SortedVector <audio_io_handle_t> inputs;
259
François Gaffie11d30102018-11-02 16:09:09 +0100260 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 switch (state)
262 {
263 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700264 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700265 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return INVALID_OPERATION;
268 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800269 sp<HwModule> module = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
270 if (module == NULL) {
271 ALOGW("setDeviceConnectionState(): could not find HW module for device %s",
272 device->toString().c_str());
273 return INVALID_OPERATION;
274 }
275
François Gaffie44481e72016-04-20 07:49:57 +0200276 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
277 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100278 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200279
François Gaffie11d30102018-11-02 16:09:09 +0100280 if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
281 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100282
283 mHwModules.cleanUpForDevice(device);
284
Eric Laurentd4692962014-05-05 18:13:44 -0700285 return INVALID_OPERATION;
286 }
287
Francois Gaffie716e1432019-01-14 16:58:59 +0100288 if (mAvailableInputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 return NO_MEMORY;
290 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800291
François Gaffie2110e042015-03-24 08:41:51 +0100292 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100293 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700294 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700295
296 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700297 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100299 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700300 return INVALID_OPERATION;
301 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700302
François Gaffie11d30102018-11-02 16:09:09 +0100303 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700304
305 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100306 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700307
François Gaffie11d30102018-11-02 16:09:09 +0100308 checkInputsForDevice(device, state, inputs);
309 mAvailableInputDevices.remove(device);
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
François Gaffie2110e042015-03-24 08:41:51 +0100311 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100312 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700313 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700314
315 default:
François Gaffie11d30102018-11-02 16:09:09 +0100316 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 return BAD_VALUE;
318 }
319
Eric Laurentd4692962014-05-05 18:13:44 -0700320 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700321 // As the input device list can impact the output device selection, update
322 // getDeviceForStrategy() cache
323 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700324
Eric Laurent87ffa392015-05-22 10:32:38 -0700325 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
327 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 }
329
Eric Laurentd60560a2015-04-10 11:31:20 -0700330 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100331 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700332 }
333
Eric Laurentb52c1522014-05-20 11:27:36 -0700334 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700335 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700336 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700337
François Gaffie11d30102018-11-02 16:09:09 +0100338 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700339 return BAD_VALUE;
340}
341
Eric Laurente0720872014-03-11 09:30:41 -0700342audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100343 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700344{
Eric Laurent634b7142016-04-20 13:48:02 -0700345 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800346 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
347 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700348 (strlen(device_address) != 0)/*matchAddress*/);
349
350 if (devDesc == 0) {
351 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
352 device, device_address);
353 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
354 }
François Gaffie53615e22015-03-19 09:24:12 +0100355
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 DeviceVector *deviceVector;
357
Eric Laurente552edb2014-03-10 17:42:56 -0700358 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700361 deviceVector = &mAvailableInputDevices;
362 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100363 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700365 }
Eric Laurent634b7142016-04-20 13:48:02 -0700366
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800367 return (deviceVector->getDevice(
368 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700369 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800370}
371
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800372status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
373 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800374 const char *device_name,
375 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376{
377 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700378 String8 reply;
379 AudioParameter param;
380 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800382 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
383 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800384
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800385 // connect/disconnect only 1 device at a time
386 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
387
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800388 // Check if the device is currently connected
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800389 DeviceVector availableDevices = getAvailableOutputDevices();
390 DeviceVector deviceList = availableDevices.getDevicesFromTypeMask(device);
391 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800392 // Nothing to do: device is not connected
393 return NO_ERROR;
394 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800395 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800396
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700397 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800398 // configure codecs.
399 // Handle two specific cases by sending a set parameter to
400 // configure A2DP codecs. No need to toggle device state.
401 // Case 1: A2DP active device switches from primary to primary
402 // module
403 // Case 2: A2DP device config changes on primary module.
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700404 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800405 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(device, encodedFormat);
406 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
407 if (availablePrimaryOutputDevices().contains(devDesc) &&
408 (module != 0 && module->getHandle() == primaryHandle)) {
409 reply = mpClientInterface->getParameters(
410 AUDIO_IO_HANDLE_NONE,
411 String8(AudioParameter::keyReconfigA2dpSupported));
412 AudioParameter repliedParameters(reply);
413 repliedParameters.getInt(
414 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
415 if (isReconfigA2dpSupported) {
416 const String8 key(AudioParameter::keyReconfigA2dp);
417 param.add(key, String8("true"));
418 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
419 devDesc->setEncodedFormat(encodedFormat);
420 return NO_ERROR;
421 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700422 }
423 }
424
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800425 // Toggle the device state: UNAVAILABLE -> AVAILABLE
426 // This will force reading again the device configuration
427 status = setDeviceConnectionState(device,
428 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800429 device_address, device_name,
430 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800431 if (status != NO_ERROR) {
432 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
433 status);
434 return status;
435 }
436
437 status = setDeviceConnectionState(device,
438 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800439 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800440 if (status != NO_ERROR) {
441 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
442 status);
443 return status;
444 }
445
446 return NO_ERROR;
447}
448
François Gaffie11d30102018-11-02 16:09:09 +0100449uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700450{
451 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700452 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700453
François Gaffie11d30102018-11-02 16:09:09 +0100454 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700455 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700456 }
François Gaffie11d30102018-11-02 16:09:09 +0100457 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
458
Francois Gaffie716e1432019-01-14 16:58:59 +0100459 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
460 auto txDevice = getDeviceAndMixForAttributes(attr);
François Gaffie11d30102018-11-02 16:09:09 +0100461 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
462 rxDevices.toString().c_str(), txDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700463
464 // release existing RX patch if any
465 if (mCallRxPatch != 0) {
466 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
467 mCallRxPatch.clear();
468 }
469 // release TX patch if any
470 if (mCallTxPatch != 0) {
471 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
472 mCallTxPatch.clear();
473 }
474
475 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
476 // via setOutputDevice() on primary output.
477 // Otherwise, create two audio patches for TX and RX path.
François Gaffie11d30102018-11-02 16:09:09 +0100478 if (availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) {
479 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480 // If the TX device is also on the primary HW module, setOutputDevice() will take care
481 // of it due to legacy implementation. If not, create a patch.
François Gaffie11d30102018-11-02 16:09:09 +0100482 if (!availablePrimaryModuleInputDevices().contains(txDevice)) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700483 createTxPatch = true;
484 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700485 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100486 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487 createTxPatch = true;
488 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700489 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800490 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
491 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700492
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800493 return muteWaitMs;
494}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700495
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800496sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100497 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700499
François Gaffie11d30102018-11-02 16:09:09 +0100500 if (device == nullptr) {
501 return nullptr;
502 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800503 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100504 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800505 addSource(mAvailableInputDevices.getDevice(
506 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800507 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100508 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800509 addSink(mAvailableOutputDevices.getDevice(
510 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 }
512
François Gaffie11d30102018-11-02 16:09:09 +0100513 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
514 const sp<DeviceDescriptor> outputDevice = isRx ?
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800515 device : mAvailableOutputDevices.getDevice(
516 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100517 SortedVector<audio_io_handle_t> outputs =
518 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
519 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800520 // request to reuse existing output stream if one is already opened to reach the target device
521 if (output != AUDIO_IO_HANDLE_NONE) {
522 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100523 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
524 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700525 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800526 }
527
528 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700529 // terminate active capture if on the same HW module as the call TX source device
530 // FIXME: would be better to refine to only inputs whose profile connects to the
531 // call TX device but this information is not in the audio patch and logic here must be
532 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800533 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100534 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700535 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700536 }
537 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700538 }
Eric Laurentdc462862016-07-19 12:29:53 -0700539
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800540 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700541 status_t status = mpClientInterface->createAudioPatch(
542 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800543 ALOGW_IF(status != NO_ERROR,
544 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
545 sp<AudioPatch> audioPatch;
546 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700547 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800548 audioPatch->mAfPatchHandle = afPatchHandle;
549 audioPatch->mUid = mUidCached;
550 }
551 return audioPatch;
552}
553
Mikhail Naganovdc769682018-05-04 15:34:08 -0700554sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100555 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700556 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800557 ALOG_ASSERT(!deviceList.isEmpty(),
558 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700559 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700560}
561
Mikhail Naganov100f0122018-11-29 11:22:16 -0800562audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
563 const DeviceVector& devices, const char *moduleId) const {
564 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
565 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
566}
567
568bool AudioPolicyManager::isDeviceOfModule(
569 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
570 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
571 if (module != 0) {
572 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
573 .indexOf(devDesc) != NAME_NOT_FOUND
574 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
575 .indexOf(devDesc) != NAME_NOT_FOUND;
576 }
577 return false;
578}
579
Eric Laurente0720872014-03-11 09:30:41 -0700580void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700581{
582 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100583 // store previous phone state for management of sonification strategy below
584 int oldState = mEngine->getPhoneState();
585
586 if (mEngine->setPhoneState(state) != NO_ERROR) {
587 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700588 return;
589 }
François Gaffie2110e042015-03-24 08:41:51 +0100590 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700591 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700592 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700593 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800594 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700595 }
596
François Gaffie2110e042015-03-24 08:41:51 +0100597 /**
598 * Switching to or from incall state or switching between telephony and VoIP lead to force
599 * routing command.
600 */
601 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
602 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700603
604 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700605 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700606
Eric Laurente552edb2014-03-10 17:42:56 -0700607 int delayMs = 0;
608 if (isStateInCall(state)) {
609 nsecs_t sysTime = systemTime();
610 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700611 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700612 // mute media and sonification strategies and delay device switch by the largest
613 // latency of any output where either strategy is active.
614 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100615 if ((isStrategyActive(desc, STRATEGY_MEDIA,
616 SONIFICATION_HEADSET_MUSIC_DELAY,
617 sysTime) ||
618 isStrategyActive(desc, STRATEGY_SONIFICATION,
619 SONIFICATION_HEADSET_MUSIC_DELAY,
620 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700621 (delayMs < (int)desc->latency()*2)) {
622 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700623 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700624 setStrategyMute(STRATEGY_MEDIA, true, desc);
625 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700626 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700627 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
628 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700629 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
630 }
631 }
632
Eric Laurent87ffa392015-05-22 10:32:38 -0700633 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100634 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700635 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100636 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700637 // force routing command to audio hardware when ending call
638 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100639 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
640 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700641 }
Eric Laurente552edb2014-03-10 17:42:56 -0700642
Eric Laurent87ffa392015-05-22 10:32:38 -0700643 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100644 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700645 } else if (oldState == AUDIO_MODE_IN_CALL) {
646 if (mCallRxPatch != 0) {
647 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
648 mCallRxPatch.clear();
649 }
650 if (mCallTxPatch != 0) {
651 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
652 mCallTxPatch.clear();
653 }
François Gaffie11d30102018-11-02 16:09:09 +0100654 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700655 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100656 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700657 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700659
660 // reevaluate routing on all outputs in case tracks have been started during the call
661 for (size_t i = 0; i < mOutputs.size(); i++) {
662 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100663 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700664 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100665 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700666 }
667 }
668
Eric Laurente552edb2014-03-10 17:42:56 -0700669 if (isStateInCall(state)) {
670 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700671 // force reevaluating accessibility routing when call starts
672 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700673 }
674
675 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700676 if (state == AUDIO_MODE_RINGTONE &&
677 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700678 mLimitRingtoneVolume = true;
679 } else {
680 mLimitRingtoneVolume = false;
681 }
682}
683
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700684audio_mode_t AudioPolicyManager::getPhoneState() {
685 return mEngine->getPhoneState();
686}
687
Eric Laurente0720872014-03-11 09:30:41 -0700688void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100689 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700690{
François Gaffie2110e042015-03-24 08:41:51 +0100691 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700692 if (config == mEngine->getForceUse(usage)) {
693 return;
694 }
Eric Laurente552edb2014-03-10 17:42:56 -0700695
François Gaffie2110e042015-03-24 08:41:51 +0100696 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
697 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
698 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700699 }
François Gaffie2110e042015-03-24 08:41:51 +0100700 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
701 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
702 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700703
704 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700705 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800706
Eric Laurentdc462862016-07-19 12:29:53 -0700707 //FIXME: workaround for truncated touch sounds
708 // to be removed when the problem is handled by system UI
709 uint32_t delayMs = 0;
710 uint32_t waitMs = 0;
711 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
712 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
713 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700714 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100715 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
716 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700717 }
Eric Laurente552edb2014-03-10 17:42:56 -0700718 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700719 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100720 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700721 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100722 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 }
François Gaffie11d30102018-11-02 16:09:09 +0100724 if (forceVolumeReeval && !newDevices.isEmpty()) {
725 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700726 }
727 }
728
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800729 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100730 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700731 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100732 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800733 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700734 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800735 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700736 }
Eric Laurente552edb2014-03-10 17:42:56 -0700737 }
Eric Laurente552edb2014-03-10 17:42:56 -0700738}
739
Eric Laurente0720872014-03-11 09:30:41 -0700740void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700741{
742 ALOGV("setSystemProperty() property %s, value %s", property, value);
743}
744
Michael Chana94fbb22018-04-24 14:31:19 +1000745// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
746// search to profiles for direct outputs.
747sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100748 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000749 uint32_t samplingRate,
750 audio_format_t format,
751 audio_channel_mask_t channelMask,
752 audio_output_flags_t flags,
753 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700754{
Michael Chana94fbb22018-04-24 14:31:19 +1000755 if (directOnly) {
756 // only retain flags that will drive the direct output profile selection
757 // if explicitly requested
758 static const uint32_t kRelevantFlags =
759 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
760 AUDIO_OUTPUT_FLAG_VOIP_RX);
761 flags =
762 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
763 }
Eric Laurent861a6282015-05-18 15:40:16 -0700764
765 sp<IOProfile> profile;
766
Mikhail Naganovd4120142017-12-06 15:49:22 -0800767 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800768 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100769 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700770 samplingRate, NULL /*updatedSamplingRate*/,
771 format, NULL /*updatedFormat*/,
772 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700773 flags)) {
774 continue;
775 }
776 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100777 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700778 continue;
779 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800780 // reject profiles if connected device does not support codec
781 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
782 continue;
783 }
Michael Chana94fbb22018-04-24 14:31:19 +1000784 if (!directOnly) return curProfile;
785 // when searching for direct outputs, if several profiles are compatible, give priority
786 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100787 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700788 continue;
789 }
790 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100791 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700792 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700793 }
Eric Laurente552edb2014-03-10 17:42:56 -0700794 }
795 }
Eric Laurent861a6282015-05-18 15:40:16 -0700796 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700797}
798
Eric Laurentf4e63452017-11-06 19:31:46 +0000799audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700800{
Eric Laurent3b73df72014-03-11 09:06:29 -0700801 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100802 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800803
804 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
805 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
806 // format, flags, etc. This may result in some discrepancy for functions that utilize
807 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
808 // and AudioSystem::getOutputSamplingRate().
809
François Gaffie11d30102018-11-02 16:09:09 +0100810 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
811 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700812
François Gaffie11d30102018-11-02 16:09:09 +0100813 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
814 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000815 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700816}
817
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700818status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
819 const audio_attributes_t *srcAttr,
820 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700821{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700822 if (srcAttr != NULL) {
823 if (!isValidAttributes(srcAttr)) {
824 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
825 __func__,
826 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
827 srcAttr->tags);
828 return BAD_VALUE;
829 }
830 *dstAttr = *srcAttr;
831 } else {
832 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
833 ALOGE("%s: invalid stream type", __func__);
834 return BAD_VALUE;
835 }
836 stream_type_to_audio_attributes(srcStream, dstAttr);
837 }
838 return NO_ERROR;
839}
840
841status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
842 audio_io_handle_t *output,
843 audio_session_t session,
844 const audio_attributes_t *attr,
845 audio_stream_type_t *stream,
846 uid_t uid,
847 const audio_config_t *config,
848 audio_output_flags_t *flags,
849 audio_port_handle_t *selectedDeviceId)
850{
François Gaffie11d30102018-11-02 16:09:09 +0100851 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700852 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100853 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Francois Gaffie716e1432019-01-14 16:58:59 +0100854 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100855 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700856
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700857 status_t status = getAudioAttributes(resultAttr, attr, *stream);
858 if (status != NO_ERROR) {
859 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700860 }
861
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700862 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700863 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700864 __func__,
865 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Francois Gaffie716e1432019-01-14 16:58:59 +0100866 session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700867
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700868 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700869
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700870 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700871
Scott Randolph7b1fd232018-06-18 15:33:03 -0700872 // First check for explicit routing (eg. setPreferredDevice)
Francois Gaffie716e1432019-01-14 16:58:59 +0100873 sp<DeviceDescriptor> requestedDevice = mAvailableOutputDevices.getDeviceFromId(requestedPortId);
874 if (requestedDevice != nullptr) {
875 deviceType = requestedDevice->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700876 } else {
877 // If no explict route, is there a matching dynamic policy that applies?
878 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700879 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700880 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
881 if (!audio_has_proportional_frames(config->format)) {
882 return BAD_VALUE;
883 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700884 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700885 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700886 AudioMix *mix = desc->mPolicyMix;
887 sp<DeviceDescriptor> deviceDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800888 mAvailableOutputDevices.getDevice(
889 mix->mDeviceType, mix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -0700890 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700891 ALOGV("%s returns output %d", __func__, *output);
892 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700893 }
894
895 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700896 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
897 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700898 return BAD_VALUE;
899 }
François Gaffie11d30102018-11-02 16:09:09 +0100900 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700901 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700902
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700903 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200904 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700905 }
906
Nadav Barb2f18162018-07-18 13:01:53 +0300907 // Set incall music only if device was explicitly set, and fallback to the device which is
908 // chosen by the engine if not.
909 // FIXME: provide a more generic approach which is not device specific and move this back
910 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200911 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100912 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700913 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300914 audio_is_linear_pcm(config->format) &&
915 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100916 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300917 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
918 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700919 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100920 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300921 }
922 }
923
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700924 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800925 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +0100926 __func__,
927 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700928
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100929 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +0100930 if (!msdDevices.isEmpty()) {
931 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800932 sp<DeviceDescriptor> deviceDesc =
933 mAvailableOutputDevices.getDevice(deviceType, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100934 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
935 ALOGV("%s() Using MSD devices %s instead of device %s",
936 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
937 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100938 } else {
939 *output = AUDIO_IO_HANDLE_NONE;
940 }
941 }
François Gaffie11d30102018-11-02 16:09:09 +0100942 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100943 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +0100944 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100945 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800946 if (*output == AUDIO_IO_HANDLE_NONE) {
947 return INVALID_OPERATION;
948 }
Paul McLeanaa981192015-03-21 09:55:15 -0700949
François Gaffie11d30102018-11-02 16:09:09 +0100950 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -0700951
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700952 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
953
954 return NO_ERROR;
955}
956
957status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
958 audio_io_handle_t *output,
959 audio_session_t session,
960 audio_stream_type_t *stream,
961 uid_t uid,
962 const audio_config_t *config,
963 audio_output_flags_t *flags,
964 audio_port_handle_t *selectedDeviceId,
965 audio_port_handle_t *portId)
966{
967 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
968 if (*portId != AUDIO_PORT_HANDLE_NONE) {
969 return INVALID_OPERATION;
970 }
Francois Gaffie716e1432019-01-14 16:58:59 +0100971 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700972 audio_attributes_t resultAttr;
973 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
974 config, flags, selectedDeviceId);
975 if (status != NO_ERROR) {
976 return status;
977 }
978
Eric Laurent8fc147b2018-07-22 19:13:55 -0700979 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
980 .format = config->format,
981 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700982 *portId = AudioPort::getNextUniqueId();
983
Eric Laurent8fc147b2018-07-22 19:13:55 -0700984 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700985 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +0100986 requestedPortId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700987 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -0700988 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700989 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700990 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700991
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700992 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
Francois Gaffie716e1432019-01-14 16:58:59 +0100993 __func__, *output, requestedPortId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700994
Eric Laurente83b55d2014-11-14 10:06:21 -0800995 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700996}
997
François Gaffie11d30102018-11-02 16:09:09 +0100998audio_io_handle_t AudioPolicyManager::getOutputForDevices(
999 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001000 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001001 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001002 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001003 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001004{
Andy Hungc88b0642018-04-27 15:42:35 -07001005 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001006 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001007
Eric Laurente552edb2014-03-10 17:42:56 -07001008 // open a direct output if required by specified parameters
1009 //force direct flag if offload flag is set: offloading implies a direct output stream
1010 // and all common behaviors are driven by checking only the direct flag
1011 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001012 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1013 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001014 }
Nadav Bar766fb022018-01-07 12:18:03 +02001015 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1016 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001017 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001018 // only allow deep buffering for music stream type
1019 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001020 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001021 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001022 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001023 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1024 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001025 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001026 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001027 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001028 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001029 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001030 audio_is_linear_pcm(config->format) &&
1031 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001032 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001033 AUDIO_OUTPUT_FLAG_DIRECT);
1034 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001035 }
Eric Laurente552edb2014-03-10 17:42:56 -07001036
Nadav Bar766fb022018-01-07 12:18:03 +02001037
Eric Laurentb732cf52014-09-24 19:08:21 -07001038 sp<IOProfile> profile;
1039
1040 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001041 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001042 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001043 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1044 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001045 goto non_direct_output;
1046 }
1047
Andy Hung2ddee192015-12-18 17:34:44 -08001048 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1049 // This prevents creating an offloaded track and tearing it down immediately after start
1050 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001051 // FIXME: We should check the audio session here but we do not have it in this context.
1052 // This may prevent offloading in rare situations where effects are left active by apps
1053 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001054
Nadav Bar766fb022018-01-07 12:18:03 +02001055 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001056 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001057 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001058 config->sample_rate,
1059 config->format,
1060 config->channel_mask,
1061 (audio_output_flags_t)*flags,
1062 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001063 }
1064
Eric Laurent1c333e22014-05-20 10:48:17 -07001065 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001066 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1067 for (size_t i = 0; i < mOutputs.size(); i++) {
1068 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1069 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1070 // reuse direct output if currently open by the same client
1071 // and configured with same parameters
1072 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001073 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001074 (config->channel_mask == desc->mChannelMask) &&
1075 (session == desc->mDirectClientSession)) {
1076 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001077 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001078 mOutputs.keyAt(i), session);
1079 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001080 }
1081 }
1082 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001083
1084 if (!profile->canOpenNewIo()) {
1085 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001086 }
Eric Laurent861a6282015-05-18 15:40:16 -07001087
Eric Laurent3974e3b2017-12-07 17:58:43 -08001088 sp<SwAudioOutputDescriptor> outputDesc =
1089 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001090
François Gaffie11d30102018-11-02 16:09:09 +01001091 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001092
Dean Wheatley3023b382018-08-09 07:42:40 +10001093 // MSD patch may be using the only output stream that can service this request. Release
1094 // MSD patch to prioritize this request over any active output on MSD.
1095 AudioPatchCollection msdPatches = getMsdPatches();
1096 for (size_t i = 0; i < msdPatches.size(); i++) {
1097 const auto& patch = msdPatches[i];
1098 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1099 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1100 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001101 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001102 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1103 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1104 releaseAudioPatch(patch->mHandle, mUidCached);
1105 break;
1106 }
1107 }
1108 }
1109
François Gaffie11d30102018-11-02 16:09:09 +01001110 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001111
1112 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001113 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001114 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001115 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001116 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001117 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1118 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001119 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1120 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001121 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001122 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001123 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001124 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001125 if (audio_is_linear_pcm(config->format) &&
1126 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001127 goto non_direct_output;
1128 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001129 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001130 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001131 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001132 outputDesc->mDirectClientSession = session;
1133
Eric Laurente552edb2014-03-10 17:42:56 -07001134 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001135 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001136 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001137 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001138 return output;
1139 }
1140
Eric Laurentb732cf52014-09-24 19:08:21 -07001141non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001142
1143 // A request for HW A/V sync cannot fallback to a mixed output because time
1144 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001145 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001146 return AUDIO_IO_HANDLE_NONE;
1147 }
1148
Eric Laurente552edb2014-03-10 17:42:56 -07001149 // ignoring channel mask due to downmix capability in mixer
1150
1151 // open a non direct output
1152
1153 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001154 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001155 // get which output is suitable for the specified stream. The actual
1156 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001157 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001158
Eric Laurent8838a382014-09-08 16:44:28 -07001159 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001160 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001161 output = selectOutput(outputs, *flags, config->format,
1162 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001163 }
François Gaffie11d30102018-11-02 16:09:09 +01001164 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001165 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001166 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001167
Eric Laurente552edb2014-03-10 17:42:56 -07001168 return output;
1169}
1170
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001171sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001172 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1173 mAvailableInputDevices);
1174 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1175}
1176
1177DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1178 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1179 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001180}
1181
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001182const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1183 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001184 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1185 if (msdModule != 0) {
1186 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1187 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1188 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1189 const struct audio_port_config *source = &patch->mPatch.sources[j];
1190 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1191 source->ext.device.hw_module == msdModule->getHandle()) {
1192 msdPatches.addAudioPatch(patch->mHandle, patch);
1193 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001194 }
1195 }
1196 }
1197 return msdPatches;
1198}
1199
François Gaffie11d30102018-11-02 16:09:09 +01001200status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001201 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1202{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001203 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001204 if (msdModule == nullptr) {
1205 ALOGE("%s() unable to get MSD module", __func__);
1206 return NO_INIT;
1207 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001208 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001209 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001210 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001211 return NO_INIT;
1212 }
1213 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1214 if (inputProfiles.isEmpty()) {
1215 ALOGE("%s() no input profiles for MSD module", __func__);
1216 return NO_INIT;
1217 }
1218 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1219 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001220 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001221 return NO_INIT;
1222 }
1223 AudioProfileVector msdProfiles;
1224 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1225 for (const auto &inProfile : inputProfiles) {
1226 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1227 msdProfiles.appendVector(inProfile->getAudioProfiles());
1228 }
1229 }
1230 AudioProfileVector deviceProfiles;
1231 for (const auto &outProfile : outputProfiles) {
1232 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1233 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1234 }
1235 }
1236 struct audio_config_base bestSinkConfig;
1237 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1238 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1239 &bestSinkConfig);
1240 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001241 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1242 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001243 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001244 }
1245 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1246 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1247 sinkConfig->format = bestSinkConfig.format;
1248 // For encoded streams force direct flag to prevent downstream mixing.
1249 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1250 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1251 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1252 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1253 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1254 sourceConfig->format = bestSinkConfig.format;
1255 // Copy input stream directly without any processing (e.g. resampling).
1256 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1257 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1258 if (hwAvSync) {
1259 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1260 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1261 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1262 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1263 }
1264 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1265 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1266 sinkConfig->config_mask |= config_mask;
1267 sourceConfig->config_mask |= config_mask;
1268 return NO_ERROR;
1269}
1270
François Gaffie11d30102018-11-02 16:09:09 +01001271PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001272{
1273 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001274 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001275 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1276 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1277 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1278 // For now, we just forcefully try with HwAvSync first.
1279 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1280 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1281 getBestMsdAudioProfileFor(
1282 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1283 if (res == NO_ERROR) {
1284 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1285 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1286 }
1287 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1288 " supporting PCM format conversion.", __func__);
1289 return patchBuilder;
1290}
1291
François Gaffie11d30102018-11-02 16:09:09 +01001292status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1293 sp<DeviceDescriptor> device = outputDevice;
1294 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001295 // Use media strategy for unspecified output device. This should only
1296 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1297 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001298 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1299 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1300 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001301 }
François Gaffie11d30102018-11-02 16:09:09 +01001302 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1303 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001304 const struct audio_patch* patch = patchBuilder.patch();
1305 const AudioPatchCollection msdPatches = getMsdPatches();
1306 if (!msdPatches.isEmpty()) {
1307 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1308 "The current MSD prototype only supports one output patch");
1309 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1310 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1311 return NO_ERROR;
1312 }
1313 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1314 }
1315 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1316 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1317 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1318 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001319 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1320 device->toString().c_str(), patch->sources[0].format,
1321 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001322 return status;
1323}
1324
Eric Laurente0720872014-03-11 09:30:41 -07001325audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001326 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001327 audio_format_t format,
1328 audio_channel_mask_t channelMask,
1329 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001330{
1331 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001332 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001333 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001334 // 1: the output supporting haptic playback when requesting haptic playback
1335 // 2: the output with the highest number of requested policy flags
1336 // 3: the output with the bit depth the closest to the requested one
1337 // 4: the primary output
1338 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001339
1340 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001341 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001342 }
1343 if (outputs.size() == 1) {
1344 return outputs[0];
1345 }
1346
1347 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001348 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1349 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001350 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1351 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1352 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001353 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1354 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001355
Eric Laurente78b6762018-12-19 16:29:01 -08001356 // Flags which must be present on both the request and the selected output
1357 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1358 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1359
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001360 for (audio_io_handle_t output : outputs) {
1361 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001362 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001363 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1364 continue;
1365 }
jiabin40573322018-11-08 12:08:02 -08001366 // If haptic channel is specified, use the haptic output if present.
1367 // When using haptic output, same audio format and sample rate are required.
1368 if (hapticChannelCount > 0) {
1369 // If haptic channel is specified, use the first output that
1370 // support haptic playback.
1371 if (audio_channel_count_from_out_mask(
1372 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1373 && format == outputDesc->mFormat
1374 && samplingRate == outputDesc->mSamplingRate) {
1375 return output;
1376 }
1377 } else {
1378 // When haptic channel is not specified, skip haptic output.
1379 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1380 continue;
1381 }
1382 }
Eric Laurente78b6762018-12-19 16:29:01 -08001383 if ((kMandatedFlags & flags) !=
1384 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1385 continue;
1386 }
jiabin40573322018-11-08 12:08:02 -08001387
Eric Laurent8838a382014-09-08 16:44:28 -07001388 // if a valid format is specified, skip output if not compatible
1389 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001390 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001391 continue;
1392 }
Eric Laurente6930022016-02-11 10:20:40 -08001393 if (AudioPort::isBetterFormatMatch(
1394 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001395 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001396 bestFormat = outputDesc->mFormat;
1397 }
Eric Laurent8838a382014-09-08 16:44:28 -07001398 }
1399
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001400 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001401 if (commonFlags >= maxCommonFlags) {
1402 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001403 if (format != AUDIO_FORMAT_INVALID
1404 && AudioPort::isBetterFormatMatch(
1405 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001406 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001407 bestFormatForFlags = outputDesc->mFormat;
1408 }
1409 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001410 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001411 maxCommonFlags = commonFlags;
1412 bestFormatForFlags = outputDesc->mFormat;
1413 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001414 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001415 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001416 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001417 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001418 }
1419 }
1420 }
1421
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001422 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001423 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001424 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001425 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001426 return outputForFormat;
1427 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001428 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001429 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001430 }
1431
1432 return outputs[0];
1433}
1434
Eric Laurent8fc147b2018-07-22 19:13:55 -07001435status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001436{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001437 ALOGV("%s portId %d", __FUNCTION__, portId);
1438
1439 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1440 if (outputDesc == 0) {
1441 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001442 return BAD_VALUE;
1443 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001444 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001445
Eric Laurent8fc147b2018-07-22 19:13:55 -07001446 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001447 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001448
Eric Laurent733ce942017-12-07 12:18:25 -08001449 status_t status = outputDesc->start();
1450 if (status != NO_ERROR) {
1451 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001452 }
1453
Eric Laurent97ac8712018-07-27 18:59:02 -07001454 uint32_t delayMs;
1455 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001456
1457 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001458 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001459 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001460 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001461 if (delayMs != 0) {
1462 usleep(delayMs * 1000);
1463 }
1464
1465 return status;
1466}
1467
Eric Laurent97ac8712018-07-27 18:59:02 -07001468status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1469 const sp<TrackClientDescriptor>& client,
1470 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001471{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001472 // cannot start playback of STREAM_TTS if any other output is being used
1473 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001474
1475 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001476 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001477 if (stream == AUDIO_STREAM_TTS) {
1478 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001479 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001480 return INVALID_OPERATION;
1481 } else {
1482 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1483 }
1484 } else {
1485 // some playback other than beacon starts
1486 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1487 }
1488
Eric Laurent77305a62016-07-25 16:39:22 -07001489 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001490 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001491 bool force = !outputDesc->isActive() &&
1492 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001493
François Gaffie11d30102018-11-02 16:09:09 +01001494 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001495 AudioMix *policyMix = NULL;
1496 const char *address = NULL;
1497 if (outputDesc->mPolicyMix != NULL) {
1498 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001499 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001500 address = policyMix->mDeviceAddress.string();
1501 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001502 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001503 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001504 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001505 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001506 devices.add(mAvailableOutputDevices.getDevice(newDeviceType,
1507 String8(address), AUDIO_FORMAT_DEFAULT));
Eric Laurent97ac8712018-07-27 18:59:02 -07001508 }
1509
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001510 // requiresMuteCheck is false when we can bypass mute strategy.
1511 // It covers a common case when there is no materially active audio
1512 // and muting would result in unnecessary delay and dropped audio.
1513 const uint32_t outputLatencyMs = outputDesc->latency();
1514 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1515
Eric Laurente552edb2014-03-10 17:42:56 -07001516 // increment usage count for this stream on the requested output:
1517 // NOTE that the usage count is the same for duplicated output and hardware output which is
1518 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001519 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001520
1521 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001522 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1523 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001524 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1525 }
1526 }
Eric Laurente552edb2014-03-10 17:42:56 -07001527
Eric Laurent36829f92017-04-07 19:04:42 -07001528 if (stream == AUDIO_STREAM_MUSIC) {
1529 selectOutputForMusicEffects();
1530 }
1531
François Gaffie11d30102018-11-02 16:09:09 +01001532 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001533 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001534 if (devices.isEmpty()) {
1535 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001536 }
Eric Laurent36829f92017-04-07 19:04:42 -07001537
Eric Laurente552edb2014-03-10 17:42:56 -07001538 routing_strategy strategy = getStrategy(stream);
1539 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001540 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1541 (beaconMuteLatency > 0);
1542 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001543 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001544 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001545 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001546 // An output has a shared device if
1547 // - managed by the same hw module
1548 // - supports the currently selected device
1549 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001550 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001551
Eric Laurent77305a62016-07-25 16:39:22 -07001552 // force a device change if any other output is:
1553 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001554 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001555 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001556 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001557 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001558 // change the device currently selected by the other output.
1559 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001560 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001561 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001562 force = true;
1563 }
1564 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001565 // a notification so that audio focus effect can propagate, or that a mute/unmute
1566 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001567 const uint32_t latencyMs = desc->latency();
1568 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1569
1570 if (shouldWait && isActive && (waitMs < latencyMs)) {
1571 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001572 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001573
1574 // Require mute check if another output is on a shared device
1575 // and currently active to have proper drain and avoid pops.
1576 // Note restoring AudioTracks onto this output needs to invoke
1577 // a volume ramp if there is no mute.
1578 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001579 }
1580 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001581
1582 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001583 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001584
Eric Laurente552edb2014-03-10 17:42:56 -07001585 // apply volume rules for current stream and device if necessary
1586 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001587 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001588 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001589 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001590
1591 // update the outputs if starting an output with a stream that can affect notification
1592 // routing
1593 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001594
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001595 // force reevaluating accessibility routing when ringtone or alarm starts
1596 if (strategy == STRATEGY_SONIFICATION) {
1597 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1598 }
Eric Laurentdc462862016-07-19 12:29:53 -07001599
1600 if (waitMs > muteWaitMs) {
1601 *delayMs = waitMs - muteWaitMs;
1602 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001603
1604 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1605 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1606 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1607 // change occurs after the MixerThread starts and causes a stream volume
1608 // glitch.
1609 //
1610 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001611 }
Eric Laurentdc462862016-07-19 12:29:53 -07001612
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001613 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1614 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1615 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1616 }
1617
Eric Laurent97ac8712018-07-27 18:59:02 -07001618 // Automatically enable the remote submix input when output is started on a re routing mix
1619 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001620 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001621 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1622 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1623 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1624 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001625 "remote-submix",
1626 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001627 }
1628
Eric Laurente552edb2014-03-10 17:42:56 -07001629 return NO_ERROR;
1630}
1631
Eric Laurent8fc147b2018-07-22 19:13:55 -07001632status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001633{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001634 ALOGV("%s portId %d", __FUNCTION__, portId);
1635
1636 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1637 if (outputDesc == 0) {
1638 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001639 return BAD_VALUE;
1640 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001641 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001642
Eric Laurent97ac8712018-07-27 18:59:02 -07001643 ALOGV("stopOutput() output %d, stream %d, session %d",
1644 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001645
Eric Laurent97ac8712018-07-27 18:59:02 -07001646 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001647
Eric Laurent733ce942017-12-07 12:18:25 -08001648 if (status == NO_ERROR ) {
1649 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001650 }
1651 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001652}
1653
Eric Laurent97ac8712018-07-27 18:59:02 -07001654status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1655 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001656{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001657 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001658 audio_stream_type_t stream = client->stream();
1659
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001660 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1661
Eric Laurent592dd7b2018-08-05 18:58:48 -07001662 if (outputDesc->streamActiveCount(stream) > 0) {
1663 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001664 // Automatically disable the remote submix input when output is stopped on a
1665 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001666 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001667 outputDesc->mPolicyMix != NULL &&
1668 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1669 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1670 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1671 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001672 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001673 }
1674 }
1675 bool forceDeviceUpdate = false;
1676 if (client->hasPreferredDevice(true)) {
1677 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1678 forceDeviceUpdate = true;
1679 }
1680
Eric Laurente552edb2014-03-10 17:42:56 -07001681 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001682 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001683
Eric Laurente552edb2014-03-10 17:42:56 -07001684 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001685 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001686 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001687 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001688 // delay the device switch by twice the latency because stopOutput() is executed when
1689 // the track stop() command is received and at that time the audio track buffer can
1690 // still contain data that needs to be drained. The latency only covers the audio HAL
1691 // and kernel buffers. Also the latency does not always include additional delay in the
1692 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001693 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001694
1695 // force restoring the device selection on other active outputs if it differs from the
1696 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001697 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001698 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001699 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001700 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001701 desc->isActive() &&
1702 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001703 (newDevices != desc->devices())) {
1704 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1705 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001706
François Gaffie11d30102018-11-02 16:09:09 +01001707 setOutputDevices(desc, newDevices2, force, delayMs);
1708
Eric Laurent57de36c2016-09-28 16:59:11 -07001709 // re-apply device specific volume if not done by setOutputDevice()
1710 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001711 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001712 }
Eric Laurente552edb2014-03-10 17:42:56 -07001713 }
1714 }
1715 // update the outputs if stopping one with a stream that can affect notification routing
1716 handleNotificationRoutingForStream(stream);
1717 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001718
1719 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1720 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1721 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1722 }
1723
Eric Laurent36829f92017-04-07 19:04:42 -07001724 if (stream == AUDIO_STREAM_MUSIC) {
1725 selectOutputForMusicEffects();
1726 }
Eric Laurente552edb2014-03-10 17:42:56 -07001727 return NO_ERROR;
1728 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001729 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001730 return INVALID_OPERATION;
1731 }
1732}
1733
Eric Laurent8fc147b2018-07-22 19:13:55 -07001734void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001735{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001736 ALOGV("%s portId %d", __FUNCTION__, portId);
1737
1738 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1739 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001740 // If an output descriptor is closed due to a device routing change,
1741 // then there are race conditions with releaseOutput from tracks
1742 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1743 // destroyed shortly thereafter.
1744 //
1745 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001746 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001747 return;
1748 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001749
1750 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001751
Eric Laurent8fc147b2018-07-22 19:13:55 -07001752 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1753 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001754 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001755 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001756 return;
1757 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001758 if (--outputDesc->mDirectOpenCount == 0) {
1759 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001760 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001761 }
1762 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001763 // stopOutput() needs to be successfully called before releaseOutput()
1764 // otherwise there may be inaccurate stream reference counts.
1765 // This is checked in outputDesc->removeClient below.
1766 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001767}
1768
Eric Laurentcaf7f482014-11-25 17:50:47 -08001769status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1770 audio_io_handle_t *input,
1771 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001772 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001773 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001774 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001775 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001776 input_type_t *inputType,
1777 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001778{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001779 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001780 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001781 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001782
Eric Laurentad2e7b92017-09-14 20:06:42 -07001783 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001784 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001785 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001786 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001787 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001788 sp<AudioInputDescriptor> inputDesc;
1789 sp<RecordClientDescriptor> clientDesc;
1790 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001791 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001792
1793 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1794 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1795 return INVALID_OPERATION;
1796 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001797
Francois Gaffie716e1432019-01-14 16:58:59 +01001798 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1799 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001800 }
1801
Paul McLean466dc8e2015-04-17 13:15:36 -06001802 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001803 sp<DeviceDescriptor> explicitRoutingDevice =
1804 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001805
Eric Laurentad2e7b92017-09-14 20:06:42 -07001806 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1807 // possible
1808 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1809 *input != AUDIO_IO_HANDLE_NONE) {
1810 ssize_t index = mInputs.indexOfKey(*input);
1811 if (index < 0) {
1812 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1813 status = BAD_VALUE;
1814 goto error;
1815 }
1816 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001817 RecordClientVector clients = inputDesc->getClientsForSession(session);
1818 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001819 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1820 status = BAD_VALUE;
1821 goto error;
1822 }
1823 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1824 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001825 // corresponds to a new client and is only permitted from the same UID.
1826 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001827 if (clients.size() > 1) {
1828 for (const auto& client : clients) {
1829 // The client map is ordered by key values (portId) and portIds are allocated
1830 // incrementaly. So the first client in this list is the one opened by audio flinger
1831 // when the mmap stream is created and should be ignored as it does not correspond
1832 // to an actual client
1833 if (client == *clients.cbegin()) {
1834 continue;
1835 }
1836 if (uid != client->uid() && !client->isSilenced()) {
1837 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1838 uid, client->portId(), client->uid());
1839 status = INVALID_OPERATION;
1840 goto error;
1841 }
Eric Laurent331679c2018-04-16 17:03:16 -07001842 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001843 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001844 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001845 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001846
Eric Laurent8f42ea12018-08-08 09:08:25 -07001847 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001848 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001849 }
1850
1851 *input = AUDIO_IO_HANDLE_NONE;
1852 *inputType = API_INPUT_INVALID;
1853
Francois Gaffie716e1432019-01-14 16:58:59 +01001854 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001855
Francois Gaffie716e1432019-01-14 16:58:59 +01001856 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1857 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1858 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001859 if (status != NO_ERROR) {
1860 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001861 }
1862 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001863 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001864 String8(attr->tags + strlen("addr=")),
1865 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001866 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001867 if (explicitRoutingDevice != nullptr) {
1868 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001869 } else {
Francois Gaffie716e1432019-01-14 16:58:59 +01001870 device = getDeviceAndMixForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001871 }
François Gaffie11d30102018-11-02 16:09:09 +01001872 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001873 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001874 status = BAD_VALUE;
1875 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001876 }
François Gaffie11d30102018-11-02 16:09:09 +01001877 if (policyMix != nullptr) {
1878 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1879 // there is an external policy, but this input is attached to a mix of recorders,
1880 // meaning it receives audio injected into the framework, so the recorder doesn't
1881 // know about it and is therefore considered "legacy"
1882 *inputType = API_INPUT_LEGACY;
1883 } else if (audio_is_remote_submix_device(device->type())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001884 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"),
1885 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001886 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001887 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001888 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001889 } else {
1890 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001891 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001892
Eric Laurent599c7582015-12-07 18:05:55 -08001893 }
1894
Francois Gaffie716e1432019-01-14 16:58:59 +01001895 *input = getInputForDevice(device, session, attributes.source,
Eric Laurentfe231122017-11-17 17:48:06 -08001896 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001897 policyMix);
1898 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001899 status = INVALID_OPERATION;
1900 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001901 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001902
Eric Laurent8f42ea12018-08-08 09:08:25 -07001903exit:
1904
François Gaffie11d30102018-11-02 16:09:09 +01001905 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1906 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001907
Francois Gaffie716e1432019-01-14 16:58:59 +01001908 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001909 mSoundTriggerSessions.indexOfKey(session) > 0;
1910 *portId = AudioPort::getNextUniqueId();
1911
François Gaffie11d30102018-11-02 16:09:09 +01001912 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001913 requestedDeviceId, attributes.source, flags,
1914 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001915 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001916 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001917
1918 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1919 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001920
Eric Laurent599c7582015-12-07 18:05:55 -08001921 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001922
1923error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001924 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001925}
1926
1927
François Gaffie11d30102018-11-02 16:09:09 +01001928audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08001929 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001930 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001931 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001932 audio_input_flags_t flags,
1933 AudioMix *policyMix)
1934{
1935 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1936 audio_source_t halInputSource = inputSource;
1937 bool isSoundTrigger = false;
1938
1939 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1940 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1941 if (index >= 0) {
1942 input = mSoundTriggerSessions.valueFor(session);
1943 isSoundTrigger = true;
1944 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1945 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1946 } else {
1947 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001948 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001949 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001950 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001951 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001952 }
1953
Andy Hungf129b032015-04-07 13:45:50 -07001954 // find a compatible input profile (not necessarily identical in parameters)
1955 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001956 // sampling rate and flags may be updated by getInputProfile
1957 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1958 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001959 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001960 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001961 audio_input_flags_t profileFlags = flags;
1962 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001963 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01001964 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07001965 profileFlags);
1966 if (profile != 0) {
1967 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001968 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1969 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001970 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1971 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1972 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01001973 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
1974 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
1975 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001976 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001977 }
Eric Laurente552edb2014-03-10 17:42:56 -07001978 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001979 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001980 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001981 if (samplingRate == 0) {
1982 samplingRate = profileSamplingRate;
1983 }
Eric Laurente552edb2014-03-10 17:42:56 -07001984
Eric Laurent322b4d22015-04-03 15:57:54 -07001985 if (profile->getModuleHandle() == 0) {
1986 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001987 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001988 }
1989
Eric Laurent3974e3b2017-12-07 17:58:43 -08001990 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001991 for (size_t i = 0; i < mInputs.size(); ) {
1992 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1993 if (desc->mProfile != profile) {
1994 continue;
1995 }
1996 // if sound trigger, reuse input if used by other sound trigger on same session
1997 // else
1998 // reuse input if active client app is not in IDLE state
1999 //
2000 RecordClientVector clients = desc->clientsList();
2001 bool doClose = false;
2002 for (const auto& client : clients) {
2003 if (isSoundTrigger != client->isSoundTrigger()) {
2004 continue;
2005 }
2006 if (client->isSoundTrigger()) {
2007 if (session == client->session()) {
2008 return desc->mIoHandle;
2009 }
2010 continue;
2011 }
2012 if (client->active() && client->appState() != APP_STATE_IDLE) {
2013 return desc->mIoHandle;
2014 }
2015 doClose = true;
2016 }
2017 if (doClose) {
2018 closeInput(desc->mIoHandle);
2019 } else {
2020 i++;
2021 }
2022 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002023 }
2024
Eric Laurentfe231122017-11-17 17:48:06 -08002025 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002026
Eric Laurentfe231122017-11-17 17:48:06 -08002027 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2028 lConfig.sample_rate = profileSamplingRate;
2029 lConfig.channel_mask = profileChannelMask;
2030 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002031
François Gaffie11d30102018-11-02 16:09:09 +01002032 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002033
2034 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002035 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002036 (profileSamplingRate != lConfig.sample_rate) ||
2037 !audio_formats_match(profileFormat, lConfig.format) ||
2038 (profileChannelMask != lConfig.channel_mask)) {
2039 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002040 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002041 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002042 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002043 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002044 }
Eric Laurent599c7582015-12-07 18:05:55 -08002045 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002046 }
2047
Eric Laurentc722f302014-12-10 11:21:49 -08002048 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002049
Eric Laurent599c7582015-12-07 18:05:55 -08002050 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002051 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002052
Eric Laurent599c7582015-12-07 18:05:55 -08002053 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002054}
2055
Eric Laurent4eb58f12018-12-07 16:41:02 -08002056status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002057{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002058 ALOGV("%s portId %d", __FUNCTION__, portId);
2059
2060 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2061 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002062 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002063 return BAD_VALUE;
2064 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002065 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002066 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002067 if (client->active()) {
2068 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2069 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002070 }
2071
Eric Laurent8f42ea12018-08-08 09:08:25 -07002072 audio_session_t session = client->session();
2073
Eric Laurent4eb58f12018-12-07 16:41:02 -08002074 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002075
Eric Laurent4eb58f12018-12-07 16:41:02 -08002076 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002077
Eric Laurent4eb58f12018-12-07 16:41:02 -08002078 status_t status = inputDesc->start();
2079 if (status != NO_ERROR) {
2080 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002081 }
Eric Laurente552edb2014-03-10 17:42:56 -07002082
Eric Laurent4eb58f12018-12-07 16:41:02 -08002083 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002084 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002085 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002086
Eric Laurent8f42ea12018-08-08 09:08:25 -07002087 // indicate active capture to sound trigger service if starting capture from a mic on
2088 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002089 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002090 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002091
Eric Laurent8f42ea12018-08-08 09:08:25 -07002092 if (inputDesc->activeCount() == 1) {
2093 // if input maps to a dynamic policy with an activity listener, notify of state change
2094 if ((inputDesc->mPolicyMix != NULL)
2095 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2096 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2097 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002098 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002099
François Gaffie11d30102018-11-02 16:09:09 +01002100 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2101 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002102 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2103 SoundTrigger::setCaptureState(true);
2104 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002105
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106 // automatically enable the remote submix output when input is started if not
2107 // used by a policy mix of type MIX_TYPE_RECORDERS
2108 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002109 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002110 String8 address = String8("");
2111 if (inputDesc->mPolicyMix == NULL) {
2112 address = String8("0");
2113 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2114 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002115 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002116 if (address != "") {
2117 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2118 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002119 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002120 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002121 }
Eric Laurente552edb2014-03-10 17:42:56 -07002122 }
2123
Eric Laurent8f42ea12018-08-08 09:08:25 -07002124 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002125
Eric Laurente552edb2014-03-10 17:42:56 -07002126 return NO_ERROR;
2127}
2128
Eric Laurent8fc147b2018-07-22 19:13:55 -07002129status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002130{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002131 ALOGV("%s portId %d", __FUNCTION__, portId);
2132
2133 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2134 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002135 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002136 return BAD_VALUE;
2137 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002138 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002139 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002140 if (!client->active()) {
2141 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002142 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002143 }
2144
Eric Laurent8f42ea12018-08-08 09:08:25 -07002145 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002146
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 inputDesc->stop();
2148 if (inputDesc->isActive()) {
2149 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2150 } else {
2151 // if input maps to a dynamic policy with an activity listener, notify of state change
2152 if ((inputDesc->mPolicyMix != NULL)
2153 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2154 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2155 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002156 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002157
2158 // automatically disable the remote submix output when input is stopped if not
2159 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002160 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002161 String8 address = String8("");
2162 if (inputDesc->mPolicyMix == NULL) {
2163 address = String8("0");
2164 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2165 address = inputDesc->mPolicyMix->mDeviceAddress;
2166 }
2167 if (address != "") {
2168 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2169 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002170 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002171 }
2172 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002173 resetInputDevice(input);
2174
2175 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2176 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002177 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2178 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002179 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2180 SoundTrigger::setCaptureState(false);
2181 }
2182 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002183 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002184 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002185}
2186
Eric Laurent8fc147b2018-07-22 19:13:55 -07002187void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002188{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002189 ALOGV("%s portId %d", __FUNCTION__, portId);
2190
2191 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2192 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002193 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002194 return;
2195 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002196 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002197 audio_io_handle_t input = inputDesc->mIoHandle;
2198
Eric Laurent8f42ea12018-08-08 09:08:25 -07002199 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002200
Andy Hung39efb7a2018-09-26 15:39:28 -07002201 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002202
Andy Hung39efb7a2018-09-26 15:39:28 -07002203 if (inputDesc->getClientCount() > 0) {
2204 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002205 return;
2206 }
2207
Eric Laurent05b90f82014-08-27 15:32:29 -07002208 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002209 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002211}
2212
Eric Laurent8f42ea12018-08-08 09:08:25 -07002213void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002214{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002216
2217 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002218 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002219 }
2220}
2221
Eric Laurent8f42ea12018-08-08 09:08:25 -07002222void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2223{
2224 stopInput(portId);
2225 releaseInput(portId);
2226}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002227
Eric Laurentd4692962014-05-05 18:13:44 -07002228void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002229 bool patchRemoved = false;
2230
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002231 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002232 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002233 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002234 if (patch_index >= 0) {
2235 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002236 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002237 mAudioPatches.removeItemsAt(patch_index);
2238 patchRemoved = true;
2239 }
Eric Laurentfe231122017-11-17 17:48:06 -08002240 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002241 }
2242 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002243 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002244 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002245
2246 if (patchRemoved) {
2247 mpClientInterface->onAudioPatchListUpdate();
2248 }
Eric Laurentd4692962014-05-05 18:13:44 -07002249}
2250
Eric Laurente0720872014-03-11 09:30:41 -07002251void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002252 int indexMin,
2253 int indexMax)
2254{
2255 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002256 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002257
2258 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002259 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2260 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002261 continue;
2262 }
2263 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002264 }
Eric Laurente552edb2014-03-10 17:42:56 -07002265}
2266
Eric Laurente0720872014-03-11 09:30:41 -07002267status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002268 int index,
2269 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002270{
2271
Nadav Bar7c605f62017-12-25 00:01:52 +02002272 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2273 // app that has MODIFY_PHONE_STATE permission.
2274 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2275 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002276 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002277 return BAD_VALUE;
2278 }
2279 if (!audio_is_output_device(device)) {
2280 return BAD_VALUE;
2281 }
2282
2283 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002284 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002285
Eric Laurent1fd372e2016-04-06 14:23:53 -07002286 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002287 stream, device, index);
2288
Eric Laurent28d09f02016-03-08 10:43:05 -08002289 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002290 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2291 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002292 continue;
2293 }
2294 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2295 }
Eric Laurente552edb2014-03-10 17:42:56 -07002296
Eric Laurent1fd372e2016-04-06 14:23:53 -07002297 // update volume on all outputs and streams matching the following:
2298 // - The requested stream (or a stream matching for volume control) is active on the output
2299 // - The device (or devices) selected by the strategy corresponding to this stream includes
2300 // the requested device
2301 // - For non default requested device, currently selected device on the output is either the
2302 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002303 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2304 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002305 status_t status = NO_ERROR;
2306 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002307 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002308 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002309 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002310 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002311 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002312 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002313 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002314 continue;
2315 }
Eric Laurent794fde22016-03-11 09:50:45 -08002316 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002317 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2318 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002319 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2320 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002321 continue;
2322 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002323 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002324 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002325 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002326 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002327 } else {
2328 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002329 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002330 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002331 // rescale index before applying to curStream as ranges may be different for
2332 // stream and curStream
2333 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002334 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002335 //FIXME: workaround for truncated touch sounds
2336 // delayed volume change for system stream to be removed when the problem is
2337 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002338 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002339 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002340 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002341 if (volStatus != NO_ERROR) {
2342 status = volStatus;
2343 }
2344 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002345 }
Eric Laurente552edb2014-03-10 17:42:56 -07002346 }
2347 return status;
2348}
2349
Eric Laurente0720872014-03-11 09:30:41 -07002350status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002351 int *index,
2352 audio_devices_t device)
2353{
2354 if (index == NULL) {
2355 return BAD_VALUE;
2356 }
2357 if (!audio_is_output_device(device)) {
2358 return BAD_VALUE;
2359 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002360 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002361 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002362 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002363 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2364 }
François Gaffiedfd74092015-03-19 12:10:59 +01002365 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002366
François Gaffied1ab2bd2015-12-02 18:20:06 +01002367 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002368 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2369 return NO_ERROR;
2370}
2371
Eric Laurent36829f92017-04-07 19:04:42 -07002372audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002373{
2374 // select one output among several suitable for global effects.
2375 // The priority is as follows:
2376 // 1: An offloaded output. If the effect ends up not being offloadable,
2377 // AudioFlinger will invalidate the track and the offloaded output
2378 // will be closed causing the effect to be moved to a PCM output.
2379 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002380 // 3: The primary output
2381 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002382
Eric Laurent3b73df72014-03-11 09:06:29 -07002383 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002384 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2385 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002386
Eric Laurent36829f92017-04-07 19:04:42 -07002387 if (outputs.size() == 0) {
2388 return AUDIO_IO_HANDLE_NONE;
2389 }
Eric Laurente552edb2014-03-10 17:42:56 -07002390
Eric Laurent36829f92017-04-07 19:04:42 -07002391 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2392 bool activeOnly = true;
2393
2394 while (output == AUDIO_IO_HANDLE_NONE) {
2395 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2396 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2397 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2398
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002399 for (audio_io_handle_t output : outputs) {
2400 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002401 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2402 continue;
2403 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002404 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2405 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002406 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002407 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002408 }
2409 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002410 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002411 }
2412 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002413 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002414 }
2415 }
2416 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2417 output = outputOffloaded;
2418 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2419 output = outputDeepBuffer;
2420 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2421 output = outputPrimary;
2422 } else {
2423 output = outputs[0];
2424 }
2425 activeOnly = false;
2426 }
2427
2428 if (output != mMusicEffectOutput) {
2429 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2430 mMusicEffectOutput = output;
2431 }
2432
2433 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002434 return output;
2435}
2436
Eric Laurent36829f92017-04-07 19:04:42 -07002437audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2438{
2439 return selectOutputForMusicEffects();
2440}
2441
Eric Laurente0720872014-03-11 09:30:41 -07002442status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002443 audio_io_handle_t io,
2444 uint32_t strategy,
2445 int session,
2446 int id)
2447{
2448 ssize_t index = mOutputs.indexOfKey(io);
2449 if (index < 0) {
2450 index = mInputs.indexOfKey(io);
2451 if (index < 0) {
2452 ALOGW("registerEffect() unknown io %d", io);
2453 return INVALID_OPERATION;
2454 }
2455 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002456 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002457}
2458
Eric Laurentc241b0d2018-11-28 09:08:49 -08002459status_t AudioPolicyManager::unregisterEffect(int id)
2460{
2461 if (mEffects.getEffect(id) == nullptr) {
2462 return INVALID_OPERATION;
2463 }
2464
2465 if (mEffects.isEffectEnabled(id)) {
2466 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2467 setEffectEnabled(id, false);
2468 }
2469 return mEffects.unregisterEffect(id);
2470}
2471
2472status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2473{
2474 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2475 if (effect == nullptr) {
2476 return INVALID_OPERATION;
2477 }
2478
2479 status_t status = mEffects.setEffectEnabled(id, enabled);
2480 if (status == NO_ERROR) {
2481 mInputs.trackEffectEnabled(effect, enabled);
2482 }
2483 return status;
2484}
2485
Eric Laurentc75307b2015-03-17 15:29:32 -07002486bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2487{
Eric Laurent28d09f02016-03-08 10:43:05 -08002488 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002489 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2490 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002491 continue;
2492 }
2493 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2494 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002495 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002496}
2497
2498bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2499{
2500 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2501}
2502
Eric Laurente0720872014-03-11 09:30:41 -07002503bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002504{
2505 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002506 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002507 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002508 return true;
2509 }
2510 }
2511 return false;
2512}
2513
Eric Laurent275e8e92014-11-30 15:14:47 -08002514// Register a list of custom mixes with their attributes and format.
2515// When a mix is registered, corresponding input and output profiles are
2516// added to the remote submix hw module. The profile contains only the
2517// parameters (sampling rate, format...) specified by the mix.
2518// The corresponding input remote submix device is also connected.
2519//
2520// When a remote submix device is connected, the address is checked to select the
2521// appropriate profile and the corresponding input or output stream is opened.
2522//
2523// When capture starts, getInputForAttr() will:
2524// - 1 look for a mix matching the address passed in attribtutes tags if any
2525// - 2 if none found, getDeviceForInputSource() will:
2526// - 2.1 look for a mix matching the attributes source
2527// - 2.2 if none found, default to device selection by policy rules
2528// At this time, the corresponding output remote submix device is also connected
2529// and active playback use cases can be transferred to this mix if needed when reconnecting
2530// after AudioTracks are invalidated
2531//
2532// When playback starts, getOutputForAttr() will:
2533// - 1 look for a mix matching the address passed in attribtutes tags if any
2534// - 2 if none found, look for a mix matching the attributes usage
2535// - 3 if none found, default to device and output selection by policy rules.
2536
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002537status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002538{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2540 status_t res = NO_ERROR;
2541
2542 sp<HwModule> rSubmixModule;
2543 // examine each mix's route type
2544 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002545 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002547 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002548 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002549 break;
2550 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002551 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002554 rSubmixModule = mHwModules.getModuleFromName(
2555 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2556 if (rSubmixModule == 0) {
2557 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2558 i);
2559 res = INVALID_OPERATION;
2560 break;
2561 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002562 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002563
Eric Laurent97ac8712018-07-27 18:59:02 -07002564 String8 address = mix.mDeviceAddress;
2565 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2566 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2567 } else {
2568 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2569 }
François Gaffie036e1e92015-03-19 10:16:24 +01002570
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002572 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 res = INVALID_OPERATION;
2574 break;
2575 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002576 audio_config_t outputConfig = mix.mFormat;
2577 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002578 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2579 // stereo and let audio flinger do the channel conversion if needed.
2580 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2581 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2582 rSubmixModule->addOutputProfile(address, &outputConfig,
2583 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2584 rSubmixModule->addInputProfile(address, &inputConfig,
2585 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002586
Eric Laurent97ac8712018-07-27 18:59:02 -07002587 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002588 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2589 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002590 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002591 } else {
2592 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2593 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002594 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002595 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002596 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2597 String8 address = mix.mDeviceAddress;
2598 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002599 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2600 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002601
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002602 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2604 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2605 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2606 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2607 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2608 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002609 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2610 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002611 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002612 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002613 } else {
2614 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 }
2616 break;
2617 }
2618 }
2619
2620 if (res != NO_ERROR) {
2621 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002622 i, device, address.string());
2623 res = INVALID_OPERATION;
2624 break;
2625 } else if (!foundOutput) {
2626 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2627 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 res = INVALID_OPERATION;
2629 break;
2630 }
Eric Laurentc722f302014-12-10 11:21:49 -08002631 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002632 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002633 if (res != NO_ERROR) {
2634 unregisterPolicyMixes(mixes);
2635 }
2636 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002637}
2638
2639status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2640{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002641 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002642 status_t res = NO_ERROR;
2643 sp<HwModule> rSubmixModule;
2644 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002645 for (const auto& mix : mixes) {
2646 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002647
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002648 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002649 rSubmixModule = mHwModules.getModuleFromName(
2650 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2651 if (rSubmixModule == 0) {
2652 res = INVALID_OPERATION;
2653 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002654 }
2655 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002656
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002657 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002658
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002659 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2660 res = INVALID_OPERATION;
2661 continue;
2662 }
2663
2664 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2665 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2666 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2667 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002668 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002669 }
2670 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2671 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2672 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2673 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002674 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002675 }
2676 rSubmixModule->removeOutputProfile(address);
2677 rSubmixModule->removeInputProfile(address);
2678
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002679 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2680 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002681 res = INVALID_OPERATION;
2682 continue;
2683 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002684 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002685 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002686 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002687}
2688
Mikhail Naganov100f0122018-11-29 11:22:16 -08002689void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2690{
2691 size_t i = 0;
2692 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2693 for (const auto& fmt : mManualSurroundFormats) {
2694 if (i++ != 0) dst->append(", ");
2695 std::string sfmt;
2696 FormatConverter::toString(fmt, sfmt);
2697 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2698 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2699 }
2700}
2701
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002702status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2703 const Vector<AudioDeviceTypeAddr>& devices) {
2704 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2705 // uid/device affinity is only for output devices
2706 for (size_t i = 0; i < devices.size(); i++) {
2707 if (!audio_is_output_device(devices[i].mType)) {
2708 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2709 devices[i].mType);
2710 return BAD_VALUE;
2711 }
2712 }
2713 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2714 if (res == NO_ERROR) {
2715 // reevaluate outputs for all given devices
2716 for (size_t i = 0; i < devices.size(); i++) {
2717 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002718 devices[i].mType, devices[i].mAddress, String8(),
2719 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002720 SortedVector<audio_io_handle_t> outputs;
2721 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002722 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002723 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2724 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2725 return INVALID_OPERATION;
2726 }
2727 }
2728 }
2729 return res;
2730}
2731
2732status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2733 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2734 Vector<AudioDeviceTypeAddr> devices;
2735 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2736 if (res == NO_ERROR) {
2737 // reevaluate outputs for all found devices
2738 for (size_t i = 0; i < devices.size(); i++) {
2739 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002740 devices[i].mType, devices[i].mAddress, String8(),
2741 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002742 SortedVector<audio_io_handle_t> outputs;
2743 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002744 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002745 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2746 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2747 return INVALID_OPERATION;
2748 }
2749 }
2750 }
2751
2752 return res;
2753}
2754
Andy Hungc29d82b2018-10-05 12:23:17 -07002755void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002756{
Andy Hungc29d82b2018-10-05 12:23:17 -07002757 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2758 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002759 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002760 std::string stateLiteral;
2761 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002762 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002763 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2764 "communications", "media", "record", "dock", "system",
2765 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2766 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2767 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002768 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2769 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2770 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2771 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2772 dst->append(" (MANUAL: ");
2773 dumpManualSurroundFormats(dst);
2774 dst->append(")");
2775 }
2776 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002777 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002778 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2779 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2780 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2781 mAvailableOutputDevices.dump(dst, String8("Available output"));
2782 mAvailableInputDevices.dump(dst, String8("Available input"));
2783 mHwModulesAll.dump(dst);
2784 mOutputs.dump(dst);
2785 mInputs.dump(dst);
2786 mVolumeCurves->dump(dst);
2787 mEffects.dump(dst);
2788 mAudioPatches.dump(dst);
2789 mPolicyMixes.dump(dst);
2790 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002791}
2792
2793status_t AudioPolicyManager::dump(int fd)
2794{
2795 String8 result;
2796 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002797 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002798 return NO_ERROR;
2799}
2800
2801// This function checks for the parameters which can be offloaded.
2802// This can be enhanced depending on the capability of the DSP and policy
2803// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002804bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002805{
2806 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002807 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002808 offloadInfo.sample_rate, offloadInfo.channel_mask,
2809 offloadInfo.format,
2810 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2811 offloadInfo.has_video);
2812
Andy Hung2ddee192015-12-18 17:34:44 -08002813 if (mMasterMono) {
2814 return false; // no offloading if mono is set.
2815 }
2816
Eric Laurente552edb2014-03-10 17:42:56 -07002817 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002818 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2819 ALOGV("offload disabled by audio.offload.disable");
2820 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002821 }
2822
2823 // Check if stream type is music, then only allow offload as of now.
2824 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2825 {
2826 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2827 return false;
2828 }
2829
2830 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002831 const bool allowOffloadWithVideo =
2832 property_get_bool("audio.offload.video", false /* default_value */);
2833 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002834 ALOGV("isOffloadSupported: has_video == true, returning false");
2835 return false;
2836 }
2837
2838 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002839 const int min_duration_secs = property_get_int32(
2840 "audio.offload.min.duration.secs", -1 /* default_value */);
2841 if (min_duration_secs >= 0) {
2842 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2843 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2844 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002845 return false;
2846 }
2847 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2848 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2849 return false;
2850 }
2851
2852 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2853 // creating an offloaded track and tearing it down immediately after start when audioflinger
2854 // detects there is an active non offloadable effect.
2855 // FIXME: We should check the audio session here but we do not have it in this context.
2856 // This may prevent offloading in rare situations where effects are left active by apps
2857 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002858 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002859 return false;
2860 }
2861
2862 // See if there is a profile to support this.
2863 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002864 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002865 offloadInfo.sample_rate,
2866 offloadInfo.format,
2867 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002868 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2869 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002870 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2871 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002872}
2873
Michael Chana94fbb22018-04-24 14:31:19 +10002874bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2875 const audio_attributes_t& attributes) {
2876 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2877 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002878 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002879 config.sample_rate,
2880 config.format,
2881 config.channel_mask,
2882 output_flags,
2883 true /* directOnly */);
2884 ALOGV("%s() profile %sfound with name: %s, "
2885 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2886 __FUNCTION__, profile != 0 ? "" : "NOT ",
2887 (profile != 0 ? profile->getTagName().string() : "null"),
2888 config.sample_rate, config.format, config.channel_mask, output_flags);
2889 return (profile != 0);
2890}
2891
Eric Laurent6a94d692014-05-20 11:18:06 -07002892status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2893 audio_port_type_t type,
2894 unsigned int *num_ports,
2895 struct audio_port *ports,
2896 unsigned int *generation)
2897{
2898 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2899 generation == NULL) {
2900 return BAD_VALUE;
2901 }
2902 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2903 if (ports == NULL) {
2904 *num_ports = 0;
2905 }
2906
2907 size_t portsWritten = 0;
2908 size_t portsMax = *num_ports;
2909 *num_ports = 0;
2910 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002911 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2912 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002913 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002914 for (const auto& dev : mAvailableOutputDevices) {
2915 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002916 continue;
2917 }
2918 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002919 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002920 }
2921 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002922 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002923 }
2924 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002925 for (const auto& dev : mAvailableInputDevices) {
2926 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002927 continue;
2928 }
2929 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002930 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002931 }
2932 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002934 }
2935 }
2936 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2937 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2938 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2939 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2940 }
2941 *num_ports += mInputs.size();
2942 }
2943 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002944 size_t numOutputs = 0;
2945 for (size_t i = 0; i < mOutputs.size(); i++) {
2946 if (!mOutputs[i]->isDuplicated()) {
2947 numOutputs++;
2948 if (portsWritten < portsMax) {
2949 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2950 }
2951 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002952 }
Eric Laurent84c70242014-06-23 08:46:27 -07002953 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002954 }
2955 }
2956 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002957 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002958 return NO_ERROR;
2959}
2960
Eric Laurent99fcae42018-05-17 16:59:18 -07002961status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002962{
Eric Laurent99fcae42018-05-17 16:59:18 -07002963 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2964 return BAD_VALUE;
2965 }
2966 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2967 if (dev != 0) {
2968 dev->toAudioPort(port);
2969 return NO_ERROR;
2970 }
2971 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2972 if (dev != 0) {
2973 dev->toAudioPort(port);
2974 return NO_ERROR;
2975 }
2976 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2977 if (out != 0) {
2978 out->toAudioPort(port);
2979 return NO_ERROR;
2980 }
2981 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2982 if (in != 0) {
2983 in->toAudioPort(port);
2984 return NO_ERROR;
2985 }
2986 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002987}
2988
Eric Laurent6a94d692014-05-20 11:18:06 -07002989status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2990 audio_patch_handle_t *handle,
2991 uid_t uid)
2992{
2993 ALOGV("createAudioPatch()");
2994
2995 if (handle == NULL || patch == NULL) {
2996 return BAD_VALUE;
2997 }
2998 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2999
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003000 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003001 return BAD_VALUE;
3002 }
3003 // only one source per audio patch supported for now
3004 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 return INVALID_OPERATION;
3006 }
Eric Laurent874c42872014-08-08 15:13:39 -07003007
3008 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003009 return INVALID_OPERATION;
3010 }
Eric Laurent874c42872014-08-08 15:13:39 -07003011 for (size_t i = 0; i < patch->num_sinks; i++) {
3012 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3013 return INVALID_OPERATION;
3014 }
3015 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003016
3017 sp<AudioPatch> patchDesc;
3018 ssize_t index = mAudioPatches.indexOfKey(*handle);
3019
Eric Laurent6a94d692014-05-20 11:18:06 -07003020 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3021 patch->sources[0].role,
3022 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003023#if LOG_NDEBUG == 0
3024 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003025 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003026 patch->sinks[i].role,
3027 patch->sinks[i].type);
3028 }
3029#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003030
3031 if (index >= 0) {
3032 patchDesc = mAudioPatches.valueAt(index);
3033 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3034 mUidCached, patchDesc->mUid, uid);
3035 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3036 return INVALID_OPERATION;
3037 }
3038 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003039 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 }
3041
3042 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003043 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003044 if (outputDesc == NULL) {
3045 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3046 return BAD_VALUE;
3047 }
Eric Laurent84c70242014-06-23 08:46:27 -07003048 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3049 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 if (patchDesc != 0) {
3051 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3052 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3053 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3054 return BAD_VALUE;
3055 }
3056 }
Eric Laurent874c42872014-08-08 15:13:39 -07003057 DeviceVector devices;
3058 for (size_t i = 0; i < patch->num_sinks; i++) {
3059 // Only support mix to devices connection
3060 // TODO add support for mix to mix connection
3061 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3062 ALOGV("createAudioPatch() source mix but sink is not a device");
3063 return INVALID_OPERATION;
3064 }
3065 sp<DeviceDescriptor> devDesc =
3066 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3067 if (devDesc == 0) {
3068 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3069 return BAD_VALUE;
3070 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003071
François Gaffie11d30102018-11-02 16:09:09 +01003072 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003073 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003074 NULL, // updatedSamplingRate
3075 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003076 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003077 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003078 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003079 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003080 ALOGV("createAudioPatch() profile not supported for device %08x",
3081 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003082 return INVALID_OPERATION;
3083 }
3084 devices.add(devDesc);
3085 }
3086 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003087 return INVALID_OPERATION;
3088 }
Eric Laurent874c42872014-08-08 15:13:39 -07003089
Eric Laurent6a94d692014-05-20 11:18:06 -07003090 // TODO: reconfigure output format and channels here
3091 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003092 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003093 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003094 index = mAudioPatches.indexOfKey(*handle);
3095 if (index >= 0) {
3096 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3097 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3098 }
3099 patchDesc = mAudioPatches.valueAt(index);
3100 patchDesc->mUid = uid;
3101 ALOGV("createAudioPatch() success");
3102 } else {
3103 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3104 return INVALID_OPERATION;
3105 }
3106 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3107 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3108 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003109 // only one sink supported when connecting an input device to a mix
3110 if (patch->num_sinks > 1) {
3111 return INVALID_OPERATION;
3112 }
François Gaffie53615e22015-03-19 09:24:12 +01003113 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003114 if (inputDesc == NULL) {
3115 return BAD_VALUE;
3116 }
3117 if (patchDesc != 0) {
3118 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3119 return BAD_VALUE;
3120 }
3121 }
François Gaffie11d30102018-11-02 16:09:09 +01003122 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003123 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003124 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003125 return BAD_VALUE;
3126 }
3127
François Gaffie11d30102018-11-02 16:09:09 +01003128 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003129 patch->sinks[0].sample_rate,
3130 NULL, /*updatedSampleRate*/
3131 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003132 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003133 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003134 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003135 // FIXME for the parameter type,
3136 // and the NONE
3137 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003138 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003139 return INVALID_OPERATION;
3140 }
3141 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003142 ALOGV("%s() setting device %s on output %d", __func__,
3143 device->toString().c_str(), inputDesc->mIoHandle);
3144 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003145 index = mAudioPatches.indexOfKey(*handle);
3146 if (index >= 0) {
3147 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3148 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3149 }
3150 patchDesc = mAudioPatches.valueAt(index);
3151 patchDesc->mUid = uid;
3152 ALOGV("createAudioPatch() success");
3153 } else {
3154 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3155 return INVALID_OPERATION;
3156 }
3157 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3158 // device to device connection
3159 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003160 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 return BAD_VALUE;
3162 }
3163 }
François Gaffie11d30102018-11-02 16:09:09 +01003164 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003165 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003166 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003167 return BAD_VALUE;
3168 }
Eric Laurent874c42872014-08-08 15:13:39 -07003169
Eric Laurent6a94d692014-05-20 11:18:06 -07003170 //update source and sink with our own data as the data passed in the patch may
3171 // be incomplete.
3172 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003173 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003174
Eric Laurent874c42872014-08-08 15:13:39 -07003175 for (size_t i = 0; i < patch->num_sinks; i++) {
3176 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3177 ALOGV("createAudioPatch() source device but one sink is not a device");
3178 return INVALID_OPERATION;
3179 }
3180
François Gaffie11d30102018-11-02 16:09:09 +01003181 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003182 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003183 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003184 return BAD_VALUE;
3185 }
François Gaffie11d30102018-11-02 16:09:09 +01003186 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003187
Eric Laurent3bcf8592015-04-03 12:13:24 -07003188 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003189 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003190 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003191 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003192 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3193 (srcDevice->getModuleVersionMajor() < 3) ||
3194 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003195 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003196 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003197 return INVALID_OPERATION;
3198 }
Eric Laurent874c42872014-08-08 15:13:39 -07003199 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003200 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003201 // if the sink device is reachable via an opened output stream, request to go via
3202 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003203 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003204 if (output != AUDIO_IO_HANDLE_NONE) {
3205 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3206 if (outputDesc->isDuplicated()) {
3207 return INVALID_OPERATION;
3208 }
3209 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003210 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003211 newPatch.num_sources = 2;
3212 }
Eric Laurent83b88082014-06-20 18:31:16 -07003213 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003214 }
3215 // TODO: check from routing capabilities in config file and other conflicting patches
3216
Mikhail Naganovdc769682018-05-04 15:34:08 -07003217 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3218 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003219 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3220 status);
3221 return INVALID_OPERATION;
3222 }
3223 } else {
3224 return BAD_VALUE;
3225 }
3226 } else {
3227 return BAD_VALUE;
3228 }
3229 return NO_ERROR;
3230}
3231
3232status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3233 uid_t uid)
3234{
3235 ALOGV("releaseAudioPatch() patch %d", handle);
3236
3237 ssize_t index = mAudioPatches.indexOfKey(handle);
3238
3239 if (index < 0) {
3240 return BAD_VALUE;
3241 }
3242 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3243 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3244 mUidCached, patchDesc->mUid, uid);
3245 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3246 return INVALID_OPERATION;
3247 }
3248
3249 struct audio_patch *patch = &patchDesc->mPatch;
3250 patchDesc->mUid = mUidCached;
3251 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003252 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003253 if (outputDesc == NULL) {
3254 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3255 return BAD_VALUE;
3256 }
3257
François Gaffie11d30102018-11-02 16:09:09 +01003258 setOutputDevices(outputDesc,
3259 getNewOutputDevices(outputDesc, true /*fromCache*/),
3260 true,
3261 0,
3262 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003263 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3264 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003265 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003266 if (inputDesc == NULL) {
3267 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3268 return BAD_VALUE;
3269 }
3270 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003271 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003272 true,
3273 NULL);
3274 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003275 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3276 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3277 status, patchDesc->mAfPatchHandle);
3278 removeAudioPatch(patchDesc->mHandle);
3279 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003280 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003281 } else {
3282 return BAD_VALUE;
3283 }
3284 } else {
3285 return BAD_VALUE;
3286 }
3287 return NO_ERROR;
3288}
3289
3290status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3291 struct audio_patch *patches,
3292 unsigned int *generation)
3293{
François Gaffie53615e22015-03-19 09:24:12 +01003294 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003295 return BAD_VALUE;
3296 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003297 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003298 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003299}
3300
Eric Laurente1715a42014-05-20 11:30:42 -07003301status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003302{
Eric Laurente1715a42014-05-20 11:30:42 -07003303 ALOGV("setAudioPortConfig()");
3304
3305 if (config == NULL) {
3306 return BAD_VALUE;
3307 }
3308 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3309 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003310 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3311 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003312 }
3313
Eric Laurenta121f902014-06-03 13:32:54 -07003314 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003315 if (config->type == AUDIO_PORT_TYPE_MIX) {
3316 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003317 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003318 if (outputDesc == NULL) {
3319 return BAD_VALUE;
3320 }
Eric Laurent84c70242014-06-23 08:46:27 -07003321 ALOG_ASSERT(!outputDesc->isDuplicated(),
3322 "setAudioPortConfig() called on duplicated output %d",
3323 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003324 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003325 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003326 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003327 if (inputDesc == NULL) {
3328 return BAD_VALUE;
3329 }
Eric Laurenta121f902014-06-03 13:32:54 -07003330 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003331 } else {
3332 return BAD_VALUE;
3333 }
3334 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3335 sp<DeviceDescriptor> deviceDesc;
3336 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3337 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3338 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3339 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3340 } else {
3341 return BAD_VALUE;
3342 }
3343 if (deviceDesc == NULL) {
3344 return BAD_VALUE;
3345 }
Eric Laurenta121f902014-06-03 13:32:54 -07003346 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003347 } else {
3348 return BAD_VALUE;
3349 }
3350
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003351 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003352 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3353 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003354 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003355 audioPortConfig->toAudioPortConfig(&newConfig, config);
3356 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003357 }
Eric Laurenta121f902014-06-03 13:32:54 -07003358 if (status != NO_ERROR) {
3359 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003360 }
Eric Laurente1715a42014-05-20 11:30:42 -07003361
3362 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003363}
3364
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003365void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3366{
Eric Laurentd60560a2015-04-10 11:31:20 -07003367 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003368 clearAudioPatches(uid);
3369 clearSessionRoutes(uid);
3370}
3371
Eric Laurent6a94d692014-05-20 11:18:06 -07003372void AudioPolicyManager::clearAudioPatches(uid_t uid)
3373{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003374 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003375 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3376 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003377 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003378 }
3379 }
3380}
3381
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003382void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3383 audio_io_handle_t ouptutToSkip)
3384{
François Gaffie11d30102018-11-02 16:09:09 +01003385 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3386 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003387 for (size_t j = 0; j < mOutputs.size(); j++) {
3388 if (mOutputs.keyAt(j) == ouptutToSkip) {
3389 continue;
3390 }
3391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3392 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3393 continue;
3394 }
3395 // If the default device for this strategy is on another output mix,
3396 // invalidate all tracks in this strategy to force re connection.
3397 // Otherwise select new device on the output mix.
3398 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003399 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003400 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3401 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3402 }
3403 }
3404 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003405 setOutputDevices(
3406 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003407 }
3408 }
3409}
3410
3411void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3412{
3413 // remove output routes associated with this uid
3414 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003415 for (size_t i = 0; i < mOutputs.size(); i++) {
3416 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003417 for (const auto& client : outputDesc->getClientIterable()) {
3418 if (client->hasPreferredDevice() && client->uid() == uid) {
3419 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3420 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003421 }
3422 }
3423 }
3424 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003425 for (const auto& strategy : affectedStrategies) {
3426 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003427 }
3428
3429 // remove input routes associated with this uid
3430 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003431 for (size_t i = 0; i < mInputs.size(); i++) {
3432 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003433 for (const auto& client : inputDesc->getClientIterable()) {
3434 if (client->hasPreferredDevice() && client->uid() == uid) {
3435 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3436 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003437 }
3438 }
3439 }
3440 // reroute inputs if necessary
3441 SortedVector<audio_io_handle_t> inputsToClose;
3442 for (size_t i = 0; i < mInputs.size(); i++) {
3443 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003444 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003445 inputsToClose.add(inputDesc->mIoHandle);
3446 }
3447 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003448 for (const auto& input : inputsToClose) {
3449 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003450 }
3451}
3452
Eric Laurentd60560a2015-04-10 11:31:20 -07003453void AudioPolicyManager::clearAudioSources(uid_t uid)
3454{
3455 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003456 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3457 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003458 stopAudioSource(mAudioSources.keyAt(i));
3459 }
3460 }
3461}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003462
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003463status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3464 audio_io_handle_t *ioHandle,
3465 audio_devices_t *device)
3466{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003467 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3468 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003469 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3470 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003471
François Gaffiedf372692015-03-19 10:43:27 +01003472 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003473}
3474
Eric Laurentd60560a2015-04-10 11:31:20 -07003475status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003476 const audio_attributes_t *attributes,
3477 audio_port_handle_t *portId,
3478 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003479{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003480 ALOGV("%s", __FUNCTION__);
3481 *portId = AUDIO_PORT_HANDLE_NONE;
3482
3483 if (source == NULL || attributes == NULL || portId == NULL) {
3484 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3485 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003486 return BAD_VALUE;
3487 }
3488
Eric Laurentd60560a2015-04-10 11:31:20 -07003489 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3490 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003491 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3492 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003493 return INVALID_OPERATION;
3494 }
3495
François Gaffie11d30102018-11-02 16:09:09 +01003496 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003497 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003498 String8(source->ext.device.address),
3499 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003500 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003501 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003502 return BAD_VALUE;
3503 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003504
3505 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003506
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003507 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003508 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003509
3510 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003511 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003512 streamTypefromAttributesInt(attributes),
3513 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003514
3515 status_t status = connectAudioSource(sourceDesc);
3516 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003517 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003518 }
3519 return status;
3520}
3521
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003522status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003523{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003524 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003525
3526 // make sure we only have one patch per source.
3527 disconnectAudioSource(sourceDesc);
3528
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003529 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003530 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003531 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003532 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003533
François Gaffie11d30102018-11-02 16:09:09 +01003534 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3535 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3536 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3537 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3538 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003539
3540 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003541
François Gaffie11d30102018-11-02 16:09:09 +01003542 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3543 srcDevice->getModuleVersionMajor() >= 3 &&
3544 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3545 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003546 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003547 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003548 // create patch between src device and output device
3549 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003550 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003551 audio_attributes_t resultAttr;
3552 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3553 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3554 config.sample_rate = sourceDesc->config().sample_rate;
3555 config.channel_mask = sourceDesc->config().channel_mask;
3556 config.format = sourceDesc->config().format;
3557 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3558 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3559 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3560 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003561 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003562 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003563 return INVALID_OPERATION;
3564 }
3565 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3566 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003567 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003568 return INVALID_OPERATION;
3569 }
Eric Laurent733ce942017-12-07 12:18:25 -08003570 status_t status = outputDesc->start();
3571 if (status != NO_ERROR) {
3572 return status;
3573 }
3574
Eric Laurentd60560a2015-04-10 11:31:20 -07003575 // create a special patch with no sink and two sources:
3576 // - the second source indicates to PatchPanel through which output mix this patch should
3577 // be connected as well as the stream type for volume control
3578 // - the sink is defined by whatever output device is currently selected for the output
3579 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003580 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003581 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003582 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003583 &afPatchHandle,
3584 0);
3585 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3586 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003587 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003588 if (status != NO_ERROR) {
3589 ALOGW("%s patch panel could not connect device patch, error %d",
3590 __FUNCTION__, status);
3591 return INVALID_OPERATION;
3592 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003593
3594 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3595 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3596 return INVALID_OPERATION;
3597 }
3598 outputDesc->addClient(sourceDesc);
3599
Eric Laurentd60560a2015-04-10 11:31:20 -07003600 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003601 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003602
3603 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003604 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003605 return status;
3606 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003607 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003608 if (delayMs != 0) {
3609 usleep(delayMs * 1000);
3610 }
3611 }
3612
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003613 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3614 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003615
3616 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003617}
3618
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003619status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003620{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003621 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3622 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003623 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003624 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003625 return BAD_VALUE;
3626 }
3627 status_t status = disconnectAudioSource(sourceDesc);
3628
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003629 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003630 return status;
3631}
3632
Andy Hung2ddee192015-12-18 17:34:44 -08003633status_t AudioPolicyManager::setMasterMono(bool mono)
3634{
3635 if (mMasterMono == mono) {
3636 return NO_ERROR;
3637 }
3638 mMasterMono = mono;
3639 // if enabling mono we close all offloaded devices, which will invalidate the
3640 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3641 // for recreating the new AudioTrack as non-offloaded PCM.
3642 //
3643 // If disabling mono, we leave all tracks as is: we don't know which clients
3644 // and tracks are able to be recreated as offloaded. The next "song" should
3645 // play back offloaded.
3646 if (mMasterMono) {
3647 Vector<audio_io_handle_t> offloaded;
3648 for (size_t i = 0; i < mOutputs.size(); ++i) {
3649 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3650 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3651 offloaded.push(desc->mIoHandle);
3652 }
3653 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003654 for (const auto& handle : offloaded) {
3655 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003656 }
3657 }
3658 // update master mono for all remaining outputs
3659 for (size_t i = 0; i < mOutputs.size(); ++i) {
3660 updateMono(mOutputs.keyAt(i));
3661 }
3662 return NO_ERROR;
3663}
3664
3665status_t AudioPolicyManager::getMasterMono(bool *mono)
3666{
3667 *mono = mMasterMono;
3668 return NO_ERROR;
3669}
3670
Eric Laurentac9cef52017-06-09 15:46:26 -07003671float AudioPolicyManager::getStreamVolumeDB(
3672 audio_stream_type_t stream, int index, audio_devices_t device)
3673{
3674 return computeVolume(stream, index, device);
3675}
3676
jiabin81772902018-04-02 17:52:27 -07003677status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3678 audio_format_t *surroundFormats,
3679 bool *surroundFormatsEnabled,
3680 bool reported)
3681{
3682 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3683 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3684 return BAD_VALUE;
3685 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003686 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3687 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003688
3689 size_t formatsWritten = 0;
3690 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003691 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003692 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003693 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003694 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003695 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3696 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3697 FormatVector supportedFormats =
3698 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3699 for (size_t j = 0; j < supportedFormats.size(); j++) {
3700 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3701 formats.insert(supportedFormats[j]);
3702 } else {
3703 for (const auto& pair : mConfig.getSurroundFormats()) {
3704 if (pair.second.count(supportedFormats[j]) != 0) {
3705 formats.insert(pair.first);
3706 break;
3707 }
3708 }
3709 }
3710 }
jiabin81772902018-04-02 17:52:27 -07003711 }
3712 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003713 for (const auto& pair : mConfig.getSurroundFormats()) {
3714 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003715 }
3716 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003717 *numSurroundFormats = formats.size();
3718 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3719 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003720 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003721 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003722 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003723 bool formatEnabled = true;
3724 switch (forceUse) {
3725 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3726 formatEnabled = mManualSurroundFormats.count(format) != 0;
3727 break;
3728 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3729 formatEnabled = false;
3730 break;
3731 default: // AUTO or ALWAYS => true
3732 break;
jiabin81772902018-04-02 17:52:27 -07003733 }
3734 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3735 }
jiabin81772902018-04-02 17:52:27 -07003736 }
3737 return NO_ERROR;
3738}
3739
3740status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3741{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003742 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003743 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3744 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003745 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003746 return BAD_VALUE;
3747 }
3748
Mikhail Naganov100f0122018-11-29 11:22:16 -08003749 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3750 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003751 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003752 return INVALID_OPERATION;
3753 }
3754
Mikhail Naganov100f0122018-11-29 11:22:16 -08003755 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003756 return NO_ERROR;
3757 }
3758
Mikhail Naganov100f0122018-11-29 11:22:16 -08003759 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003760 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003761 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003762 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003763 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003764 }
3765 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003766 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003767 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003768 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003769 }
3770 }
3771
3772 sp<SwAudioOutputDescriptor> outputDesc;
3773 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003774 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003775 AUDIO_DEVICE_OUT_HDMI);
3776 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3777 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003778 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003779 String8 name = hdmiOutputDevices[i]->getName();
3780 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3781 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3782 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003783 name.c_str(),
3784 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003785 if (status != NO_ERROR) {
3786 continue;
3787 }
3788 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3789 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3790 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003791 name.c_str(),
3792 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003793 profileUpdated |= (status == NO_ERROR);
3794 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003795 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003796 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003797 AUDIO_DEVICE_IN_HDMI);
3798 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3799 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003800 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003801 String8 name = hdmiInputDevices[i]->getName();
3802 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3803 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3804 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003805 name.c_str(),
3806 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003807 if (status != NO_ERROR) {
3808 continue;
3809 }
3810 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3811 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3812 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003813 name.c_str(),
3814 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003815 profileUpdated |= (status == NO_ERROR);
3816 }
3817
jiabin81772902018-04-02 17:52:27 -07003818 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003819 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003820 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003821 }
3822
3823 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3824}
3825
Eric Laurentf32108e2018-10-04 17:22:04 -07003826void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003827{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003828 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003829
Eric Laurenta9f86652018-11-28 17:23:11 -08003830 for (size_t i = 0; i < mInputs.size(); i++) {
3831 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3832 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003833 for (const auto& client : clients) {
3834 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003835 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003836 }
3837 }
3838 }
3839}
3840
jiabin6012f912018-11-02 17:06:30 -07003841bool AudioPolicyManager::isHapticPlaybackSupported()
3842{
3843 for (const auto& hwModule : mHwModules) {
3844 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3845 for (const auto &outProfile : outputProfiles) {
3846 struct audio_port audioPort;
3847 outProfile->toAudioPort(&audioPort);
3848 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3849 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3850 return true;
3851 }
3852 }
3853 }
3854 }
3855 return false;
3856}
3857
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003858status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003859{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003860 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003861
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003862 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003863 if (patchDesc == 0) {
3864 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003865 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003866 return BAD_VALUE;
3867 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003868 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003869
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003870 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003871 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003872 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003873 if (status == NO_ERROR) {
3874 swOutputDesc->stop();
3875 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003876 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3877 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003878 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003879 if (hwOutputDesc != 0) {
3880 // release patch between src device and output device
3881 // close Hwoutput and remove from mHwOutputs
3882 } else {
3883 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3884 }
3885 }
3886 return NO_ERROR;
3887}
3888
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003889sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003890 audio_io_handle_t output, routing_strategy strategy)
3891{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003892 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003893 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003894 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3895 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003896 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003897 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003898 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3899 source = sourceDesc;
3900 break;
3901 }
3902 }
3903 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003904}
3905
Eric Laurente552edb2014-03-10 17:42:56 -07003906// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003907// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003908// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003909uint32_t AudioPolicyManager::nextAudioPortGeneration()
3910{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003911 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003912}
3913
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003914// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3915static const char *kConfigLocationList[] =
3916 {"/odm/etc", "/vendor/etc", "/system/etc"};
3917static const int kConfigLocationListSize =
3918 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3919
3920static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3921 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003922 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003923 status_t ret;
3924
Petri Gyntherf497f292018-04-17 18:46:10 -07003925 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3926 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3927 // A2DP offload supported but disabled: try to use special XML file
3928 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3929 }
3930 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3931
3932 for (const char* fileName : fileNames) {
3933 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003934 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3935 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003936 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003937 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003938 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003939 return ret;
3940 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003941 }
3942 }
3943 return ret;
3944}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003945
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003946AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3947 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003948 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003949 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003950 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003951 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003952 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003953 mVolumeCurves(new VolumeCurvesCollection()),
3954 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003955 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003956 mAudioPortGeneration(1),
3957 mBeaconMuteRefCount(0),
3958 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003959 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003960 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003961 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003962 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003963{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003964}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003965
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003966AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3967 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3968{
3969 loadConfig();
3970 initialize();
3971}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003972
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003973// This check is to catch any legacy platform updating to Q without having
3974// switched to XML since its deprecation on O.
3975// TODO: after Q release, remove this check and flag as XML is now the only
3976// option and all legacy platform should have transitioned to XML.
3977#ifndef USE_XML_AUDIO_POLICY_CONF
3978#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003979#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003980
3981void AudioPolicyManager::loadConfig() {
3982 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003983 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003984 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003985 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003986}
3987
3988status_t AudioPolicyManager::initialize() {
3989 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003990
3991 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003992 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3993 if (!engineInstance) {
3994 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003995 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003996 }
3997 // Retrieve the Policy Manager Interface
3998 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3999 if (mEngine == NULL) {
4000 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004001 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004002 }
4003 mEngine->setObserver(this);
4004 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004005 if (status != NO_ERROR) {
4006 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4007 return status;
4008 }
François Gaffie2110e042015-03-24 08:41:51 +01004009
Eric Laurent3a4311c2014-03-17 12:00:47 -07004010 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004011 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004012 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004013 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004014 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4015 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004016 continue;
4017 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004018 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004019 // open all output streams needed to access attached devices
4020 // except for direct output streams that are only opened when they are actually
4021 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004022 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004023 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004024 if (!outProfile->canOpenNewIo()) {
4025 ALOGE("Invalid Output profile max open count %u for profile %s",
4026 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4027 continue;
4028 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004029 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004030 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004031 continue;
4032 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004033 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004034 mTtsOutputAvailable = true;
4035 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004036
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004037 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004038 continue;
4039 }
François Gaffie11d30102018-11-02 16:09:09 +01004040 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4041 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4042 sp<DeviceDescriptor> supportedDevice = 0;
4043 if (supportedDevices.contains(mDefaultOutputDevice)) {
4044 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004045 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004046 // choose first device present in profile's SupportedDevices also part of
4047 // mAvailableOutputDevices.
4048 if (availProfileDevices.isEmpty()) {
4049 continue;
4050 }
4051 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004052 }
François Gaffie11d30102018-11-02 16:09:09 +01004053 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004054 continue;
4055 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004056 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4057 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004058 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004059 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4060 AUDIO_STREAM_DEFAULT,
4061 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004062 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004063 ALOGW("Cannot open output stream for devices %s on hw module %s",
4064 supportedDevice->toString().c_str(), hwModule->getName());
4065 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004066 }
François Gaffie11d30102018-11-02 16:09:09 +01004067 for (const auto &device : availProfileDevices) {
4068 // give a valid ID to an attached device once confirmed it is reachable
4069 if (!device->isAttached()) {
4070 device->attach(hwModule);
4071 }
4072 }
4073 if (mPrimaryOutput == 0 &&
4074 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4075 mPrimaryOutput = outputDesc;
4076 }
4077 addOutput(output, outputDesc);
4078 setOutputDevices(outputDesc,
4079 DeviceVector(supportedDevice),
4080 true,
4081 0,
4082 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004083 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004084 // open input streams needed to access attached devices to validate
4085 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004086 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004087 if (!inProfile->canOpenNewIo()) {
4088 ALOGE("Invalid Input profile max open count %u for profile %s",
4089 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4090 continue;
4091 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004092 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004093 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 continue;
4095 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004096 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004097 // available input devices
4098 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4099 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4100 if (availProfileDevices.isEmpty()) {
4101 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004102 continue;
4103 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004104 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004105 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004106
Eric Laurentd78f1532014-09-16 16:38:20 -07004107 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004108 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004109 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004110 AUDIO_SOURCE_MIC,
4111 AUDIO_INPUT_FLAG_NONE,
4112 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004113 if (status != NO_ERROR) {
4114 ALOGW("Cannot open input stream for device %s on hw module %s",
4115 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004116 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004117 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004118 }
François Gaffie11d30102018-11-02 16:09:09 +01004119 for (const auto &device : availProfileDevices) {
4120 // give a valid ID to an attached device once confirmed it is reachable
4121 if (!device->isAttached()) {
4122 device->attach(hwModule);
4123 device->importAudioPort(inProfile, true);
4124 }
4125 }
4126 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004127 }
4128 }
4129 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004130 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004131 for (size_t i = 0; i < devices.size();) {
4132 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004133 if (!device->isAttached()) {
4134 ALOGW("device %s is unreachable", device->toString().c_str());
4135 devices.remove(device);
4136 continue;
4137 }
4138 // Device is now validated and can be appended to the available devices of the engine
4139 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004140 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 }
François Gaffie11d30102018-11-02 16:09:09 +01004142 };
4143 checkAndSetAvailable(mAvailableOutputDevices);
4144 checkAndSetAvailable(mAvailableInputDevices);
4145
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004147 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4148 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4149 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004150 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004151 }
jiabin9ff780e2018-03-19 18:19:52 -07004152 // If microphones address is empty, set it according to device type
4153 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004154 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004155 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004156 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004157 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004158 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004159 }
4160 }
4161 }
Eric Laurente552edb2014-03-10 17:42:56 -07004162
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004163 if (mPrimaryOutput == 0) {
4164 ALOGE("Failed to open primary output");
4165 status = NO_INIT;
4166 }
Eric Laurente552edb2014-03-10 17:42:56 -07004167
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004168 // Silence ALOGV statements
4169 property_set("log.tag." LOG_TAG, "D");
4170
Eric Laurente552edb2014-03-10 17:42:56 -07004171 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004172 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004173}
4174
Eric Laurente0720872014-03-11 09:30:41 -07004175AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004176{
Eric Laurente552edb2014-03-10 17:42:56 -07004177 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004178 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004179 }
4180 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004181 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004182 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004183 mAvailableOutputDevices.clear();
4184 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004185 mOutputs.clear();
4186 mInputs.clear();
4187 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004188 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004189 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004190}
4191
Eric Laurente0720872014-03-11 09:30:41 -07004192status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004193{
Eric Laurent87ffa392015-05-22 10:32:38 -07004194 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004195}
4196
Eric Laurente552edb2014-03-10 17:42:56 -07004197// ---
4198
Eric Laurent98e38192018-02-15 18:31:53 -08004199void AudioPolicyManager::addOutput(audio_io_handle_t output,
4200 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004201{
Eric Laurent1c333e22014-05-20 10:48:17 -07004202 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004203 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004204 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004205 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004206 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004207}
4208
François Gaffie53615e22015-03-19 09:24:12 +01004209void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4210{
4211 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004212 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004213}
4214
Eric Laurent98e38192018-02-15 18:31:53 -08004215void AudioPolicyManager::addInput(audio_io_handle_t input,
4216 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004217{
Eric Laurent1c333e22014-05-20 10:48:17 -07004218 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004219 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004220}
Eric Laurente552edb2014-03-10 17:42:56 -07004221
François Gaffie11d30102018-11-02 16:09:09 +01004222status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004223 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004224 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004225{
François Gaffie11d30102018-11-02 16:09:09 +01004226 audio_devices_t deviceType = device->type();
4227 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004228 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004229
François Gaffie11d30102018-11-02 16:09:09 +01004230 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004231 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004232 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004233 }
Eric Laurente552edb2014-03-10 17:42:56 -07004234
Eric Laurent3b73df72014-03-11 09:06:29 -07004235 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004236 // first list already open outputs that can be routed to this device
4237 for (size_t i = 0; i < mOutputs.size(); i++) {
4238 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004239 if (!desc->isDuplicated() && desc->supportsDevice(device)
4240 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004241 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4242 mOutputs.keyAt(i), device->toString().c_str());
4243 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004244 }
4245 }
4246 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004247 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004248 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004249 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4250 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004251 if (profile->supportsDevice(device)) {
4252 profiles.add(profile);
4253 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4254 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004255 }
4256 }
4257 }
4258
Eric Laurent7b279bb2015-12-14 10:18:23 -08004259 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004260
Eric Laurente552edb2014-03-10 17:42:56 -07004261 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004262 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004263 return BAD_VALUE;
4264 }
4265
4266 // open outputs for matching profiles if needed. Direct outputs are also opened to
4267 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4268 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004269 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004270
4271 // nothing to do if one output is already opened for this profile
4272 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004273 for (j = 0; j < outputs.size(); j++) {
4274 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004275 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004276 // matching profile: save the sample rates, format and channel masks supported
4277 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004278 if (audio_device_is_digital(deviceType)) {
4279 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004280 }
Eric Laurente552edb2014-03-10 17:42:56 -07004281 break;
4282 }
4283 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004284 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004285 continue;
4286 }
4287
Eric Laurent3974e3b2017-12-07 17:58:43 -08004288 if (!profile->canOpenNewIo()) {
4289 ALOGW("Max Output number %u already opened for this profile %s",
4290 profile->maxOpenCount, profile->getTagName().c_str());
4291 continue;
4292 }
4293
Eric Laurent83efe1c2017-07-09 16:51:08 -07004294 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004295 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004296 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004297 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004298 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004299 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004300
Eric Laurentfe231122017-11-17 17:48:06 -08004301 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004302 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004303 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004304 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004305 mpClientInterface->setParameters(output, String8(param));
4306 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004307 }
François Gaffie11d30102018-11-02 16:09:09 +01004308 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004309 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004310 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004311 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004312 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004313 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004314 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004315 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004316 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4317 profile->pickAudioProfile(
4318 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004319 config.offload_info.sample_rate = config.sample_rate;
4320 config.offload_info.channel_mask = config.channel_mask;
4321 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004322
François Gaffie11d30102018-11-02 16:09:09 +01004323 status_t status = desc->open(&config, DeviceVector(device),
4324 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004325 AUDIO_OUTPUT_FLAG_NONE, &output);
4326 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004327 output = AUDIO_IO_HANDLE_NONE;
4328 }
Eric Laurentd4692962014-05-05 18:13:44 -07004329 }
4330
Eric Laurentcf2c0212014-07-25 16:20:43 -07004331 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004332 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004333 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004334 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004335 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4336 policyMix->setOutput(desc);
4337 desc->mPolicyMix = policyMix->getMix();
4338 } else {
4339 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004340 address.string());
4341 }
François Gaffie036e1e92015-03-19 10:16:24 +01004342
Eric Laurent87ffa392015-05-22 10:32:38 -07004343 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4344 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004345 // no duplicated output for direct outputs and
4346 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004347 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004348
Eric Laurentd4692962014-05-05 18:13:44 -07004349 //TODO: configure audio effect output stage here
4350
4351 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004352 sp<SwAudioOutputDescriptor> dupOutputDesc =
4353 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4354 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4355 &duplicatedOutput);
4356 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004357 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004358 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004359 } else {
4360 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004361 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004362 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004363 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004364 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004365 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004366 }
Eric Laurente552edb2014-03-10 17:42:56 -07004367 }
4368 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004369 } else {
4370 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004371 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004372 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004373 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004374 profiles.removeAt(profile_index);
4375 profile_index--;
4376 } else {
4377 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004378 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004379 if (audio_device_is_digital(deviceType)) {
4380 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004381 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004382
François Gaffie11d30102018-11-02 16:09:09 +01004383 if (device_distinguishes_on_address(deviceType)) {
4384 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4385 device->toString().c_str());
4386 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4387 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004388 }
Eric Laurente552edb2014-03-10 17:42:56 -07004389 ALOGV("checkOutputsForDevice(): adding output %d", output);
4390 }
4391 }
4392
4393 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004394 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004395 return BAD_VALUE;
4396 }
Eric Laurentd4692962014-05-05 18:13:44 -07004397 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004398 // check if one opened output is not needed any more after disconnecting one device
4399 for (size_t i = 0; i < mOutputs.size(); i++) {
4400 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004401 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004402 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004403 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4404 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004405 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004406 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004407 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4408 mOutputs.keyAt(i));
4409 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004410 }
Eric Laurente552edb2014-03-10 17:42:56 -07004411 }
4412 }
Eric Laurentd4692962014-05-05 18:13:44 -07004413 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004414 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004415 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4416 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004417 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004418 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004419 "clearing direct output profile %zu on module %s",
4420 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004421 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004422 }
4423 }
4424 }
4425 }
4426 return NO_ERROR;
4427}
4428
François Gaffie11d30102018-11-02 16:09:09 +01004429status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004430 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004431 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004432{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004433 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004434
François Gaffie11d30102018-11-02 16:09:09 +01004435 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004436 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004437 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004438 }
4439
Eric Laurentd4692962014-05-05 18:13:44 -07004440 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4441 // first list already open inputs that can be routed to this device
4442 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4443 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004444 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004445 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4446 inputs.add(mInputs.keyAt(input_index));
4447 }
4448 }
4449
4450 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004451 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004452 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004453 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004454 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004455 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004456 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004457
François Gaffie11d30102018-11-02 16:09:09 +01004458 if (profile->supportsDevice(device)) {
4459 profiles.add(profile);
4460 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4461 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004462 }
4463 }
4464 }
4465
4466 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004467 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004468 return BAD_VALUE;
4469 }
4470
4471 // open inputs for matching profiles if needed. Direct inputs are also opened to
4472 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4473 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4474
Eric Laurent1c333e22014-05-20 10:48:17 -07004475 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004476
Eric Laurentd4692962014-05-05 18:13:44 -07004477 // nothing to do if one input is already opened for this profile
4478 size_t input_index;
4479 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4480 desc = mInputs.valueAt(input_index);
4481 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004482 if (audio_device_is_digital(device->type())) {
4483 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004484 }
Eric Laurentd4692962014-05-05 18:13:44 -07004485 break;
4486 }
4487 }
4488 if (input_index != mInputs.size()) {
4489 continue;
4490 }
4491
Eric Laurent3974e3b2017-12-07 17:58:43 -08004492 if (!profile->canOpenNewIo()) {
4493 ALOGW("Max Input number %u already opened for this profile %s",
4494 profile->maxOpenCount, profile->getTagName().c_str());
4495 continue;
4496 }
4497
Eric Laurentfe231122017-11-17 17:48:06 -08004498 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004499 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004500 status_t status = desc->open(nullptr,
4501 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004502 AUDIO_SOURCE_MIC,
4503 AUDIO_INPUT_FLAG_NONE,
4504 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004505
Eric Laurentcf2c0212014-07-25 16:20:43 -07004506 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004507 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004508 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004509 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004510 mpClientInterface->setParameters(input, String8(param));
4511 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004512 }
François Gaffie11d30102018-11-02 16:09:09 +01004513 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004514 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004515 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004516 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004517 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004518 }
4519
4520 if (input != 0) {
4521 addInput(input, desc);
4522 }
4523 } // endif input != 0
4524
Eric Laurentcf2c0212014-07-25 16:20:43 -07004525 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004526 ALOGW("%s could not open input for device %s", __func__,
4527 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004528 profiles.removeAt(profile_index);
4529 profile_index--;
4530 } else {
4531 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004532 if (audio_device_is_digital(device->type())) {
4533 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004534 }
Eric Laurentd4692962014-05-05 18:13:44 -07004535 ALOGV("checkInputsForDevice(): adding input %d", input);
4536 }
4537 } // end scan profiles
4538
4539 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004540 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004541 return BAD_VALUE;
4542 }
4543 } else {
4544 // Disconnect
4545 // check if one opened input is not needed any more after disconnecting one device
4546 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4547 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004548 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004549 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4550 mInputs.keyAt(input_index));
4551 inputs.add(mInputs.keyAt(input_index));
4552 }
4553 }
4554 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004555 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004556 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004557 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004558 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004559 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004560 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004561 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4562 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004563 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004564 }
4565 }
4566 }
4567 } // end disconnect
4568
4569 return NO_ERROR;
4570}
4571
4572
Eric Laurente0720872014-03-11 09:30:41 -07004573void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004574{
4575 ALOGV("closeOutput(%d)", output);
4576
Eric Laurentc75307b2015-03-17 15:29:32 -07004577 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004578 if (outputDesc == NULL) {
4579 ALOGW("closeOutput() unknown output %d", output);
4580 return;
4581 }
François Gaffie036e1e92015-03-19 10:16:24 +01004582 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004583
Eric Laurente552edb2014-03-10 17:42:56 -07004584 // look for duplicated outputs connected to the output being removed.
4585 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004586 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004587 if (dupOutputDesc->isDuplicated() &&
4588 (dupOutputDesc->mOutput1 == outputDesc ||
4589 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004590 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004591 if (dupOutputDesc->mOutput1 == outputDesc) {
4592 outputDesc2 = dupOutputDesc->mOutput2;
4593 } else {
4594 outputDesc2 = dupOutputDesc->mOutput1;
4595 }
4596 // As all active tracks on duplicated output will be deleted,
4597 // and as they were also referenced on the other output, the reference
4598 // count for their stream type must be adjusted accordingly on
4599 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004600 const bool wasActive = outputDesc2->isActive();
4601 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4602 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004603 }
Eric Laurent733ce942017-12-07 12:18:25 -08004604 // stop() will be a no op if the output is still active but is needed in case all
4605 // active streams refcounts where cleared above
4606 if (wasActive) {
4607 outputDesc2->stop();
4608 }
Eric Laurente552edb2014-03-10 17:42:56 -07004609 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4610 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4611
4612 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004613 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004614 }
4615 }
4616
Eric Laurent05b90f82014-08-27 15:32:29 -07004617 nextAudioPortGeneration();
4618
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004619 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004620 if (index >= 0) {
4621 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004622 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004623 mAudioPatches.removeItemsAt(index);
4624 mpClientInterface->onAudioPatchListUpdate();
4625 }
4626
Eric Laurentfe231122017-11-17 17:48:06 -08004627 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004628
François Gaffie53615e22015-03-19 09:24:12 +01004629 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004630 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004631
4632 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4633 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004634 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004635 bool directOutputOpen = false;
4636 for (size_t i = 0; i < mOutputs.size(); i++) {
4637 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4638 directOutputOpen = true;
4639 break;
4640 }
4641 }
4642 if (!directOutputOpen) {
4643 ALOGV("no direct outputs open, reset MSD patch");
4644 setMsdPatch();
4645 }
4646 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004647}
4648
4649void AudioPolicyManager::closeInput(audio_io_handle_t input)
4650{
4651 ALOGV("closeInput(%d)", input);
4652
4653 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4654 if (inputDesc == NULL) {
4655 ALOGW("closeInput() unknown input %d", input);
4656 return;
4657 }
4658
Eric Laurent6a94d692014-05-20 11:18:06 -07004659 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004660
François Gaffie11d30102018-11-02 16:09:09 +01004661 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004662 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004663 if (index >= 0) {
4664 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004665 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004666 mAudioPatches.removeItemsAt(index);
4667 mpClientInterface->onAudioPatchListUpdate();
4668 }
4669
Eric Laurentfe231122017-11-17 17:48:06 -08004670 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004671 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004672
François Gaffie11d30102018-11-02 16:09:09 +01004673 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4674 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004675 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4676 SoundTrigger::setCaptureState(false);
4677 }
Eric Laurente552edb2014-03-10 17:42:56 -07004678}
4679
François Gaffie11d30102018-11-02 16:09:09 +01004680SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4681 const DeviceVector &devices,
4682 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004683{
4684 SortedVector<audio_io_handle_t> outputs;
4685
François Gaffie11d30102018-11-02 16:09:09 +01004686 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004687 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004688 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004689 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004690 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004691 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4692 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004693 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004694 outputs.add(openOutputs.keyAt(i));
4695 }
4696 }
4697 return outputs;
4698}
4699
Mikhail Naganov37977152018-07-11 15:54:44 -07004700void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4701{
4702 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4703 // output is suspended before any tracks are moved to it
4704 checkA2dpSuspend();
4705 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004706 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004707 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004708 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004709 setMsdPatch();
4710 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004711}
4712
Eric Laurente0720872014-03-11 09:30:41 -07004713void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004714{
François Gaffie11d30102018-11-02 16:09:09 +01004715 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4716 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4717 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4718 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004719
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004720 // also take into account external policy-related changes: add all outputs which are
4721 // associated with policies in the "before" and "after" output vectors
4722 ALOGVV("checkOutputForStrategy(): policy related outputs");
4723 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004724 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004725 if (desc != 0 && desc->mPolicyMix != NULL) {
4726 srcOutputs.add(desc->mIoHandle);
4727 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4728 }
4729 }
4730 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004731 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004732 if (desc != 0 && desc->mPolicyMix != NULL) {
4733 dstOutputs.add(desc->mIoHandle);
4734 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4735 }
4736 }
4737
Francois Gaffie716e1432019-01-14 16:58:59 +01004738 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004739 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4740 // audio from invalidated tracks will be rendered when unmuting
4741 uint32_t maxLatency = 0;
4742 for (audio_io_handle_t srcOut : srcOutputs) {
4743 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4744 if (desc != 0 && maxLatency < desc->latency()) {
4745 maxLatency = desc->latency();
4746 }
4747 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004748 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
4749 "%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4750 std::to_string(srcOutputs[0]).c_str(),
4751 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004752 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004753 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004754 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4755 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004756 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004757 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4758 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004759 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004760 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004761 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004762 if (source != 0){
4763 connectAudioSource(source);
4764 }
Eric Laurente552edb2014-03-10 17:42:56 -07004765 }
4766
4767 // Move effects associated to this strategy from previous output to new output
4768 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004769 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004770 }
4771 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004772 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004773 if (getStrategy((audio_stream_type_t)i) == strategy) {
4774 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004775 }
4776 }
4777 }
4778}
4779
Eric Laurente0720872014-03-11 09:30:41 -07004780void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004781{
François Gaffie2110e042015-03-24 08:41:51 +01004782 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004783 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004784 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004785 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004786 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004787 checkOutputForStrategy(STRATEGY_SONIFICATION);
4788 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004789 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004790 checkOutputForStrategy(STRATEGY_MEDIA);
4791 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004792 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004793}
4794
Eric Laurente0720872014-03-11 09:30:41 -07004795void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004796{
François Gaffie53615e22015-03-19 09:24:12 +01004797 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004798 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004799 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004800 return;
4801 }
4802
Eric Laurent3a4311c2014-03-17 12:00:47 -07004803 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004804 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4805 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4806 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004807
4808 // if suspended, restore A2DP output if:
4809 // ((SCO device is NOT connected) ||
4810 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4811 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004812 //
Eric Laurentf732e072016-08-03 19:30:28 -07004813 // if not suspended, suspend A2DP output if:
4814 // (SCO device is connected) &&
4815 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4816 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004817 //
4818 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004819 if (!isScoConnected ||
4820 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4821 AUDIO_POLICY_FORCE_BT_SCO) &&
4822 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4823 AUDIO_POLICY_FORCE_BT_SCO) &&
4824 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004825 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004826
4827 mpClientInterface->restoreOutput(a2dpOutput);
4828 mA2dpSuspended = false;
4829 }
4830 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004831 if (isScoConnected &&
4832 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4833 AUDIO_POLICY_FORCE_BT_SCO) ||
4834 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4835 AUDIO_POLICY_FORCE_BT_SCO) ||
4836 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004837 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004838
4839 mpClientInterface->suspendOutput(a2dpOutput);
4840 mA2dpSuspended = true;
4841 }
4842 }
4843}
4844
Eric Laurent97ac8712018-07-27 18:59:02 -07004845template <class IoDescriptor, class Filter>
4846sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4847 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4848{
4849 auto activeClients = desc->clientsList(true /*activeOnly*/);
4850 auto activeClientsWithRoute =
4851 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4852 active = activeClients.size() > 0;
4853 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4854 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4855 }
4856 return nullptr;
4857}
4858
4859template <class IoCollection, class Filter>
4860sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4861 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4862{
4863 sp<DeviceDescriptor> device;
4864 for (size_t i = 0; i < ioCollection.size(); i++) {
4865 auto desc = ioCollection.valueAt(i);
4866 bool active;
4867 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4868 if (active && curDevice == nullptr) {
4869 return nullptr;
4870 } else if (curDevice != nullptr) {
4871 device = curDevice;
4872 }
4873 }
4874 return device;
4875}
4876
François Gaffie11d30102018-11-02 16:09:09 +01004877DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4878 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004879{
François Gaffie11d30102018-11-02 16:09:09 +01004880 DeviceVector devices;
4881
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004882 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 if (index >= 0) {
4884 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4885 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004886 ALOGV("%s device %s forced by patch %d", __func__,
4887 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4888 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 }
4890 }
4891
Eric Laurent97ac8712018-07-27 18:59:02 -07004892 // Honor explicit routing requests only if no client using default routing is active on this
4893 // input: a specific app can not force routing for other apps by setting a preferred device.
4894 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004895 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004896 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004897 if (device != nullptr) {
4898 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004899 }
4900
Eric Laurente552edb2014-03-10 17:42:56 -07004901 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004902 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004903 // use device for strategy enforced audible
4904 // 2: we are in call or the strategy phone is active on the output:
4905 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004906 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004907 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004908 // 4: the strategy for enforced audible is active but not enforced on the output:
4909 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004910 // 5: the strategy accessibility is active on the output:
4911 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004912 // 6: the strategy "respectful" sonification is active on the output:
4913 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004914 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004915 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004916 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004917 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004918 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004919 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004920
4921 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4922 // with a refined rule considering mutually exclusive devices (using same backend)
4923 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004924 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004925 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01004926 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004927 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004928 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004929 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004930 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01004931 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004932 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004933 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004934 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01004935 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004936 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01004937 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004938 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01004939 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004940 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01004941 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004942 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01004943 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004944 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01004945 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004946 }
4947
François Gaffie11d30102018-11-02 16:09:09 +01004948 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
4949 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07004950}
4951
François Gaffie11d30102018-11-02 16:09:09 +01004952sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
4953 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004954{
François Gaffie11d30102018-11-02 16:09:09 +01004955 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07004956
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004957 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 if (index >= 0) {
4959 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4960 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004961 ALOGV("getNewInputDevice() device %s forced by patch %d",
4962 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
4963 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07004964 }
4965 }
4966
Eric Laurent97ac8712018-07-27 18:59:02 -07004967 // Honor explicit routing requests only if no client using default routing is active on this
4968 // input: a specific app can not force routing for other apps by setting a preferred device.
4969 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01004970 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4971 if (device != nullptr) {
4972 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07004973 }
4974
Eric Laurentdc95a252018-04-12 12:46:56 -07004975 // If we are not in call and no client is active on this input, this methods returns
4976 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01004977 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
4978 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4979 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07004980 }
Francois Gaffie716e1432019-01-14 16:58:59 +01004981 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
4982 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08004983 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004984
Eric Laurente552edb2014-03-10 17:42:56 -07004985 return device;
4986}
4987
Eric Laurent794fde22016-03-11 09:50:45 -08004988bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4989 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004990 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004991}
4992
Eric Laurente0720872014-03-11 09:30:41 -07004993uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004994 return (uint32_t)getStrategy(stream);
4995}
4996
Eric Laurente0720872014-03-11 09:30:41 -07004997audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004998 // By checking the range of stream before calling getStrategy, we avoid
4999 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5000 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005001 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 return AUDIO_DEVICE_NONE;
5003 }
François Gaffie11d30102018-11-02 16:09:09 +01005004 DeviceVector activeDevices;
5005 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08005006 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5007 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005008 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 }
Eric Laurent794fde22016-03-11 09:50:45 -08005010 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01005011 DeviceVector curDevices =
5012 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
5013 devices.merge(curDevices);
5014 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005015 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005016 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005017 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005018 }
5019 }
Eric Laurente552edb2014-03-10 17:42:56 -07005020 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005021
Eric Laurentb0688d62018-08-14 15:49:18 -07005022 // Favor devices selected on active streams if any to report correct device in case of
5023 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005024 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005025 devices = activeDevices;
5026 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005027 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5028 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005029 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5030 if (!speakerSafeDevices.isEmpty()) {
5031 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5032 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005033 }
François Gaffie11d30102018-11-02 16:09:09 +01005034 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005035}
5036
François Gaffie2110e042015-03-24 08:41:51 +01005037routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5038{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005039 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005040 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005041}
5042
Eric Laurent97ac8712018-07-27 18:59:02 -07005043routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005044 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005045 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005046 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005047 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005048 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005049 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005050 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005051 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005052 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005053}
5054
Eric Laurente0720872014-03-11 09:30:41 -07005055void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005056 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005057 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005058 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5059 updateDevicesAndOutputs();
5060 break;
5061 default:
5062 break;
5063 }
5064}
5065
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005066uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005067
5068 // skip beacon mute management if a dedicated TTS output is available
5069 if (mTtsOutputAvailable) {
5070 return 0;
5071 }
5072
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005073 switch(event) {
5074 case STARTING_OUTPUT:
5075 mBeaconMuteRefCount++;
5076 break;
5077 case STOPPING_OUTPUT:
5078 if (mBeaconMuteRefCount > 0) {
5079 mBeaconMuteRefCount--;
5080 }
5081 break;
5082 case STARTING_BEACON:
5083 mBeaconPlayingRefCount++;
5084 break;
5085 case STOPPING_BEACON:
5086 if (mBeaconPlayingRefCount > 0) {
5087 mBeaconPlayingRefCount--;
5088 }
5089 break;
5090 }
5091
5092 if (mBeaconMuteRefCount > 0) {
5093 // any playback causes beacon to be muted
5094 return setBeaconMute(true);
5095 } else {
5096 // no other playback: unmute when beacon starts playing, mute when it stops
5097 return setBeaconMute(mBeaconPlayingRefCount == 0);
5098 }
5099}
5100
5101uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5102 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5103 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5104 // keep track of muted state to avoid repeating mute/unmute operations
5105 if (mBeaconMuted != mute) {
5106 // mute/unmute AUDIO_STREAM_TTS on all outputs
5107 ALOGV("\t muting %d", mute);
5108 uint32_t maxLatency = 0;
5109 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005110 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005111 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005113 0 /*delay*/, AUDIO_DEVICE_NONE);
5114 const uint32_t latency = desc->latency() * 2;
5115 if (latency > maxLatency) {
5116 maxLatency = latency;
5117 }
5118 }
5119 mBeaconMuted = mute;
5120 return maxLatency;
5121 }
5122 return 0;
5123}
5124
François Gaffie11d30102018-11-02 16:09:09 +01005125DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005126{
Eric Laurent97ac8712018-07-27 18:59:02 -07005127 // Honor explicit routing requests only if all active clients have a preferred route in which
5128 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005129 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5130 if (device != nullptr) {
5131 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005132 }
5133
Eric Laurente552edb2014-03-10 17:42:56 -07005134 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005135 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5136 mDevicesForStrategy[strategy].toString().c_str());
5137 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005138 }
François Gaffie11d30102018-11-02 16:09:09 +01005139 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005140}
5141
Eric Laurente0720872014-03-11 09:30:41 -07005142void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005143{
5144 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005145 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005146 }
5147 mPreviousOutputs = mOutputs;
5148}
5149
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005150uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005151 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005152 uint32_t delayMs)
5153{
5154 // mute/unmute strategies using an incompatible device combination
5155 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5156 // if unmuting, unmute only after the specified delay
5157 if (outputDesc->isDuplicated()) {
5158 return 0;
5159 }
5160
5161 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005162 audio_devices_t deviceType = outputDesc->devices().types();
5163 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005164
5165 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005166 audio_devices_t curDeviceType =
5167 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5168 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5169 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005170 bool doMute = false;
5171
5172 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5173 doMute = true;
5174 outputDesc->mStrategyMutedByDevice[i] = true;
5175 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5176 doMute = true;
5177 outputDesc->mStrategyMutedByDevice[i] = false;
5178 }
Eric Laurent99401132014-05-07 19:48:15 -07005179 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005180 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005181 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005182 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005183 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005184 continue;
5185 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005186 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005187 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005188 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005189 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005190 if (mute) {
5191 // FIXME: should not need to double latency if volume could be applied
5192 // immediately by the audioflinger mixer. We must account for the delay
5193 // between now and the next time the audioflinger thread for this output
5194 // will process a buffer (which corresponds to one buffer size,
5195 // usually 1/2 or 1/4 of the latency).
5196 if (muteWaitMs < desc->latency() * 2) {
5197 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005198 }
5199 }
5200 }
5201 }
5202 }
5203 }
5204
Eric Laurent99401132014-05-07 19:48:15 -07005205 // temporary mute output if device selection changes to avoid volume bursts due to
5206 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005207 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005208 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5209 // temporary mute duration is conservatively set to 4 times the reported latency
5210 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5211 if (muteWaitMs < tempMuteWaitMs) {
5212 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005213 }
Eric Laurentdc462862016-07-19 12:29:53 -07005214
Eric Laurent99401132014-05-07 19:48:15 -07005215 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005216 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005217 // make sure that we do not start the temporary mute period too early in case of
5218 // delayed device change
5219 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005220 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005221 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005222 }
5223 }
5224 }
5225
Eric Laurente552edb2014-03-10 17:42:56 -07005226 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5227 if (muteWaitMs > delayMs) {
5228 muteWaitMs -= delayMs;
5229 usleep(muteWaitMs * 1000);
5230 return muteWaitMs;
5231 }
5232 return 0;
5233}
5234
François Gaffie11d30102018-11-02 16:09:09 +01005235uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5236 const DeviceVector &devices,
5237 bool force,
5238 int delayMs,
5239 audio_patch_handle_t *patchHandle,
5240 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005241{
François Gaffie11d30102018-11-02 16:09:09 +01005242 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005243 uint32_t muteWaitMs;
5244
5245 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005246 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5247 nullptr /* patchHandle */, requiresMuteCheck);
5248 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5249 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005250 return muteWaitMs;
5251 }
Eric Laurente552edb2014-03-10 17:42:56 -07005252
5253 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005254 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005255
François Gaffie11d30102018-11-02 16:09:09 +01005256 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5257 // output profile
5258 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5259 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5260 return 0;
5261 }
Eric Laurente552edb2014-03-10 17:42:56 -07005262
François Gaffie11d30102018-11-02 16:09:09 +01005263 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005264
François Gaffie11d30102018-11-02 16:09:09 +01005265 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5266
5267 if (!filteredDevices.isEmpty()) {
5268 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005269 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005270
5271 // if the outputs are not materially active, there is no need to mute.
5272 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005273 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005274 } else {
5275 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5276 muteWaitMs = 0;
5277 }
Eric Laurente552edb2014-03-10 17:42:56 -07005278
5279 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005280 // the requested device is AUDIO_DEVICE_NONE
5281 // OR the requested device is the same as current device
5282 // AND force is not specified
5283 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005284 // Doing this check here allows the caller to call setOutputDevices() without conditions
5285 if ((!filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5286 !force && outputDesc->getPatchHandle() != 0) {
5287 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5288 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005289 return muteWaitMs;
5290 }
5291
François Gaffie11d30102018-11-02 16:09:09 +01005292 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005293
Eric Laurente552edb2014-03-10 17:42:56 -07005294 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005295 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005296 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005297 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005298 PatchBuilder patchBuilder;
5299 patchBuilder.addSource(outputDesc);
5300 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5301 for (const auto &filteredDevice : filteredDevices) {
5302 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005303 }
5304
François Gaffie11d30102018-11-02 16:09:09 +01005305 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005306 }
Eric Laurente552edb2014-03-10 17:42:56 -07005307
5308 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005309 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005310
5311 return muteWaitMs;
5312}
5313
Eric Laurentc75307b2015-03-17 15:29:32 -07005314status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 int delayMs,
5316 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005317{
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 ssize_t index;
5319 if (patchHandle) {
5320 index = mAudioPatches.indexOfKey(*patchHandle);
5321 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005322 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 }
5324 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005325 return INVALID_OPERATION;
5326 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005327 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5328 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005329 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005330 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005331 removeAudioPatch(patchDesc->mHandle);
5332 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005333 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005334 return status;
5335}
5336
5337status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005338 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005339 bool force,
5340 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005341{
5342 status_t status = NO_ERROR;
5343
Eric Laurent1f2f2232014-06-02 12:01:23 -07005344 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005345 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5346 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005347
François Gaffie11d30102018-11-02 16:09:09 +01005348 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005349 PatchBuilder patchBuilder;
5350 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005351 // AUDIO_SOURCE_HOTWORD is for internal use only:
5352 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005353 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5354 auto result = usecase;
5355 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5356 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5357 }
5358 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005359 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005360 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005361 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005362 }
5363 }
5364 return status;
5365}
5366
Eric Laurent6a94d692014-05-20 11:18:06 -07005367status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5368 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005369{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005370 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005371 ssize_t index;
5372 if (patchHandle) {
5373 index = mAudioPatches.indexOfKey(*patchHandle);
5374 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005375 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 }
5377 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005378 return INVALID_OPERATION;
5379 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5381 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005382 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005383 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005384 removeAudioPatch(patchDesc->mHandle);
5385 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005386 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005387 return status;
5388}
5389
François Gaffie11d30102018-11-02 16:09:09 +01005390sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005391 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005392 audio_format_t& format,
5393 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005394 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005395{
5396 // Choose an input profile based on the requested capture parameters: select the first available
5397 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005398 //
5399 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5400 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005401
Glenn Kasten730b9262018-03-29 15:01:26 -07005402 sp<IOProfile> firstInexact;
5403 uint32_t updatedSamplingRate = 0;
5404 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5405 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005406 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005407 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005408 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005409 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005410 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005411 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005412 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005413 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005414 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005415 &channelMask /*updatedChannelMask*/,
5416 // FIXME ugly cast
5417 (audio_output_flags_t) flags,
5418 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005419 return profile;
5420 }
François Gaffie11d30102018-11-02 16:09:09 +01005421 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005422 samplingRate,
5423 &updatedSamplingRate,
5424 format,
5425 &updatedFormat,
5426 channelMask,
5427 &updatedChannelMask,
5428 // FIXME ugly cast
5429 (audio_output_flags_t) flags,
5430 false /*exactMatchRequiredForInputFlags*/)) {
5431 firstInexact = profile;
5432 }
5433
Eric Laurente552edb2014-03-10 17:42:56 -07005434 }
5435 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005436 if (firstInexact != nullptr) {
5437 samplingRate = updatedSamplingRate;
5438 format = updatedFormat;
5439 channelMask = updatedChannelMask;
5440 return firstInexact;
5441 }
Eric Laurente552edb2014-03-10 17:42:56 -07005442 return NULL;
5443}
5444
Francois Gaffie716e1432019-01-14 16:58:59 +01005445sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5446 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005447{
Eric Laurent97ac8712018-07-27 18:59:02 -07005448 // Honor explicit routing requests only if all active clients have a preferred route in which
5449 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005450 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005451 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005452 if (device != nullptr) {
5453 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005454 }
5455
François Gaffie11d30102018-11-02 16:09:09 +01005456 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005457 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005458 policyMix);
5459 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005460 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005461}
5462
Francois Gaffie716e1432019-01-14 16:58:59 +01005463sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005464{
Francois Gaffie716e1432019-01-14 16:58:59 +01005465 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5466 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5467 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5468 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005469 String8(attributes.tags + strlen("addr=")),
5470 AUDIO_FORMAT_DEFAULT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005471 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005472 return mAvailableInputDevices.getDevice(device, String8(), AUDIO_FORMAT_DEFAULT);
Eric Laurente552edb2014-03-10 17:42:56 -07005473}
5474
Eric Laurente0720872014-03-11 09:30:41 -07005475float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005476 int index,
5477 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005478{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005479 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005480
5481 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5482 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5483 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5484 // the ringtone volume
5485 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5486 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5487 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5488 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5489 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5490 }
5491
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005492 // in-call: always cap volume by voice volume + some low headroom
5493 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005494 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005495 switch (stream) {
5496 case AUDIO_STREAM_SYSTEM:
5497 case AUDIO_STREAM_RING:
5498 case AUDIO_STREAM_MUSIC:
5499 case AUDIO_STREAM_ALARM:
5500 case AUDIO_STREAM_NOTIFICATION:
5501 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5502 case AUDIO_STREAM_DTMF:
5503 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005504 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005505 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005506 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005507 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005508 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005509 if (volumeDB > maxVoiceVolDb) {
5510 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5511 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5512 volumeDB = maxVoiceVolDb;
5513 }
5514 } break;
5515 default:
5516 break;
5517 }
5518 }
5519
Eric Laurente552edb2014-03-10 17:42:56 -07005520 // if a headset is connected, apply the following rules to ring tones and notifications
5521 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005522 // - always attenuate notifications volume by 6dB
5523 // - attenuate ring tones volume by 6dB unless music is not playing and
5524 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005525 // - if music is playing, always limit the volume to current music volume,
5526 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005527 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005528 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5529 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5530 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005531 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005532 AUDIO_DEVICE_OUT_USB_HEADSET |
5533 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005534 ((stream_strategy == STRATEGY_SONIFICATION)
5535 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005536 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005537 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005538 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005539 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005540 // when the phone is ringing we must consider that music could have been paused just before
5541 // by the music application and behave as if music was active if the last music track was
5542 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005543 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005544 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005545 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005546 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005547 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005548 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5549 musicDevice),
5550 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005551 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5552 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005553 if (volumeDB > minVolDB) {
5554 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005555 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005556 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005557 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5558 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5559 // on A2DP, also ensure notification volume is not too low compared to media when
5560 // intended to be played
5561 if ((volumeDB > -96.0f) &&
5562 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5563 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5564 stream, device,
5565 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5566 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5567 }
5568 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005569 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5570 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005571 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005572 }
5573 }
5574
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005575 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005576}
5577
Eric Laurent3839bc02018-07-10 18:33:34 -07005578int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5579 audio_stream_type_t srcStream,
5580 audio_stream_type_t dstStream)
5581{
5582 if (srcStream == dstStream) {
5583 return srcIndex;
5584 }
5585 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5586 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5587 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5588 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5589
5590 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5591}
5592
Eric Laurente0720872014-03-11 09:30:41 -07005593status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005594 int index,
5595 const sp<AudioOutputDescriptor>& outputDesc,
5596 audio_devices_t device,
5597 int delayMs,
5598 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005599{
Eric Laurente552edb2014-03-10 17:42:56 -07005600 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005601 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005602 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005603 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005604 return NO_ERROR;
5605 }
François Gaffie2110e042015-03-24 08:41:51 +01005606 audio_policy_forced_cfg_t forceUseForComm =
5607 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005608 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005609 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5610 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005611 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005612 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005613 return INVALID_OPERATION;
5614 }
5615
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005617 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005618 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005619
Eric Laurentffbc80f2015-03-18 18:30:19 -07005620 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005621 if (outputDesc->isFixedVolume(device) ||
5622 // Force VoIP volume to max for bluetooth SCO
5623 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5624 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005625 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005626 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005627
Eric Laurentffbc80f2015-03-18 18:30:19 -07005628 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005629
Eric Laurent3b73df72014-03-11 09:06:29 -07005630 if (stream == AUDIO_STREAM_VOICE_CALL ||
5631 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005632 float voiceVolume;
5633 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005634 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005635 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005636 } else {
5637 voiceVolume = 1.0;
5638 }
5639
Eric Laurent18fba842016-03-31 14:41:26 -07005640 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005641 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5642 mLastVoiceVolume = voiceVolume;
5643 }
5644 }
5645
5646 return NO_ERROR;
5647}
5648
Eric Laurentc75307b2015-03-17 15:29:32 -07005649void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5650 audio_devices_t device,
5651 int delayMs,
5652 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005653{
Eric Laurentc75307b2015-03-17 15:29:32 -07005654 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005655
Eric Laurent794fde22016-03-11 09:50:45 -08005656 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005657 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005658 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005659 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005660 device,
5661 delayMs,
5662 force);
5663 }
5664}
5665
Eric Laurente0720872014-03-11 09:30:41 -07005666void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005667 bool on,
5668 const sp<AudioOutputDescriptor>& outputDesc,
5669 int delayMs,
5670 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005671{
Eric Laurent72249d52015-06-08 11:12:15 -07005672 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5673 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005674 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005675 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005676 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005677 }
5678 }
5679}
5680
Eric Laurente0720872014-03-11 09:30:41 -07005681void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005682 bool on,
5683 const sp<AudioOutputDescriptor>& outputDesc,
5684 int delayMs,
5685 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005686{
Eric Laurente552edb2014-03-10 17:42:56 -07005687 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005688 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005689 }
5690
Eric Laurentc75307b2015-03-17 15:29:32 -07005691 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5692 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005693
5694 if (on) {
5695 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005696 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005697 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005698 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005699 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005700 }
5701 }
5702 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5703 outputDesc->mMuteCount[stream]++;
5704 } else {
5705 if (outputDesc->mMuteCount[stream] == 0) {
5706 ALOGV("setStreamMute() unmuting non muted stream!");
5707 return;
5708 }
5709 if (--outputDesc->mMuteCount[stream] == 0) {
5710 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005711 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005712 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005713 device,
5714 delayMs);
5715 }
5716 }
5717}
5718
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005719audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5720{
5721 // flags to stream type mapping
5722 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5723 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5724 }
5725 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5726 return AUDIO_STREAM_BLUETOOTH_SCO;
5727 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005728 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5729 return AUDIO_STREAM_TTS;
5730 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005731
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005732 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005733}
Eric Laurente83b55d2014-11-14 10:06:21 -08005734
François Gaffie53615e22015-03-19 09:24:12 +01005735bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5736{
Eric Laurente83b55d2014-11-14 10:06:21 -08005737 // has flags that map to a strategy?
5738 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5739 return true;
5740 }
5741
5742 // has known usage?
5743 switch (paa->usage) {
5744 case AUDIO_USAGE_UNKNOWN:
5745 case AUDIO_USAGE_MEDIA:
5746 case AUDIO_USAGE_VOICE_COMMUNICATION:
5747 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5748 case AUDIO_USAGE_ALARM:
5749 case AUDIO_USAGE_NOTIFICATION:
5750 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5751 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5752 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5753 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5754 case AUDIO_USAGE_NOTIFICATION_EVENT:
5755 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5756 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5757 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5758 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005759 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005760 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005761 break;
5762 default:
5763 return false;
5764 }
5765 return true;
5766}
5767
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005768bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005769 routing_strategy strategy, uint32_t inPastMs,
5770 nsecs_t sysTime) const
5771{
5772 if ((sysTime == 0) && (inPastMs != 0)) {
5773 sysTime = systemTime();
5774 }
Eric Laurent794fde22016-03-11 09:50:45 -08005775 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005776 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005777 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005778 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5779 return true;
5780 }
5781 }
5782 return false;
5783}
5784
François Gaffie11d30102018-11-02 16:09:09 +01005785bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5786 routing_strategy strategy, uint32_t inPastMs,
5787 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005788{
5789 for (size_t i = 0; i < mOutputs.size(); i++) {
5790 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5791 if (outputDesc->sharesHwModuleWith(desc)
5792 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5793 return true;
5794 }
5795 }
5796 return false;
5797}
5798
François Gaffie2110e042015-03-24 08:41:51 +01005799audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5800{
5801 return mEngine->getForceUse(usage);
5802}
5803
5804bool AudioPolicyManager::isInCall()
5805{
5806 return isStateInCall(mEngine->getPhoneState());
5807}
5808
5809bool AudioPolicyManager::isStateInCall(int state)
5810{
5811 return is_state_in_call(state);
5812}
5813
Eric Laurentd60560a2015-04-10 11:31:20 -07005814void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5815{
5816 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005817 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5818 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5819 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5820 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005821 }
5822 }
5823
5824 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5825 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5826 bool release = false;
5827 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5828 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5829 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5830 source->ext.device.type == deviceDesc->type()) {
5831 release = true;
5832 }
5833 }
5834 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5835 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5836 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5837 sink->ext.device.type == deviceDesc->type()) {
5838 release = true;
5839 }
5840 }
5841 if (release) {
5842 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5843 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5844 }
5845 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005846
5847 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005848}
5849
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005850void AudioPolicyManager::modifySurroundFormats(
5851 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005852 std::unordered_set<audio_format_t> enforcedSurround(
5853 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005854 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5855 for (const auto& pair : mConfig.getSurroundFormats()) {
5856 allSurround.insert(pair.first);
5857 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5858 }
Phil Burk09bc4612016-02-24 15:58:15 -08005859
5860 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5861 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005862 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005863 // This is the resulting set of formats depending on the surround mode:
5864 // 'all surround' = allSurround
5865 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5866 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5867 // 'manual surround' = mManualSurroundFormats
5868 // AUTO: formats v 'enforced surround'
5869 // ALWAYS: formats v 'all surround' v 'enforced surround'
5870 // NEVER: formats ^ 'non-surround'
5871 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005872
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005873 std::unordered_set<audio_format_t> formatSet;
5874 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5875 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005876 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005877 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005878 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005879 formatSet.insert(*formatIter);
5880 }
5881 }
5882 } else {
5883 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5884 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005885 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005886
jiabin81772902018-04-02 17:52:27 -07005887 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005888 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005889 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5890 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5891 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005892 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005893 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5894 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5895 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005896 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005897 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005898 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005899 for (const auto& format : formatSet) {
5900 formatsPtr->push(format);
5901 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005902}
5903
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005904void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005905 ChannelsVector &channelMasks = *channelMasksPtr;
5906 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5907 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5908
5909 // If NEVER, then remove support for channelMasks > stereo.
5910 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5911 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5912 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5913 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5914 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5915 channelMasks.removeAt(maskIndex);
5916 } else {
5917 maskIndex++;
5918 }
5919 }
jiabin81772902018-04-02 17:52:27 -07005920 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5921 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5922 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005923 bool supports5dot1 = false;
5924 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005925 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005926 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5927 supports5dot1 = true;
5928 break;
5929 }
5930 }
5931 // If not then add 5.1 support.
5932 if (!supports5dot1) {
5933 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005934 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005935 }
Phil Burk09bc4612016-02-24 15:58:15 -08005936 }
5937}
5938
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005939void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005940 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005941 AudioProfileVector &profiles)
5942{
5943 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005944 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005945
François Gaffie112b0af2015-11-19 16:13:25 +01005946 // Format MUST be checked first to update the list of AudioProfile
5947 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005948 reply = mpClientInterface->getParameters(
5949 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005950 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005951 AudioParameter repliedParameters(reply);
5952 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005953 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005954 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5955 return;
5956 }
Phil Burk09bc4612016-02-24 15:58:15 -08005957 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005958 if (device == AUDIO_DEVICE_OUT_HDMI
5959 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005960 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005961 }
Phil Burk09bc4612016-02-24 15:58:15 -08005962 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005963 }
François Gaffie112b0af2015-11-19 16:13:25 +01005964
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005965 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005966 ChannelsVector channelMasks;
5967 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005968 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005969 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005970
5971 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005972 reply = mpClientInterface->getParameters(
5973 ioHandle,
5974 requestedParameters.toString() + ";" +
5975 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005976 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005977 AudioParameter repliedParameters(reply);
5978 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005979 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005980 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005981 }
5982 }
5983 if (profiles.hasDynamicChannelsFor(format)) {
5984 reply = mpClientInterface->getParameters(ioHandle,
5985 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005986 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005987 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005988 AudioParameter repliedParameters(reply);
5989 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005990 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005991 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005992 if (device == AUDIO_DEVICE_OUT_HDMI
5993 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005994 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005995 }
François Gaffie112b0af2015-11-19 16:13:25 +01005996 }
5997 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005998 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005999 }
6000}
Eric Laurentd60560a2015-04-10 11:31:20 -07006001
Mikhail Naganovdc769682018-05-04 15:34:08 -07006002status_t AudioPolicyManager::installPatch(const char *caller,
6003 audio_patch_handle_t *patchHandle,
6004 AudioIODescriptorInterface *ioDescriptor,
6005 const struct audio_patch *patch,
6006 int delayMs)
6007{
6008 ssize_t index = mAudioPatches.indexOfKey(
6009 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6010 *patchHandle : ioDescriptor->getPatchHandle());
6011 sp<AudioPatch> patchDesc;
6012 status_t status = installPatch(
6013 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6014 if (status == NO_ERROR) {
6015 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6016 }
6017 return status;
6018}
6019
6020status_t AudioPolicyManager::installPatch(const char *caller,
6021 ssize_t index,
6022 audio_patch_handle_t *patchHandle,
6023 const struct audio_patch *patch,
6024 int delayMs,
6025 uid_t uid,
6026 sp<AudioPatch> *patchDescPtr)
6027{
6028 sp<AudioPatch> patchDesc;
6029 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6030 if (index >= 0) {
6031 patchDesc = mAudioPatches.valueAt(index);
6032 afPatchHandle = patchDesc->mAfPatchHandle;
6033 }
6034
6035 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6036 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6037 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6038 if (status == NO_ERROR) {
6039 if (index < 0) {
6040 patchDesc = new AudioPatch(patch, uid);
6041 addAudioPatch(patchDesc->mHandle, patchDesc);
6042 } else {
6043 patchDesc->mPatch = *patch;
6044 }
6045 patchDesc->mAfPatchHandle = afPatchHandle;
6046 if (patchHandle) {
6047 *patchHandle = patchDesc->mHandle;
6048 }
6049 nextAudioPortGeneration();
6050 mpClientInterface->onAudioPatchListUpdate();
6051 }
6052 if (patchDescPtr) *patchDescPtr = patchDesc;
6053 return status;
6054}
6055
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006056} // namespace android