blob: 262ee8b8cfd673e42668997e1c18f131f1add0da [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
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800449status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
450 std::vector<audio_format_t> *formats)
451{
452 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
453 char *tok = NULL, *saveptr;
454 status_t status = NO_ERROR;
455 char encoding_formats_list[PROPERTY_VALUE_MAX];
456 audio_format_t format = AUDIO_FORMAT_DEFAULT;
457 // FIXME This list should not come from a property but the supported encoded
458 // formats of declared A2DP devices in primary module
459 property_get("persist.bluetooth.a2dp_offload.cap", encoding_formats_list, "");
460 tok = strtok_r(encoding_formats_list, "-", &saveptr);
461 for (;tok != NULL; tok = strtok_r(NULL, "-", &saveptr)) {
462 if (strcmp(tok, "sbc") == 0) {
463 ALOGV("%s: SBC offload supported\n",__func__);
464 format = AUDIO_FORMAT_SBC;
465 } else if (strcmp(tok, "aptx") == 0) {
466 ALOGV("%s: APTX offload supported\n",__func__);
467 format = AUDIO_FORMAT_APTX;
468 } else if (strcmp(tok, "aptxhd") == 0) {
469 ALOGV("%s: APTX HD offload supported\n",__func__);
470 format = AUDIO_FORMAT_APTX_HD;
471 } else if (strcmp(tok, "ldac") == 0) {
472 ALOGV("%s: LDAC offload supported\n",__func__);
473 format = AUDIO_FORMAT_LDAC;
474 } else if (strcmp(tok, "aac") == 0) {
475 ALOGV("%s: AAC offload supported\n",__func__);
476 format = AUDIO_FORMAT_AAC;
477 } else {
478 ALOGE("%s: undefined token - %s\n",__func__, tok);
479 continue;
480 }
481 formats->push_back(format);
482 }
483 return status;
484}
485
François Gaffie11d30102018-11-02 16:09:09 +0100486uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487{
488 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100489 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700490 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700491
François Gaffie11d30102018-11-02 16:09:09 +0100492 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700493 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700494 }
François Gaffie11d30102018-11-02 16:09:09 +0100495 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
496
Francois Gaffie716e1432019-01-14 16:58:59 +0100497 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffie9eb18552018-11-05 10:33:26 +0100498 auto txSourceDevice = getDeviceAndMixForAttributes(attr);
499 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffie11d30102018-11-02 16:09:09 +0100500 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100501 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700502
503 // release existing RX patch if any
504 if (mCallRxPatch != 0) {
505 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
506 mCallRxPatch.clear();
507 }
508 // release TX patch if any
509 if (mCallTxPatch != 0) {
510 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
511 mCallTxPatch.clear();
512 }
513
François Gaffie9eb18552018-11-05 10:33:26 +0100514 auto telephonyRxModule =
515 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
516 auto telephonyTxModule =
517 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
518 // retrieve Rx Source and Tx Sink device descriptors
519 sp<DeviceDescriptor> rxSourceDevice =
520 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
521 String8(),
522 AUDIO_FORMAT_DEFAULT);
523 sp<DeviceDescriptor> txSinkDevice =
524 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
525 String8(),
526 AUDIO_FORMAT_DEFAULT);
527
528 // RX and TX Telephony device are declared by Primary Audio HAL
529 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
530 (telephonyRxModule->getHalVersionMajor() >= 3)) {
531 if (rxSourceDevice == 0 || txSinkDevice == 0) {
532 // RX / TX Telephony device(s) is(are) not currently available
533 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
534 return muteWaitMs;
535 }
536 // do not create a patch (aka Sw Bridging) if Primary HW module has declared supporting a
537 // route between telephony RX to Sink device and Source device to telephony TX
538 const auto &primaryModule = telephonyRxModule;
539 createRxPatch = !primaryModule->supportsPatch(rxSourceDevice, rxDevices.itemAt(0));
540 createTxPatch = !primaryModule->supportsPatch(txSourceDevice, txSinkDevice);
541 } else {
542 // If the RX device is on the primary HW module, then use legacy routing method for
543 // voice calls via setOutputDevice() on primary output.
544 // Otherwise, create two audio patches for TX and RX path.
545 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
546 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 // If the TX device is also on the primary HW module, setOutputDevice() will take care
548 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100549 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
550 (txSinkDevice != 0);
551 }
552 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
553 // Otherwise, create two audio patches for TX and RX path.
554 if (!createRxPatch) {
555 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700556 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100557 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
François Gaffie9eb18552018-11-05 10:33:26 +0100558 ALOG_ASSERT(createTxPatch, "No Tx Patch will be created, nor legacy routing done");
Eric Laurentc2730ba2014-07-20 15:47:07 -0700559 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700560 if (createTxPatch) { // create TX path audio patch
François Gaffie9eb18552018-11-05 10:33:26 +0100561 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800562 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700563
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800564 return muteWaitMs;
565}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700566
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800567sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100568 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700569 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700570
François Gaffie11d30102018-11-02 16:09:09 +0100571 if (device == nullptr) {
572 return nullptr;
573 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800574 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100575 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800576 addSource(mAvailableInputDevices.getDevice(
577 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800578 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100579 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800580 addSink(mAvailableOutputDevices.getDevice(
581 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800582 }
583
François Gaffie11d30102018-11-02 16:09:09 +0100584 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
585 const sp<DeviceDescriptor> outputDevice = isRx ?
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800586 device : mAvailableOutputDevices.getDevice(
587 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100588 SortedVector<audio_io_handle_t> outputs =
589 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
590 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800591 // request to reuse existing output stream if one is already opened to reach the target device
592 if (output != AUDIO_IO_HANDLE_NONE) {
593 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100594 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
595 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700596 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800597 }
598
599 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700600 // terminate active capture if on the same HW module as the call TX source device
601 // FIXME: would be better to refine to only inputs whose profile connects to the
602 // call TX device but this information is not in the audio patch and logic here must be
603 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800604 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100605 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700606 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700607 }
608 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 }
Eric Laurentdc462862016-07-19 12:29:53 -0700610
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800611 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700612 status_t status = mpClientInterface->createAudioPatch(
613 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800614 ALOGW_IF(status != NO_ERROR,
615 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
616 sp<AudioPatch> audioPatch;
617 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700618 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800619 audioPatch->mAfPatchHandle = afPatchHandle;
620 audioPatch->mUid = mUidCached;
621 }
622 return audioPatch;
623}
624
Mikhail Naganovdc769682018-05-04 15:34:08 -0700625sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100626 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700627 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800628 ALOG_ASSERT(!deviceList.isEmpty(),
629 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700630 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700631}
632
Mikhail Naganov100f0122018-11-29 11:22:16 -0800633audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
634 const DeviceVector& devices, const char *moduleId) const {
635 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
636 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
637}
638
639bool AudioPolicyManager::isDeviceOfModule(
640 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
641 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
642 if (module != 0) {
643 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
644 .indexOf(devDesc) != NAME_NOT_FOUND
645 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
646 .indexOf(devDesc) != NAME_NOT_FOUND;
647 }
648 return false;
649}
650
Eric Laurente0720872014-03-11 09:30:41 -0700651void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700652{
653 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100654 // store previous phone state for management of sonification strategy below
655 int oldState = mEngine->getPhoneState();
656
657 if (mEngine->setPhoneState(state) != NO_ERROR) {
658 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700659 return;
660 }
François Gaffie2110e042015-03-24 08:41:51 +0100661 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700662 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700663 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700664 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800665 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700666 }
667
François Gaffie2110e042015-03-24 08:41:51 +0100668 /**
669 * Switching to or from incall state or switching between telephony and VoIP lead to force
670 * routing command.
671 */
672 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
673 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700674
675 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700676 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700677
Eric Laurente552edb2014-03-10 17:42:56 -0700678 int delayMs = 0;
679 if (isStateInCall(state)) {
680 nsecs_t sysTime = systemTime();
681 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700682 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700683 // mute media and sonification strategies and delay device switch by the largest
684 // latency of any output where either strategy is active.
685 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100686 if ((isStrategyActive(desc, STRATEGY_MEDIA,
687 SONIFICATION_HEADSET_MUSIC_DELAY,
688 sysTime) ||
689 isStrategyActive(desc, STRATEGY_SONIFICATION,
690 SONIFICATION_HEADSET_MUSIC_DELAY,
691 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700692 (delayMs < (int)desc->latency()*2)) {
693 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700695 setStrategyMute(STRATEGY_MEDIA, true, desc);
696 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700697 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700698 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
699 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700700 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
701 }
702 }
703
Eric Laurent87ffa392015-05-22 10:32:38 -0700704 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100705 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700706 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100707 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700708 // force routing command to audio hardware when ending call
709 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100710 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
711 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700712 }
Eric Laurente552edb2014-03-10 17:42:56 -0700713
Eric Laurent87ffa392015-05-22 10:32:38 -0700714 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100715 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700716 } else if (oldState == AUDIO_MODE_IN_CALL) {
717 if (mCallRxPatch != 0) {
718 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
719 mCallRxPatch.clear();
720 }
721 if (mCallTxPatch != 0) {
722 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
723 mCallTxPatch.clear();
724 }
François Gaffie11d30102018-11-02 16:09:09 +0100725 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700726 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100727 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700729 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700730
731 // reevaluate routing on all outputs in case tracks have been started during the call
732 for (size_t i = 0; i < mOutputs.size(); i++) {
733 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100734 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700735 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100736 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700737 }
738 }
739
Eric Laurente552edb2014-03-10 17:42:56 -0700740 if (isStateInCall(state)) {
741 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700742 // force reevaluating accessibility routing when call starts
743 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700744 }
745
746 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700747 if (state == AUDIO_MODE_RINGTONE &&
748 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700749 mLimitRingtoneVolume = true;
750 } else {
751 mLimitRingtoneVolume = false;
752 }
753}
754
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700755audio_mode_t AudioPolicyManager::getPhoneState() {
756 return mEngine->getPhoneState();
757}
758
Eric Laurente0720872014-03-11 09:30:41 -0700759void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100760 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700761{
François Gaffie2110e042015-03-24 08:41:51 +0100762 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700763 if (config == mEngine->getForceUse(usage)) {
764 return;
765 }
Eric Laurente552edb2014-03-10 17:42:56 -0700766
François Gaffie2110e042015-03-24 08:41:51 +0100767 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
768 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
769 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700770 }
François Gaffie2110e042015-03-24 08:41:51 +0100771 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
772 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
773 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700774
775 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700776 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800777
Eric Laurentdc462862016-07-19 12:29:53 -0700778 //FIXME: workaround for truncated touch sounds
779 // to be removed when the problem is handled by system UI
780 uint32_t delayMs = 0;
781 uint32_t waitMs = 0;
782 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
783 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
784 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700785 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100786 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
787 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700788 }
Eric Laurente552edb2014-03-10 17:42:56 -0700789 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700790 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100791 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700792 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100793 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700794 }
François Gaffie11d30102018-11-02 16:09:09 +0100795 if (forceVolumeReeval && !newDevices.isEmpty()) {
796 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700797 }
798 }
799
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800800 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100801 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700802 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100803 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800804 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700805 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800806 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700807 }
Eric Laurente552edb2014-03-10 17:42:56 -0700808 }
Eric Laurente552edb2014-03-10 17:42:56 -0700809}
810
Eric Laurente0720872014-03-11 09:30:41 -0700811void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700812{
813 ALOGV("setSystemProperty() property %s, value %s", property, value);
814}
815
Michael Chana94fbb22018-04-24 14:31:19 +1000816// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
817// search to profiles for direct outputs.
818sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100819 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000820 uint32_t samplingRate,
821 audio_format_t format,
822 audio_channel_mask_t channelMask,
823 audio_output_flags_t flags,
824 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700825{
Michael Chana94fbb22018-04-24 14:31:19 +1000826 if (directOnly) {
827 // only retain flags that will drive the direct output profile selection
828 // if explicitly requested
829 static const uint32_t kRelevantFlags =
830 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
831 AUDIO_OUTPUT_FLAG_VOIP_RX);
832 flags =
833 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
834 }
Eric Laurent861a6282015-05-18 15:40:16 -0700835
836 sp<IOProfile> profile;
837
Mikhail Naganovd4120142017-12-06 15:49:22 -0800838 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800839 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100840 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700841 samplingRate, NULL /*updatedSamplingRate*/,
842 format, NULL /*updatedFormat*/,
843 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700844 flags)) {
845 continue;
846 }
847 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100848 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700849 continue;
850 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800851 // reject profiles if connected device does not support codec
852 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
853 continue;
854 }
Michael Chana94fbb22018-04-24 14:31:19 +1000855 if (!directOnly) return curProfile;
856 // when searching for direct outputs, if several profiles are compatible, give priority
857 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100858 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700859 continue;
860 }
861 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100862 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700863 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700864 }
Eric Laurente552edb2014-03-10 17:42:56 -0700865 }
866 }
Eric Laurent861a6282015-05-18 15:40:16 -0700867 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700868}
869
Eric Laurentf4e63452017-11-06 19:31:46 +0000870audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700871{
Eric Laurent3b73df72014-03-11 09:06:29 -0700872 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100873 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800874
875 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
876 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
877 // format, flags, etc. This may result in some discrepancy for functions that utilize
878 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
879 // and AudioSystem::getOutputSamplingRate().
880
François Gaffie11d30102018-11-02 16:09:09 +0100881 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
882 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700883
François Gaffie11d30102018-11-02 16:09:09 +0100884 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
885 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000886 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700887}
888
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700889status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
890 const audio_attributes_t *srcAttr,
891 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700892{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700893 if (srcAttr != NULL) {
894 if (!isValidAttributes(srcAttr)) {
895 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
896 __func__,
897 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
898 srcAttr->tags);
899 return BAD_VALUE;
900 }
901 *dstAttr = *srcAttr;
902 } else {
903 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
904 ALOGE("%s: invalid stream type", __func__);
905 return BAD_VALUE;
906 }
907 stream_type_to_audio_attributes(srcStream, dstAttr);
908 }
909 return NO_ERROR;
910}
911
912status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
913 audio_io_handle_t *output,
914 audio_session_t session,
915 const audio_attributes_t *attr,
916 audio_stream_type_t *stream,
917 uid_t uid,
918 const audio_config_t *config,
919 audio_output_flags_t *flags,
920 audio_port_handle_t *selectedDeviceId)
921{
François Gaffie11d30102018-11-02 16:09:09 +0100922 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700923 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100924 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Francois Gaffie716e1432019-01-14 16:58:59 +0100925 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100926 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700927
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700928 status_t status = getAudioAttributes(resultAttr, attr, *stream);
929 if (status != NO_ERROR) {
930 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700931 }
932
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700933 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700934 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700935 __func__,
936 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Francois Gaffie716e1432019-01-14 16:58:59 +0100937 session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700938
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700939 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700940
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700941 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700942
Scott Randolph7b1fd232018-06-18 15:33:03 -0700943 // First check for explicit routing (eg. setPreferredDevice)
Francois Gaffie716e1432019-01-14 16:58:59 +0100944 sp<DeviceDescriptor> requestedDevice = mAvailableOutputDevices.getDeviceFromId(requestedPortId);
945 if (requestedDevice != nullptr) {
946 deviceType = requestedDevice->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700947 } else {
948 // If no explict route, is there a matching dynamic policy that applies?
949 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700950 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700951 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
952 if (!audio_has_proportional_frames(config->format)) {
953 return BAD_VALUE;
954 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700955 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700956 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700957 AudioMix *mix = desc->mPolicyMix;
958 sp<DeviceDescriptor> deviceDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800959 mAvailableOutputDevices.getDevice(
960 mix->mDeviceType, mix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -0700961 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700962 ALOGV("%s returns output %d", __func__, *output);
963 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700964 }
965
966 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700967 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
968 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700969 return BAD_VALUE;
970 }
François Gaffie11d30102018-11-02 16:09:09 +0100971 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700972 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700973
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700974 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200975 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700976 }
977
Nadav Barb2f18162018-07-18 13:01:53 +0300978 // Set incall music only if device was explicitly set, and fallback to the device which is
979 // chosen by the engine if not.
980 // FIXME: provide a more generic approach which is not device specific and move this back
981 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200982 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100983 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700984 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300985 audio_is_linear_pcm(config->format) &&
986 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100987 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300988 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
989 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700990 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100991 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300992 }
993 }
994
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700995 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800996 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +0100997 __func__,
998 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700999
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001000 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001001 if (!msdDevices.isEmpty()) {
1002 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001003 sp<DeviceDescriptor> deviceDesc =
1004 mAvailableOutputDevices.getDevice(deviceType, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01001005 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
1006 ALOGV("%s() Using MSD devices %s instead of device %s",
1007 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
1008 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001009 } else {
1010 *output = AUDIO_IO_HANDLE_NONE;
1011 }
1012 }
François Gaffie11d30102018-11-02 16:09:09 +01001013 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001014 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01001015 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001016 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001017 if (*output == AUDIO_IO_HANDLE_NONE) {
1018 return INVALID_OPERATION;
1019 }
Paul McLeanaa981192015-03-21 09:55:15 -07001020
François Gaffie11d30102018-11-02 16:09:09 +01001021 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001022
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001023 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1024
1025 return NO_ERROR;
1026}
1027
1028status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1029 audio_io_handle_t *output,
1030 audio_session_t session,
1031 audio_stream_type_t *stream,
1032 uid_t uid,
1033 const audio_config_t *config,
1034 audio_output_flags_t *flags,
1035 audio_port_handle_t *selectedDeviceId,
1036 audio_port_handle_t *portId)
1037{
1038 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1039 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1040 return INVALID_OPERATION;
1041 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001042 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001043 audio_attributes_t resultAttr;
1044 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1045 config, flags, selectedDeviceId);
1046 if (status != NO_ERROR) {
1047 return status;
1048 }
1049
Eric Laurent8fc147b2018-07-22 19:13:55 -07001050 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1051 .format = config->format,
1052 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001053 *portId = AudioPort::getNextUniqueId();
1054
Eric Laurent8fc147b2018-07-22 19:13:55 -07001055 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001056 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +01001057 requestedPortId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001058 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -07001059 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001060 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001061 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001062
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001063 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
Francois Gaffie716e1432019-01-14 16:58:59 +01001064 __func__, *output, requestedPortId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001065
Eric Laurente83b55d2014-11-14 10:06:21 -08001066 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001067}
1068
François Gaffie11d30102018-11-02 16:09:09 +01001069audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1070 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001071 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001072 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001073 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001074 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001075{
Andy Hungc88b0642018-04-27 15:42:35 -07001076 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001077 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001078
Eric Laurente552edb2014-03-10 17:42:56 -07001079 // open a direct output if required by specified parameters
1080 //force direct flag if offload flag is set: offloading implies a direct output stream
1081 // and all common behaviors are driven by checking only the direct flag
1082 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001083 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1084 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
Nadav Bar766fb022018-01-07 12:18:03 +02001086 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1087 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001088 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001089 // only allow deep buffering for music stream type
1090 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001091 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001092 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001093 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001094 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1095 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001096 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001097 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001098 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001099 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001100 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001101 audio_is_linear_pcm(config->format) &&
1102 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001103 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001104 AUDIO_OUTPUT_FLAG_DIRECT);
1105 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001106 }
Eric Laurente552edb2014-03-10 17:42:56 -07001107
Nadav Bar766fb022018-01-07 12:18:03 +02001108
Eric Laurentb732cf52014-09-24 19:08:21 -07001109 sp<IOProfile> profile;
1110
1111 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001112 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001113 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001114 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1115 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001116 goto non_direct_output;
1117 }
1118
Andy Hung2ddee192015-12-18 17:34:44 -08001119 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1120 // This prevents creating an offloaded track and tearing it down immediately after start
1121 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001122 // FIXME: We should check the audio session here but we do not have it in this context.
1123 // This may prevent offloading in rare situations where effects are left active by apps
1124 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001125
Nadav Bar766fb022018-01-07 12:18:03 +02001126 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001127 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001128 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001129 config->sample_rate,
1130 config->format,
1131 config->channel_mask,
1132 (audio_output_flags_t)*flags,
1133 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001134 }
1135
Eric Laurent1c333e22014-05-20 10:48:17 -07001136 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001137 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1138 for (size_t i = 0; i < mOutputs.size(); i++) {
1139 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1140 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1141 // reuse direct output if currently open by the same client
1142 // and configured with same parameters
1143 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001144 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001145 (config->channel_mask == desc->mChannelMask) &&
1146 (session == desc->mDirectClientSession)) {
1147 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001148 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001149 mOutputs.keyAt(i), session);
1150 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001151 }
1152 }
1153 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001154
1155 if (!profile->canOpenNewIo()) {
1156 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001157 }
Eric Laurent861a6282015-05-18 15:40:16 -07001158
Eric Laurent3974e3b2017-12-07 17:58:43 -08001159 sp<SwAudioOutputDescriptor> outputDesc =
1160 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001161
François Gaffie11d30102018-11-02 16:09:09 +01001162 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001163
Dean Wheatley3023b382018-08-09 07:42:40 +10001164 // MSD patch may be using the only output stream that can service this request. Release
1165 // MSD patch to prioritize this request over any active output on MSD.
1166 AudioPatchCollection msdPatches = getMsdPatches();
1167 for (size_t i = 0; i < msdPatches.size(); i++) {
1168 const auto& patch = msdPatches[i];
1169 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1170 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1171 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001172 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001173 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1174 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1175 releaseAudioPatch(patch->mHandle, mUidCached);
1176 break;
1177 }
1178 }
1179 }
1180
François Gaffie11d30102018-11-02 16:09:09 +01001181 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001182
1183 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001184 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001185 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001186 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001187 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001188 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1189 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001190 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1191 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001192 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001193 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001194 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001195 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001196 if (audio_is_linear_pcm(config->format) &&
1197 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001198 goto non_direct_output;
1199 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001200 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001201 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001202 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001203 outputDesc->mDirectClientSession = session;
1204
Eric Laurente552edb2014-03-10 17:42:56 -07001205 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001206 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001207 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001208 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001209 return output;
1210 }
1211
Eric Laurentb732cf52014-09-24 19:08:21 -07001212non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001213
1214 // A request for HW A/V sync cannot fallback to a mixed output because time
1215 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001216 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001217 return AUDIO_IO_HANDLE_NONE;
1218 }
1219
Eric Laurente552edb2014-03-10 17:42:56 -07001220 // ignoring channel mask due to downmix capability in mixer
1221
1222 // open a non direct output
1223
1224 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001225 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001226 // get which output is suitable for the specified stream. The actual
1227 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001228 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001229
Eric Laurent8838a382014-09-08 16:44:28 -07001230 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001231 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001232 output = selectOutput(outputs, *flags, config->format,
1233 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001234 }
François Gaffie11d30102018-11-02 16:09:09 +01001235 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001236 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001237 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001238
Eric Laurente552edb2014-03-10 17:42:56 -07001239 return output;
1240}
1241
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001242sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001243 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1244 mAvailableInputDevices);
1245 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1246}
1247
1248DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1249 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1250 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001251}
1252
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001253const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1254 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001255 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1256 if (msdModule != 0) {
1257 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1258 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1259 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1260 const struct audio_port_config *source = &patch->mPatch.sources[j];
1261 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1262 source->ext.device.hw_module == msdModule->getHandle()) {
1263 msdPatches.addAudioPatch(patch->mHandle, patch);
1264 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001265 }
1266 }
1267 }
1268 return msdPatches;
1269}
1270
François Gaffie11d30102018-11-02 16:09:09 +01001271status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001272 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1273{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001274 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001275 if (msdModule == nullptr) {
1276 ALOGE("%s() unable to get MSD module", __func__);
1277 return NO_INIT;
1278 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001279 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001280 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001281 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001282 return NO_INIT;
1283 }
1284 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1285 if (inputProfiles.isEmpty()) {
1286 ALOGE("%s() no input profiles for MSD module", __func__);
1287 return NO_INIT;
1288 }
1289 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1290 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001291 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001292 return NO_INIT;
1293 }
1294 AudioProfileVector msdProfiles;
1295 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1296 for (const auto &inProfile : inputProfiles) {
1297 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1298 msdProfiles.appendVector(inProfile->getAudioProfiles());
1299 }
1300 }
1301 AudioProfileVector deviceProfiles;
1302 for (const auto &outProfile : outputProfiles) {
1303 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1304 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1305 }
1306 }
1307 struct audio_config_base bestSinkConfig;
1308 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1309 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1310 &bestSinkConfig);
1311 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001312 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1313 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001314 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001315 }
1316 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1317 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1318 sinkConfig->format = bestSinkConfig.format;
1319 // For encoded streams force direct flag to prevent downstream mixing.
1320 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1321 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1322 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1323 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1324 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1325 sourceConfig->format = bestSinkConfig.format;
1326 // Copy input stream directly without any processing (e.g. resampling).
1327 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1328 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1329 if (hwAvSync) {
1330 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1331 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1332 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1333 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1334 }
1335 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1336 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1337 sinkConfig->config_mask |= config_mask;
1338 sourceConfig->config_mask |= config_mask;
1339 return NO_ERROR;
1340}
1341
François Gaffie11d30102018-11-02 16:09:09 +01001342PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001343{
1344 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001345 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1347 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1348 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1349 // For now, we just forcefully try with HwAvSync first.
1350 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1351 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1352 getBestMsdAudioProfileFor(
1353 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1354 if (res == NO_ERROR) {
1355 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1356 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1357 }
1358 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1359 " supporting PCM format conversion.", __func__);
1360 return patchBuilder;
1361}
1362
François Gaffie11d30102018-11-02 16:09:09 +01001363status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1364 sp<DeviceDescriptor> device = outputDevice;
1365 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001366 // Use media strategy for unspecified output device. This should only
1367 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1368 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001369 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1370 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1371 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001372 }
François Gaffie11d30102018-11-02 16:09:09 +01001373 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1374 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001375 const struct audio_patch* patch = patchBuilder.patch();
1376 const AudioPatchCollection msdPatches = getMsdPatches();
1377 if (!msdPatches.isEmpty()) {
1378 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1379 "The current MSD prototype only supports one output patch");
1380 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1381 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1382 return NO_ERROR;
1383 }
1384 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1385 }
1386 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1387 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1388 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1389 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001390 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1391 device->toString().c_str(), patch->sources[0].format,
1392 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001393 return status;
1394}
1395
Eric Laurente0720872014-03-11 09:30:41 -07001396audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001397 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001398 audio_format_t format,
1399 audio_channel_mask_t channelMask,
1400 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001401{
1402 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001403 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001404 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001405 // 1: the output supporting haptic playback when requesting haptic playback
1406 // 2: the output with the highest number of requested policy flags
1407 // 3: the output with the bit depth the closest to the requested one
1408 // 4: the primary output
1409 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001410
1411 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001412 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001413 }
1414 if (outputs.size() == 1) {
1415 return outputs[0];
1416 }
1417
1418 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001419 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1420 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001421 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1422 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1423 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001424 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1425 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001426
Eric Laurente78b6762018-12-19 16:29:01 -08001427 // Flags which must be present on both the request and the selected output
1428 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1429 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1430
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001431 for (audio_io_handle_t output : outputs) {
1432 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001433 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001434 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1435 continue;
1436 }
jiabin40573322018-11-08 12:08:02 -08001437 // If haptic channel is specified, use the haptic output if present.
1438 // When using haptic output, same audio format and sample rate are required.
1439 if (hapticChannelCount > 0) {
1440 // If haptic channel is specified, use the first output that
1441 // support haptic playback.
1442 if (audio_channel_count_from_out_mask(
1443 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1444 && format == outputDesc->mFormat
1445 && samplingRate == outputDesc->mSamplingRate) {
1446 return output;
1447 }
1448 } else {
1449 // When haptic channel is not specified, skip haptic output.
1450 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1451 continue;
1452 }
1453 }
Eric Laurente78b6762018-12-19 16:29:01 -08001454 if ((kMandatedFlags & flags) !=
1455 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1456 continue;
1457 }
jiabin40573322018-11-08 12:08:02 -08001458
Eric Laurent8838a382014-09-08 16:44:28 -07001459 // if a valid format is specified, skip output if not compatible
1460 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001461 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001462 continue;
1463 }
Eric Laurente6930022016-02-11 10:20:40 -08001464 if (AudioPort::isBetterFormatMatch(
1465 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001466 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001467 bestFormat = outputDesc->mFormat;
1468 }
Eric Laurent8838a382014-09-08 16:44:28 -07001469 }
1470
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001471 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001472 if (commonFlags >= maxCommonFlags) {
1473 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001474 if (format != AUDIO_FORMAT_INVALID
1475 && AudioPort::isBetterFormatMatch(
1476 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001477 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001478 bestFormatForFlags = outputDesc->mFormat;
1479 }
1480 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001481 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001482 maxCommonFlags = commonFlags;
1483 bestFormatForFlags = outputDesc->mFormat;
1484 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001485 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001486 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001487 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001488 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001489 }
1490 }
1491 }
1492
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001493 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001494 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001495 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001496 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001497 return outputForFormat;
1498 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001499 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001500 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001501 }
1502
1503 return outputs[0];
1504}
1505
Eric Laurent8fc147b2018-07-22 19:13:55 -07001506status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001507{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001508 ALOGV("%s portId %d", __FUNCTION__, portId);
1509
1510 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1511 if (outputDesc == 0) {
1512 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001513 return BAD_VALUE;
1514 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001515 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001516
Eric Laurent8fc147b2018-07-22 19:13:55 -07001517 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001518 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001519
Eric Laurent733ce942017-12-07 12:18:25 -08001520 status_t status = outputDesc->start();
1521 if (status != NO_ERROR) {
1522 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001523 }
1524
Eric Laurent97ac8712018-07-27 18:59:02 -07001525 uint32_t delayMs;
1526 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001527
1528 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001529 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001530 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001531 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001532 if (delayMs != 0) {
1533 usleep(delayMs * 1000);
1534 }
1535
1536 return status;
1537}
1538
Eric Laurent97ac8712018-07-27 18:59:02 -07001539status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1540 const sp<TrackClientDescriptor>& client,
1541 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001542{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001543 // cannot start playback of STREAM_TTS if any other output is being used
1544 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001545
1546 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001547 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001548 if (stream == AUDIO_STREAM_TTS) {
1549 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001550 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001551 return INVALID_OPERATION;
1552 } else {
1553 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1554 }
1555 } else {
1556 // some playback other than beacon starts
1557 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1558 }
1559
Eric Laurent77305a62016-07-25 16:39:22 -07001560 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001561 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001562 bool force = !outputDesc->isActive() &&
1563 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001564
François Gaffie11d30102018-11-02 16:09:09 +01001565 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001566 AudioMix *policyMix = NULL;
1567 const char *address = NULL;
1568 if (outputDesc->mPolicyMix != NULL) {
1569 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001570 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001571 address = policyMix->mDeviceAddress.string();
1572 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001573 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001574 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001575 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001576 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001577 devices.add(mAvailableOutputDevices.getDevice(newDeviceType,
1578 String8(address), AUDIO_FORMAT_DEFAULT));
Eric Laurent97ac8712018-07-27 18:59:02 -07001579 }
1580
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001581 // requiresMuteCheck is false when we can bypass mute strategy.
1582 // It covers a common case when there is no materially active audio
1583 // and muting would result in unnecessary delay and dropped audio.
1584 const uint32_t outputLatencyMs = outputDesc->latency();
1585 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1586
Eric Laurente552edb2014-03-10 17:42:56 -07001587 // increment usage count for this stream on the requested output:
1588 // NOTE that the usage count is the same for duplicated output and hardware output which is
1589 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001590 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001591
1592 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001593 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1594 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001595 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1596 }
1597 }
Eric Laurente552edb2014-03-10 17:42:56 -07001598
Eric Laurent36829f92017-04-07 19:04:42 -07001599 if (stream == AUDIO_STREAM_MUSIC) {
1600 selectOutputForMusicEffects();
1601 }
1602
François Gaffie11d30102018-11-02 16:09:09 +01001603 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001604 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001605 if (devices.isEmpty()) {
1606 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001607 }
Eric Laurent36829f92017-04-07 19:04:42 -07001608
Eric Laurente552edb2014-03-10 17:42:56 -07001609 routing_strategy strategy = getStrategy(stream);
1610 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001611 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1612 (beaconMuteLatency > 0);
1613 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001614 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001615 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001616 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001617 // An output has a shared device if
1618 // - managed by the same hw module
1619 // - supports the currently selected device
1620 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001621 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001622
Eric Laurent77305a62016-07-25 16:39:22 -07001623 // force a device change if any other output is:
1624 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001625 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001626 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001627 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001628 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001629 // change the device currently selected by the other output.
1630 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001631 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001632 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001633 force = true;
1634 }
1635 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001636 // a notification so that audio focus effect can propagate, or that a mute/unmute
1637 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001638 const uint32_t latencyMs = desc->latency();
1639 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1640
1641 if (shouldWait && isActive && (waitMs < latencyMs)) {
1642 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001643 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001644
1645 // Require mute check if another output is on a shared device
1646 // and currently active to have proper drain and avoid pops.
1647 // Note restoring AudioTracks onto this output needs to invoke
1648 // a volume ramp if there is no mute.
1649 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001650 }
1651 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001652
1653 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001654 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001655
Eric Laurente552edb2014-03-10 17:42:56 -07001656 // apply volume rules for current stream and device if necessary
1657 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001658 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001659 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001660 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001661
1662 // update the outputs if starting an output with a stream that can affect notification
1663 // routing
1664 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001665
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001666 // force reevaluating accessibility routing when ringtone or alarm starts
1667 if (strategy == STRATEGY_SONIFICATION) {
1668 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1669 }
Eric Laurentdc462862016-07-19 12:29:53 -07001670
1671 if (waitMs > muteWaitMs) {
1672 *delayMs = waitMs - muteWaitMs;
1673 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001674
1675 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1676 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1677 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1678 // change occurs after the MixerThread starts and causes a stream volume
1679 // glitch.
1680 //
1681 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001682 }
Eric Laurentdc462862016-07-19 12:29:53 -07001683
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001684 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1685 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1686 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1687 }
1688
Eric Laurent97ac8712018-07-27 18:59:02 -07001689 // Automatically enable the remote submix input when output is started on a re routing mix
1690 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001691 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001692 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1693 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1694 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1695 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001696 "remote-submix",
1697 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001698 }
1699
Eric Laurente552edb2014-03-10 17:42:56 -07001700 return NO_ERROR;
1701}
1702
Eric Laurent8fc147b2018-07-22 19:13:55 -07001703status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001704{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001705 ALOGV("%s portId %d", __FUNCTION__, portId);
1706
1707 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1708 if (outputDesc == 0) {
1709 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001710 return BAD_VALUE;
1711 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001712 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001713
Eric Laurent97ac8712018-07-27 18:59:02 -07001714 ALOGV("stopOutput() output %d, stream %d, session %d",
1715 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001716
Eric Laurent97ac8712018-07-27 18:59:02 -07001717 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001718
Eric Laurent733ce942017-12-07 12:18:25 -08001719 if (status == NO_ERROR ) {
1720 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001721 }
1722 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001723}
1724
Eric Laurent97ac8712018-07-27 18:59:02 -07001725status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1726 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001727{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001728 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001729 audio_stream_type_t stream = client->stream();
1730
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001731 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1732
Eric Laurent592dd7b2018-08-05 18:58:48 -07001733 if (outputDesc->streamActiveCount(stream) > 0) {
1734 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001735 // Automatically disable the remote submix input when output is stopped on a
1736 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001737 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001738 outputDesc->mPolicyMix != NULL &&
1739 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1740 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1741 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1742 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001743 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001744 }
1745 }
1746 bool forceDeviceUpdate = false;
1747 if (client->hasPreferredDevice(true)) {
1748 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1749 forceDeviceUpdate = true;
1750 }
1751
Eric Laurente552edb2014-03-10 17:42:56 -07001752 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001753 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001754
Eric Laurente552edb2014-03-10 17:42:56 -07001755 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001756 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001757 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001758 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001759 // delay the device switch by twice the latency because stopOutput() is executed when
1760 // the track stop() command is received and at that time the audio track buffer can
1761 // still contain data that needs to be drained. The latency only covers the audio HAL
1762 // and kernel buffers. Also the latency does not always include additional delay in the
1763 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001764 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001765
1766 // force restoring the device selection on other active outputs if it differs from the
1767 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001768 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001769 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001770 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001771 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001772 desc->isActive() &&
1773 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001774 (newDevices != desc->devices())) {
1775 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1776 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001777
François Gaffie11d30102018-11-02 16:09:09 +01001778 setOutputDevices(desc, newDevices2, force, delayMs);
1779
Eric Laurent57de36c2016-09-28 16:59:11 -07001780 // re-apply device specific volume if not done by setOutputDevice()
1781 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001782 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001783 }
Eric Laurente552edb2014-03-10 17:42:56 -07001784 }
1785 }
1786 // update the outputs if stopping one with a stream that can affect notification routing
1787 handleNotificationRoutingForStream(stream);
1788 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001789
1790 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1791 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1792 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1793 }
1794
Eric Laurent36829f92017-04-07 19:04:42 -07001795 if (stream == AUDIO_STREAM_MUSIC) {
1796 selectOutputForMusicEffects();
1797 }
Eric Laurente552edb2014-03-10 17:42:56 -07001798 return NO_ERROR;
1799 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001800 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001801 return INVALID_OPERATION;
1802 }
1803}
1804
Eric Laurent8fc147b2018-07-22 19:13:55 -07001805void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001806{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001807 ALOGV("%s portId %d", __FUNCTION__, portId);
1808
1809 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1810 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001811 // If an output descriptor is closed due to a device routing change,
1812 // then there are race conditions with releaseOutput from tracks
1813 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1814 // destroyed shortly thereafter.
1815 //
1816 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001817 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001818 return;
1819 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001820
1821 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001822
Eric Laurent8fc147b2018-07-22 19:13:55 -07001823 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1824 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001825 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001826 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001827 return;
1828 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001829 if (--outputDesc->mDirectOpenCount == 0) {
1830 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001831 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001832 }
1833 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001834 // stopOutput() needs to be successfully called before releaseOutput()
1835 // otherwise there may be inaccurate stream reference counts.
1836 // This is checked in outputDesc->removeClient below.
1837 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001838}
1839
Eric Laurentcaf7f482014-11-25 17:50:47 -08001840status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1841 audio_io_handle_t *input,
1842 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001843 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001844 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001845 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001846 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001847 input_type_t *inputType,
1848 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001849{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001850 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001851 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001852 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001853
Eric Laurentad2e7b92017-09-14 20:06:42 -07001854 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001855 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001856 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001857 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001858 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001859 sp<AudioInputDescriptor> inputDesc;
1860 sp<RecordClientDescriptor> clientDesc;
1861 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001862 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001863
1864 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1865 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1866 return INVALID_OPERATION;
1867 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001868
Francois Gaffie716e1432019-01-14 16:58:59 +01001869 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1870 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001871 }
1872
Paul McLean466dc8e2015-04-17 13:15:36 -06001873 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001874 sp<DeviceDescriptor> explicitRoutingDevice =
1875 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001876
Eric Laurentad2e7b92017-09-14 20:06:42 -07001877 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1878 // possible
1879 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1880 *input != AUDIO_IO_HANDLE_NONE) {
1881 ssize_t index = mInputs.indexOfKey(*input);
1882 if (index < 0) {
1883 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1884 status = BAD_VALUE;
1885 goto error;
1886 }
1887 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001888 RecordClientVector clients = inputDesc->getClientsForSession(session);
1889 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001890 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1891 status = BAD_VALUE;
1892 goto error;
1893 }
1894 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1895 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001896 // corresponds to a new client and is only permitted from the same UID.
1897 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001898 if (clients.size() > 1) {
1899 for (const auto& client : clients) {
1900 // The client map is ordered by key values (portId) and portIds are allocated
1901 // incrementaly. So the first client in this list is the one opened by audio flinger
1902 // when the mmap stream is created and should be ignored as it does not correspond
1903 // to an actual client
1904 if (client == *clients.cbegin()) {
1905 continue;
1906 }
1907 if (uid != client->uid() && !client->isSilenced()) {
1908 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1909 uid, client->portId(), client->uid());
1910 status = INVALID_OPERATION;
1911 goto error;
1912 }
Eric Laurent331679c2018-04-16 17:03:16 -07001913 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001914 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001915 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001916 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001917
Eric Laurent8f42ea12018-08-08 09:08:25 -07001918 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001919 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001920 }
1921
1922 *input = AUDIO_IO_HANDLE_NONE;
1923 *inputType = API_INPUT_INVALID;
1924
Francois Gaffie716e1432019-01-14 16:58:59 +01001925 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001926
Francois Gaffie716e1432019-01-14 16:58:59 +01001927 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1928 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1929 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001930 if (status != NO_ERROR) {
1931 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001932 }
1933 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001934 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001935 String8(attr->tags + strlen("addr=")),
1936 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001937 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001938 if (explicitRoutingDevice != nullptr) {
1939 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001940 } else {
Francois Gaffie716e1432019-01-14 16:58:59 +01001941 device = getDeviceAndMixForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001942 }
François Gaffie11d30102018-11-02 16:09:09 +01001943 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001944 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001945 status = BAD_VALUE;
1946 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001947 }
François Gaffie11d30102018-11-02 16:09:09 +01001948 if (policyMix != nullptr) {
1949 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1950 // there is an external policy, but this input is attached to a mix of recorders,
1951 // meaning it receives audio injected into the framework, so the recorder doesn't
1952 // know about it and is therefore considered "legacy"
1953 *inputType = API_INPUT_LEGACY;
1954 } else if (audio_is_remote_submix_device(device->type())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001955 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"),
1956 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001957 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001958 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001959 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001960 } else {
1961 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001962 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001963
Eric Laurent599c7582015-12-07 18:05:55 -08001964 }
1965
Francois Gaffie716e1432019-01-14 16:58:59 +01001966 *input = getInputForDevice(device, session, attributes.source,
Eric Laurentfe231122017-11-17 17:48:06 -08001967 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001968 policyMix);
1969 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001970 status = INVALID_OPERATION;
1971 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001972 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001973
Eric Laurent8f42ea12018-08-08 09:08:25 -07001974exit:
1975
François Gaffie11d30102018-11-02 16:09:09 +01001976 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1977 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001978
Francois Gaffie716e1432019-01-14 16:58:59 +01001979 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001980 mSoundTriggerSessions.indexOfKey(session) > 0;
1981 *portId = AudioPort::getNextUniqueId();
1982
François Gaffie11d30102018-11-02 16:09:09 +01001983 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001984 requestedDeviceId, attributes.source, flags,
1985 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001986 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001987 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001988
1989 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1990 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001991
Eric Laurent599c7582015-12-07 18:05:55 -08001992 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001993
1994error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001995 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001996}
1997
1998
François Gaffie11d30102018-11-02 16:09:09 +01001999audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002000 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08002001 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08002002 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002003 audio_input_flags_t flags,
2004 AudioMix *policyMix)
2005{
2006 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2007 audio_source_t halInputSource = inputSource;
2008 bool isSoundTrigger = false;
2009
2010 if (inputSource == AUDIO_SOURCE_HOTWORD) {
2011 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2012 if (index >= 0) {
2013 input = mSoundTriggerSessions.valueFor(session);
2014 isSoundTrigger = true;
2015 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2016 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2017 } else {
2018 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002019 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002020 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002021 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002022 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002023 }
2024
Andy Hungf129b032015-04-07 13:45:50 -07002025 // find a compatible input profile (not necessarily identical in parameters)
2026 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002027 // sampling rate and flags may be updated by getInputProfile
2028 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2029 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002030 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002031 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002032 audio_input_flags_t profileFlags = flags;
2033 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002034 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002035 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002036 profileFlags);
2037 if (profile != 0) {
2038 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002039 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2040 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002041 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2042 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2043 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002044 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2045 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2046 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002047 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002048 }
Eric Laurente552edb2014-03-10 17:42:56 -07002049 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002050 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002051 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002052 if (samplingRate == 0) {
2053 samplingRate = profileSamplingRate;
2054 }
Eric Laurente552edb2014-03-10 17:42:56 -07002055
Eric Laurent322b4d22015-04-03 15:57:54 -07002056 if (profile->getModuleHandle() == 0) {
2057 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002058 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002059 }
2060
Eric Laurent3974e3b2017-12-07 17:58:43 -08002061 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002062 for (size_t i = 0; i < mInputs.size(); ) {
2063 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2064 if (desc->mProfile != profile) {
2065 continue;
2066 }
2067 // if sound trigger, reuse input if used by other sound trigger on same session
2068 // else
2069 // reuse input if active client app is not in IDLE state
2070 //
2071 RecordClientVector clients = desc->clientsList();
2072 bool doClose = false;
2073 for (const auto& client : clients) {
2074 if (isSoundTrigger != client->isSoundTrigger()) {
2075 continue;
2076 }
2077 if (client->isSoundTrigger()) {
2078 if (session == client->session()) {
2079 return desc->mIoHandle;
2080 }
2081 continue;
2082 }
2083 if (client->active() && client->appState() != APP_STATE_IDLE) {
2084 return desc->mIoHandle;
2085 }
2086 doClose = true;
2087 }
2088 if (doClose) {
2089 closeInput(desc->mIoHandle);
2090 } else {
2091 i++;
2092 }
2093 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002094 }
2095
Eric Laurentfe231122017-11-17 17:48:06 -08002096 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002097
Eric Laurentfe231122017-11-17 17:48:06 -08002098 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2099 lConfig.sample_rate = profileSamplingRate;
2100 lConfig.channel_mask = profileChannelMask;
2101 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002102
François Gaffie11d30102018-11-02 16:09:09 +01002103 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002104
2105 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002106 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002107 (profileSamplingRate != lConfig.sample_rate) ||
2108 !audio_formats_match(profileFormat, lConfig.format) ||
2109 (profileChannelMask != lConfig.channel_mask)) {
2110 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002111 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002112 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002113 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002114 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002115 }
Eric Laurent599c7582015-12-07 18:05:55 -08002116 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002117 }
2118
Eric Laurentc722f302014-12-10 11:21:49 -08002119 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002120
Eric Laurent599c7582015-12-07 18:05:55 -08002121 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002122 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002123
Eric Laurent599c7582015-12-07 18:05:55 -08002124 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002125}
2126
Eric Laurent4eb58f12018-12-07 16:41:02 -08002127status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002128{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002129 ALOGV("%s portId %d", __FUNCTION__, portId);
2130
2131 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2132 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002133 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002134 return BAD_VALUE;
2135 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002137 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002138 if (client->active()) {
2139 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2140 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002141 }
2142
Eric Laurent8f42ea12018-08-08 09:08:25 -07002143 audio_session_t session = client->session();
2144
Eric Laurent4eb58f12018-12-07 16:41:02 -08002145 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002146
Eric Laurent4eb58f12018-12-07 16:41:02 -08002147 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002148
Eric Laurent4eb58f12018-12-07 16:41:02 -08002149 status_t status = inputDesc->start();
2150 if (status != NO_ERROR) {
2151 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002152 }
Eric Laurente552edb2014-03-10 17:42:56 -07002153
Eric Laurent4eb58f12018-12-07 16:41:02 -08002154 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002155 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002156 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002157
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158 // indicate active capture to sound trigger service if starting capture from a mic on
2159 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002160 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002161 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002162
Eric Laurent8f42ea12018-08-08 09:08:25 -07002163 if (inputDesc->activeCount() == 1) {
2164 // if input maps to a dynamic policy with an activity listener, notify of state change
2165 if ((inputDesc->mPolicyMix != NULL)
2166 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2167 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2168 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002169 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002170
François Gaffie11d30102018-11-02 16:09:09 +01002171 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2172 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002173 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2174 SoundTrigger::setCaptureState(true);
2175 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002176
Eric Laurent8f42ea12018-08-08 09:08:25 -07002177 // automatically enable the remote submix output when input is started if not
2178 // used by a policy mix of type MIX_TYPE_RECORDERS
2179 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002180 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002181 String8 address = String8("");
2182 if (inputDesc->mPolicyMix == NULL) {
2183 address = String8("0");
2184 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2185 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002186 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002187 if (address != "") {
2188 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2189 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002190 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002191 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002192 }
Eric Laurente552edb2014-03-10 17:42:56 -07002193 }
2194
Eric Laurent8f42ea12018-08-08 09:08:25 -07002195 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002196
Eric Laurente552edb2014-03-10 17:42:56 -07002197 return NO_ERROR;
2198}
2199
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002201{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002202 ALOGV("%s portId %d", __FUNCTION__, portId);
2203
2204 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2205 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002206 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002207 return BAD_VALUE;
2208 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002209 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002210 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002211 if (!client->active()) {
2212 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002213 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002214 }
2215
Eric Laurent8f42ea12018-08-08 09:08:25 -07002216 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002217
Eric Laurent8f42ea12018-08-08 09:08:25 -07002218 inputDesc->stop();
2219 if (inputDesc->isActive()) {
2220 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2221 } else {
2222 // if input maps to a dynamic policy with an activity listener, notify of state change
2223 if ((inputDesc->mPolicyMix != NULL)
2224 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2225 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2226 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002227 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002228
2229 // automatically disable the remote submix output when input is stopped if not
2230 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002231 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002232 String8 address = String8("");
2233 if (inputDesc->mPolicyMix == NULL) {
2234 address = String8("0");
2235 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2236 address = inputDesc->mPolicyMix->mDeviceAddress;
2237 }
2238 if (address != "") {
2239 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2240 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002241 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002242 }
2243 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002244 resetInputDevice(input);
2245
2246 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2247 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002248 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2249 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002250 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2251 SoundTrigger::setCaptureState(false);
2252 }
2253 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002254 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002255 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002256}
2257
Eric Laurent8fc147b2018-07-22 19:13:55 -07002258void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002259{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002260 ALOGV("%s portId %d", __FUNCTION__, portId);
2261
2262 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2263 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002264 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002265 return;
2266 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002267 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002268 audio_io_handle_t input = inputDesc->mIoHandle;
2269
Eric Laurent8f42ea12018-08-08 09:08:25 -07002270 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002271
Andy Hung39efb7a2018-09-26 15:39:28 -07002272 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002273
Andy Hung39efb7a2018-09-26 15:39:28 -07002274 if (inputDesc->getClientCount() > 0) {
2275 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002276 return;
2277 }
2278
Eric Laurent05b90f82014-08-27 15:32:29 -07002279 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002280 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002281 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002282}
2283
Eric Laurent8f42ea12018-08-08 09:08:25 -07002284void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002285{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002286 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002287
2288 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002289 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002290 }
2291}
2292
Eric Laurent8f42ea12018-08-08 09:08:25 -07002293void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2294{
2295 stopInput(portId);
2296 releaseInput(portId);
2297}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002298
Eric Laurentd4692962014-05-05 18:13:44 -07002299void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002300 bool patchRemoved = false;
2301
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002302 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002303 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002304 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002305 if (patch_index >= 0) {
2306 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002307 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002308 mAudioPatches.removeItemsAt(patch_index);
2309 patchRemoved = true;
2310 }
Eric Laurentfe231122017-11-17 17:48:06 -08002311 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002312 }
2313 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002314 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002315 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002316
2317 if (patchRemoved) {
2318 mpClientInterface->onAudioPatchListUpdate();
2319 }
Eric Laurentd4692962014-05-05 18:13:44 -07002320}
2321
Eric Laurente0720872014-03-11 09:30:41 -07002322void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002323 int indexMin,
2324 int indexMax)
2325{
2326 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002327 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002328
2329 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002330 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2331 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002332 continue;
2333 }
2334 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002335 }
Eric Laurente552edb2014-03-10 17:42:56 -07002336}
2337
Eric Laurente0720872014-03-11 09:30:41 -07002338status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002339 int index,
2340 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002341{
2342
Nadav Bar7c605f62017-12-25 00:01:52 +02002343 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2344 // app that has MODIFY_PHONE_STATE permission.
2345 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2346 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002347 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002348 return BAD_VALUE;
2349 }
2350 if (!audio_is_output_device(device)) {
2351 return BAD_VALUE;
2352 }
2353
2354 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002355 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002356
Eric Laurent1fd372e2016-04-06 14:23:53 -07002357 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002358 stream, device, index);
2359
Eric Laurent28d09f02016-03-08 10:43:05 -08002360 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002361 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2362 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002363 continue;
2364 }
2365 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2366 }
Eric Laurente552edb2014-03-10 17:42:56 -07002367
Eric Laurent1fd372e2016-04-06 14:23:53 -07002368 // update volume on all outputs and streams matching the following:
2369 // - The requested stream (or a stream matching for volume control) is active on the output
2370 // - The device (or devices) selected by the strategy corresponding to this stream includes
2371 // the requested device
2372 // - For non default requested device, currently selected device on the output is either the
2373 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002374 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2375 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002376 status_t status = NO_ERROR;
2377 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002378 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002379 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002380 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002381 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002382 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002383 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002384 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002385 continue;
2386 }
Eric Laurent794fde22016-03-11 09:50:45 -08002387 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002388 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2389 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002390 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2391 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002392 continue;
2393 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002394 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002395 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002396 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002397 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002398 } else {
2399 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002400 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002401 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002402 // rescale index before applying to curStream as ranges may be different for
2403 // stream and curStream
2404 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002405 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002406 //FIXME: workaround for truncated touch sounds
2407 // delayed volume change for system stream to be removed when the problem is
2408 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002409 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002410 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002411 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002412 if (volStatus != NO_ERROR) {
2413 status = volStatus;
2414 }
2415 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002416 }
Eric Laurente552edb2014-03-10 17:42:56 -07002417 }
2418 return status;
2419}
2420
Eric Laurente0720872014-03-11 09:30:41 -07002421status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002422 int *index,
2423 audio_devices_t device)
2424{
2425 if (index == NULL) {
2426 return BAD_VALUE;
2427 }
2428 if (!audio_is_output_device(device)) {
2429 return BAD_VALUE;
2430 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002431 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002432 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002433 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002434 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2435 }
François Gaffiedfd74092015-03-19 12:10:59 +01002436 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002437
François Gaffied1ab2bd2015-12-02 18:20:06 +01002438 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002439 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2440 return NO_ERROR;
2441}
2442
Eric Laurent36829f92017-04-07 19:04:42 -07002443audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002444{
2445 // select one output among several suitable for global effects.
2446 // The priority is as follows:
2447 // 1: An offloaded output. If the effect ends up not being offloadable,
2448 // AudioFlinger will invalidate the track and the offloaded output
2449 // will be closed causing the effect to be moved to a PCM output.
2450 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002451 // 3: The primary output
2452 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002453
Eric Laurent3b73df72014-03-11 09:06:29 -07002454 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002455 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2456 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002457
Eric Laurent36829f92017-04-07 19:04:42 -07002458 if (outputs.size() == 0) {
2459 return AUDIO_IO_HANDLE_NONE;
2460 }
Eric Laurente552edb2014-03-10 17:42:56 -07002461
Eric Laurent36829f92017-04-07 19:04:42 -07002462 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2463 bool activeOnly = true;
2464
2465 while (output == AUDIO_IO_HANDLE_NONE) {
2466 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2467 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2468 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2469
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002470 for (audio_io_handle_t output : outputs) {
2471 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002472 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2473 continue;
2474 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002475 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2476 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002477 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002478 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002479 }
2480 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002481 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002482 }
2483 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002484 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002485 }
2486 }
2487 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2488 output = outputOffloaded;
2489 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2490 output = outputDeepBuffer;
2491 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2492 output = outputPrimary;
2493 } else {
2494 output = outputs[0];
2495 }
2496 activeOnly = false;
2497 }
2498
2499 if (output != mMusicEffectOutput) {
2500 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2501 mMusicEffectOutput = output;
2502 }
2503
2504 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002505 return output;
2506}
2507
Eric Laurent36829f92017-04-07 19:04:42 -07002508audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2509{
2510 return selectOutputForMusicEffects();
2511}
2512
Eric Laurente0720872014-03-11 09:30:41 -07002513status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002514 audio_io_handle_t io,
2515 uint32_t strategy,
2516 int session,
2517 int id)
2518{
2519 ssize_t index = mOutputs.indexOfKey(io);
2520 if (index < 0) {
2521 index = mInputs.indexOfKey(io);
2522 if (index < 0) {
2523 ALOGW("registerEffect() unknown io %d", io);
2524 return INVALID_OPERATION;
2525 }
2526 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002527 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002528}
2529
Eric Laurentc241b0d2018-11-28 09:08:49 -08002530status_t AudioPolicyManager::unregisterEffect(int id)
2531{
2532 if (mEffects.getEffect(id) == nullptr) {
2533 return INVALID_OPERATION;
2534 }
2535
2536 if (mEffects.isEffectEnabled(id)) {
2537 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2538 setEffectEnabled(id, false);
2539 }
2540 return mEffects.unregisterEffect(id);
2541}
2542
2543status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2544{
2545 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2546 if (effect == nullptr) {
2547 return INVALID_OPERATION;
2548 }
2549
2550 status_t status = mEffects.setEffectEnabled(id, enabled);
2551 if (status == NO_ERROR) {
2552 mInputs.trackEffectEnabled(effect, enabled);
2553 }
2554 return status;
2555}
2556
Eric Laurentc75307b2015-03-17 15:29:32 -07002557bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2558{
Eric Laurent28d09f02016-03-08 10:43:05 -08002559 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002560 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2561 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002562 continue;
2563 }
2564 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2565 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002566 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002567}
2568
2569bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2570{
2571 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2572}
2573
Eric Laurente0720872014-03-11 09:30:41 -07002574bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002575{
2576 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002577 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002578 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002579 return true;
2580 }
2581 }
2582 return false;
2583}
2584
Eric Laurent275e8e92014-11-30 15:14:47 -08002585// Register a list of custom mixes with their attributes and format.
2586// When a mix is registered, corresponding input and output profiles are
2587// added to the remote submix hw module. The profile contains only the
2588// parameters (sampling rate, format...) specified by the mix.
2589// The corresponding input remote submix device is also connected.
2590//
2591// When a remote submix device is connected, the address is checked to select the
2592// appropriate profile and the corresponding input or output stream is opened.
2593//
2594// When capture starts, getInputForAttr() will:
2595// - 1 look for a mix matching the address passed in attribtutes tags if any
2596// - 2 if none found, getDeviceForInputSource() will:
2597// - 2.1 look for a mix matching the attributes source
2598// - 2.2 if none found, default to device selection by policy rules
2599// At this time, the corresponding output remote submix device is also connected
2600// and active playback use cases can be transferred to this mix if needed when reconnecting
2601// after AudioTracks are invalidated
2602//
2603// When playback starts, getOutputForAttr() will:
2604// - 1 look for a mix matching the address passed in attribtutes tags if any
2605// - 2 if none found, look for a mix matching the attributes usage
2606// - 3 if none found, default to device and output selection by policy rules.
2607
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002608status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002609{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002610 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2611 status_t res = NO_ERROR;
2612
2613 sp<HwModule> rSubmixModule;
2614 // examine each mix's route type
2615 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002616 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002617 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002618 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002619 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002620 break;
2621 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002622 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002623 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002624 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002625 rSubmixModule = mHwModules.getModuleFromName(
2626 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2627 if (rSubmixModule == 0) {
2628 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2629 i);
2630 res = INVALID_OPERATION;
2631 break;
2632 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002633 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002634
Eric Laurent97ac8712018-07-27 18:59:02 -07002635 String8 address = mix.mDeviceAddress;
2636 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2637 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2638 } else {
2639 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2640 }
François Gaffie036e1e92015-03-19 10:16:24 +01002641
Eric Laurent97ac8712018-07-27 18:59:02 -07002642 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002643 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002644 res = INVALID_OPERATION;
2645 break;
2646 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002647 audio_config_t outputConfig = mix.mFormat;
2648 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002649 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2650 // stereo and let audio flinger do the channel conversion if needed.
2651 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2652 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2653 rSubmixModule->addOutputProfile(address, &outputConfig,
2654 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2655 rSubmixModule->addInputProfile(address, &inputConfig,
2656 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002657
Eric Laurent97ac8712018-07-27 18:59:02 -07002658 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002659 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2660 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002661 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002662 } else {
2663 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2664 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002665 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002666 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002667 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2668 String8 address = mix.mDeviceAddress;
2669 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002670 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2671 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002672
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002673 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2675 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2676 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2677 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2678 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2679 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002680 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2681 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002682 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002683 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002684 } else {
2685 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002686 }
2687 break;
2688 }
2689 }
2690
2691 if (res != NO_ERROR) {
2692 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002693 i, device, address.string());
2694 res = INVALID_OPERATION;
2695 break;
2696 } else if (!foundOutput) {
2697 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2698 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002699 res = INVALID_OPERATION;
2700 break;
2701 }
Eric Laurentc722f302014-12-10 11:21:49 -08002702 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002703 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002704 if (res != NO_ERROR) {
2705 unregisterPolicyMixes(mixes);
2706 }
2707 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002708}
2709
2710status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2711{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002712 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002713 status_t res = NO_ERROR;
2714 sp<HwModule> rSubmixModule;
2715 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002716 for (const auto& mix : mixes) {
2717 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002718
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002719 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002720 rSubmixModule = mHwModules.getModuleFromName(
2721 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2722 if (rSubmixModule == 0) {
2723 res = INVALID_OPERATION;
2724 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002725 }
2726 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002727
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002728 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002729
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002730 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2731 res = INVALID_OPERATION;
2732 continue;
2733 }
2734
2735 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2736 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2737 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2738 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002739 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002740 }
2741 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2742 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2743 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2744 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002745 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002746 }
2747 rSubmixModule->removeOutputProfile(address);
2748 rSubmixModule->removeInputProfile(address);
2749
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002750 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2751 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002752 res = INVALID_OPERATION;
2753 continue;
2754 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002755 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002756 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002757 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002758}
2759
Mikhail Naganov100f0122018-11-29 11:22:16 -08002760void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2761{
2762 size_t i = 0;
2763 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2764 for (const auto& fmt : mManualSurroundFormats) {
2765 if (i++ != 0) dst->append(", ");
2766 std::string sfmt;
2767 FormatConverter::toString(fmt, sfmt);
2768 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2769 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2770 }
2771}
2772
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002773status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2774 const Vector<AudioDeviceTypeAddr>& devices) {
2775 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2776 // uid/device affinity is only for output devices
2777 for (size_t i = 0; i < devices.size(); i++) {
2778 if (!audio_is_output_device(devices[i].mType)) {
2779 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2780 devices[i].mType);
2781 return BAD_VALUE;
2782 }
2783 }
2784 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2785 if (res == NO_ERROR) {
2786 // reevaluate outputs for all given devices
2787 for (size_t i = 0; i < devices.size(); i++) {
2788 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002789 devices[i].mType, devices[i].mAddress, String8(),
2790 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002791 SortedVector<audio_io_handle_t> outputs;
2792 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002793 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002794 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2795 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2796 return INVALID_OPERATION;
2797 }
2798 }
2799 }
2800 return res;
2801}
2802
2803status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2804 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2805 Vector<AudioDeviceTypeAddr> devices;
2806 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2807 if (res == NO_ERROR) {
2808 // reevaluate outputs for all found devices
2809 for (size_t i = 0; i < devices.size(); i++) {
2810 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002811 devices[i].mType, devices[i].mAddress, String8(),
2812 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002813 SortedVector<audio_io_handle_t> outputs;
2814 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002815 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002816 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2817 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2818 return INVALID_OPERATION;
2819 }
2820 }
2821 }
2822
2823 return res;
2824}
2825
Andy Hungc29d82b2018-10-05 12:23:17 -07002826void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002827{
Andy Hungc29d82b2018-10-05 12:23:17 -07002828 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2829 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002830 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002831 std::string stateLiteral;
2832 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002833 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002834 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2835 "communications", "media", "record", "dock", "system",
2836 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2837 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2838 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002839 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2840 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2841 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2842 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2843 dst->append(" (MANUAL: ");
2844 dumpManualSurroundFormats(dst);
2845 dst->append(")");
2846 }
2847 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002848 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002849 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2850 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2851 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2852 mAvailableOutputDevices.dump(dst, String8("Available output"));
2853 mAvailableInputDevices.dump(dst, String8("Available input"));
2854 mHwModulesAll.dump(dst);
2855 mOutputs.dump(dst);
2856 mInputs.dump(dst);
2857 mVolumeCurves->dump(dst);
2858 mEffects.dump(dst);
2859 mAudioPatches.dump(dst);
2860 mPolicyMixes.dump(dst);
2861 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002862}
2863
2864status_t AudioPolicyManager::dump(int fd)
2865{
2866 String8 result;
2867 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002868 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002869 return NO_ERROR;
2870}
2871
2872// This function checks for the parameters which can be offloaded.
2873// This can be enhanced depending on the capability of the DSP and policy
2874// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002875bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002876{
2877 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002878 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002879 offloadInfo.sample_rate, offloadInfo.channel_mask,
2880 offloadInfo.format,
2881 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2882 offloadInfo.has_video);
2883
Andy Hung2ddee192015-12-18 17:34:44 -08002884 if (mMasterMono) {
2885 return false; // no offloading if mono is set.
2886 }
2887
Eric Laurente552edb2014-03-10 17:42:56 -07002888 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002889 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2890 ALOGV("offload disabled by audio.offload.disable");
2891 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002892 }
2893
2894 // Check if stream type is music, then only allow offload as of now.
2895 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2896 {
2897 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2898 return false;
2899 }
2900
2901 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002902 const bool allowOffloadWithVideo =
2903 property_get_bool("audio.offload.video", false /* default_value */);
2904 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002905 ALOGV("isOffloadSupported: has_video == true, returning false");
2906 return false;
2907 }
2908
2909 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002910 const int min_duration_secs = property_get_int32(
2911 "audio.offload.min.duration.secs", -1 /* default_value */);
2912 if (min_duration_secs >= 0) {
2913 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2914 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2915 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002916 return false;
2917 }
2918 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2919 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2920 return false;
2921 }
2922
2923 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2924 // creating an offloaded track and tearing it down immediately after start when audioflinger
2925 // detects there is an active non offloadable effect.
2926 // FIXME: We should check the audio session here but we do not have it in this context.
2927 // This may prevent offloading in rare situations where effects are left active by apps
2928 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002929 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002930 return false;
2931 }
2932
2933 // See if there is a profile to support this.
2934 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002935 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002936 offloadInfo.sample_rate,
2937 offloadInfo.format,
2938 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002939 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2940 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002941 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2942 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002943}
2944
Michael Chana94fbb22018-04-24 14:31:19 +10002945bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2946 const audio_attributes_t& attributes) {
2947 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2948 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002949 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002950 config.sample_rate,
2951 config.format,
2952 config.channel_mask,
2953 output_flags,
2954 true /* directOnly */);
2955 ALOGV("%s() profile %sfound with name: %s, "
2956 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2957 __FUNCTION__, profile != 0 ? "" : "NOT ",
2958 (profile != 0 ? profile->getTagName().string() : "null"),
2959 config.sample_rate, config.format, config.channel_mask, output_flags);
2960 return (profile != 0);
2961}
2962
Eric Laurent6a94d692014-05-20 11:18:06 -07002963status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2964 audio_port_type_t type,
2965 unsigned int *num_ports,
2966 struct audio_port *ports,
2967 unsigned int *generation)
2968{
2969 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2970 generation == NULL) {
2971 return BAD_VALUE;
2972 }
2973 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2974 if (ports == NULL) {
2975 *num_ports = 0;
2976 }
2977
2978 size_t portsWritten = 0;
2979 size_t portsMax = *num_ports;
2980 *num_ports = 0;
2981 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002982 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2983 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002984 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002985 for (const auto& dev : mAvailableOutputDevices) {
2986 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002987 continue;
2988 }
2989 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002990 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002991 }
2992 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002993 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002994 }
2995 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002996 for (const auto& dev : mAvailableInputDevices) {
2997 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002998 continue;
2999 }
3000 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003001 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003002 }
3003 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003004 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 }
3006 }
3007 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3008 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3009 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3010 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3011 }
3012 *num_ports += mInputs.size();
3013 }
3014 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003015 size_t numOutputs = 0;
3016 for (size_t i = 0; i < mOutputs.size(); i++) {
3017 if (!mOutputs[i]->isDuplicated()) {
3018 numOutputs++;
3019 if (portsWritten < portsMax) {
3020 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3021 }
3022 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003023 }
Eric Laurent84c70242014-06-23 08:46:27 -07003024 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003025 }
3026 }
3027 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003028 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003029 return NO_ERROR;
3030}
3031
Eric Laurent99fcae42018-05-17 16:59:18 -07003032status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003033{
Eric Laurent99fcae42018-05-17 16:59:18 -07003034 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3035 return BAD_VALUE;
3036 }
3037 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3038 if (dev != 0) {
3039 dev->toAudioPort(port);
3040 return NO_ERROR;
3041 }
3042 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3043 if (dev != 0) {
3044 dev->toAudioPort(port);
3045 return NO_ERROR;
3046 }
3047 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3048 if (out != 0) {
3049 out->toAudioPort(port);
3050 return NO_ERROR;
3051 }
3052 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3053 if (in != 0) {
3054 in->toAudioPort(port);
3055 return NO_ERROR;
3056 }
3057 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003058}
3059
Eric Laurent6a94d692014-05-20 11:18:06 -07003060status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3061 audio_patch_handle_t *handle,
3062 uid_t uid)
3063{
3064 ALOGV("createAudioPatch()");
3065
3066 if (handle == NULL || patch == NULL) {
3067 return BAD_VALUE;
3068 }
3069 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3070
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003071 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003072 return BAD_VALUE;
3073 }
3074 // only one source per audio patch supported for now
3075 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003076 return INVALID_OPERATION;
3077 }
Eric Laurent874c42872014-08-08 15:13:39 -07003078
3079 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003080 return INVALID_OPERATION;
3081 }
Eric Laurent874c42872014-08-08 15:13:39 -07003082 for (size_t i = 0; i < patch->num_sinks; i++) {
3083 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3084 return INVALID_OPERATION;
3085 }
3086 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003087
3088 sp<AudioPatch> patchDesc;
3089 ssize_t index = mAudioPatches.indexOfKey(*handle);
3090
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3092 patch->sources[0].role,
3093 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003094#if LOG_NDEBUG == 0
3095 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003096 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003097 patch->sinks[i].role,
3098 patch->sinks[i].type);
3099 }
3100#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003101
3102 if (index >= 0) {
3103 patchDesc = mAudioPatches.valueAt(index);
3104 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3105 mUidCached, patchDesc->mUid, uid);
3106 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3107 return INVALID_OPERATION;
3108 }
3109 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003110 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003111 }
3112
3113 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003114 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003115 if (outputDesc == NULL) {
3116 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3117 return BAD_VALUE;
3118 }
Eric Laurent84c70242014-06-23 08:46:27 -07003119 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3120 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003121 if (patchDesc != 0) {
3122 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3123 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3124 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3125 return BAD_VALUE;
3126 }
3127 }
Eric Laurent874c42872014-08-08 15:13:39 -07003128 DeviceVector devices;
3129 for (size_t i = 0; i < patch->num_sinks; i++) {
3130 // Only support mix to devices connection
3131 // TODO add support for mix to mix connection
3132 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3133 ALOGV("createAudioPatch() source mix but sink is not a device");
3134 return INVALID_OPERATION;
3135 }
3136 sp<DeviceDescriptor> devDesc =
3137 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3138 if (devDesc == 0) {
3139 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3140 return BAD_VALUE;
3141 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003142
François Gaffie11d30102018-11-02 16:09:09 +01003143 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003144 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003145 NULL, // updatedSamplingRate
3146 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003147 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003148 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003149 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003150 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003151 ALOGV("createAudioPatch() profile not supported for device %08x",
3152 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003153 return INVALID_OPERATION;
3154 }
3155 devices.add(devDesc);
3156 }
3157 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003158 return INVALID_OPERATION;
3159 }
Eric Laurent874c42872014-08-08 15:13:39 -07003160
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 // TODO: reconfigure output format and channels here
3162 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003163 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003164 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003165 index = mAudioPatches.indexOfKey(*handle);
3166 if (index >= 0) {
3167 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3168 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3169 }
3170 patchDesc = mAudioPatches.valueAt(index);
3171 patchDesc->mUid = uid;
3172 ALOGV("createAudioPatch() success");
3173 } else {
3174 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3175 return INVALID_OPERATION;
3176 }
3177 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3178 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3179 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003180 // only one sink supported when connecting an input device to a mix
3181 if (patch->num_sinks > 1) {
3182 return INVALID_OPERATION;
3183 }
François Gaffie53615e22015-03-19 09:24:12 +01003184 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003185 if (inputDesc == NULL) {
3186 return BAD_VALUE;
3187 }
3188 if (patchDesc != 0) {
3189 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3190 return BAD_VALUE;
3191 }
3192 }
François Gaffie11d30102018-11-02 16:09:09 +01003193 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003194 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003195 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 return BAD_VALUE;
3197 }
3198
François Gaffie11d30102018-11-02 16:09:09 +01003199 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003200 patch->sinks[0].sample_rate,
3201 NULL, /*updatedSampleRate*/
3202 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003203 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003204 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003205 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003206 // FIXME for the parameter type,
3207 // and the NONE
3208 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003209 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003210 return INVALID_OPERATION;
3211 }
3212 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003213 ALOGV("%s() setting device %s on output %d", __func__,
3214 device->toString().c_str(), inputDesc->mIoHandle);
3215 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003216 index = mAudioPatches.indexOfKey(*handle);
3217 if (index >= 0) {
3218 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3219 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3220 }
3221 patchDesc = mAudioPatches.valueAt(index);
3222 patchDesc->mUid = uid;
3223 ALOGV("createAudioPatch() success");
3224 } else {
3225 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3226 return INVALID_OPERATION;
3227 }
3228 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3229 // device to device connection
3230 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003231 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003232 return BAD_VALUE;
3233 }
3234 }
François Gaffie11d30102018-11-02 16:09:09 +01003235 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003236 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003237 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003238 return BAD_VALUE;
3239 }
Eric Laurent874c42872014-08-08 15:13:39 -07003240
Eric Laurent6a94d692014-05-20 11:18:06 -07003241 //update source and sink with our own data as the data passed in the patch may
3242 // be incomplete.
3243 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003244 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003245
Eric Laurent874c42872014-08-08 15:13:39 -07003246 for (size_t i = 0; i < patch->num_sinks; i++) {
3247 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3248 ALOGV("createAudioPatch() source device but one sink is not a device");
3249 return INVALID_OPERATION;
3250 }
3251
François Gaffie11d30102018-11-02 16:09:09 +01003252 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003253 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003254 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003255 return BAD_VALUE;
3256 }
François Gaffie11d30102018-11-02 16:09:09 +01003257 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003258
Eric Laurent3bcf8592015-04-03 12:13:24 -07003259 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003260 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003261 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003262 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003263 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3264 (srcDevice->getModuleVersionMajor() < 3) ||
3265 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003266 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003267 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003268 return INVALID_OPERATION;
3269 }
Eric Laurent874c42872014-08-08 15:13:39 -07003270 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003271 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003272 // if the sink device is reachable via an opened output stream, request to go via
3273 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003274 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003275 if (output != AUDIO_IO_HANDLE_NONE) {
3276 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3277 if (outputDesc->isDuplicated()) {
3278 return INVALID_OPERATION;
3279 }
3280 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003281 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003282 newPatch.num_sources = 2;
3283 }
Eric Laurent83b88082014-06-20 18:31:16 -07003284 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003285 }
3286 // TODO: check from routing capabilities in config file and other conflicting patches
3287
Mikhail Naganovdc769682018-05-04 15:34:08 -07003288 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3289 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003290 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3291 status);
3292 return INVALID_OPERATION;
3293 }
3294 } else {
3295 return BAD_VALUE;
3296 }
3297 } else {
3298 return BAD_VALUE;
3299 }
3300 return NO_ERROR;
3301}
3302
3303status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3304 uid_t uid)
3305{
3306 ALOGV("releaseAudioPatch() patch %d", handle);
3307
3308 ssize_t index = mAudioPatches.indexOfKey(handle);
3309
3310 if (index < 0) {
3311 return BAD_VALUE;
3312 }
3313 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3314 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3315 mUidCached, patchDesc->mUid, uid);
3316 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3317 return INVALID_OPERATION;
3318 }
3319
3320 struct audio_patch *patch = &patchDesc->mPatch;
3321 patchDesc->mUid = mUidCached;
3322 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003323 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003324 if (outputDesc == NULL) {
3325 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3326 return BAD_VALUE;
3327 }
3328
François Gaffie11d30102018-11-02 16:09:09 +01003329 setOutputDevices(outputDesc,
3330 getNewOutputDevices(outputDesc, true /*fromCache*/),
3331 true,
3332 0,
3333 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003334 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3335 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003336 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003337 if (inputDesc == NULL) {
3338 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3339 return BAD_VALUE;
3340 }
3341 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003342 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003343 true,
3344 NULL);
3345 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003346 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3347 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3348 status, patchDesc->mAfPatchHandle);
3349 removeAudioPatch(patchDesc->mHandle);
3350 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003351 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003352 } else {
3353 return BAD_VALUE;
3354 }
3355 } else {
3356 return BAD_VALUE;
3357 }
3358 return NO_ERROR;
3359}
3360
3361status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3362 struct audio_patch *patches,
3363 unsigned int *generation)
3364{
François Gaffie53615e22015-03-19 09:24:12 +01003365 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003366 return BAD_VALUE;
3367 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003368 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003369 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003370}
3371
Eric Laurente1715a42014-05-20 11:30:42 -07003372status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003373{
Eric Laurente1715a42014-05-20 11:30:42 -07003374 ALOGV("setAudioPortConfig()");
3375
3376 if (config == NULL) {
3377 return BAD_VALUE;
3378 }
3379 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3380 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003381 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3382 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003383 }
3384
Eric Laurenta121f902014-06-03 13:32:54 -07003385 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003386 if (config->type == AUDIO_PORT_TYPE_MIX) {
3387 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003388 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003389 if (outputDesc == NULL) {
3390 return BAD_VALUE;
3391 }
Eric Laurent84c70242014-06-23 08:46:27 -07003392 ALOG_ASSERT(!outputDesc->isDuplicated(),
3393 "setAudioPortConfig() called on duplicated output %d",
3394 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003395 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003396 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003397 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003398 if (inputDesc == NULL) {
3399 return BAD_VALUE;
3400 }
Eric Laurenta121f902014-06-03 13:32:54 -07003401 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003402 } else {
3403 return BAD_VALUE;
3404 }
3405 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3406 sp<DeviceDescriptor> deviceDesc;
3407 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3408 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3409 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3410 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3411 } else {
3412 return BAD_VALUE;
3413 }
3414 if (deviceDesc == NULL) {
3415 return BAD_VALUE;
3416 }
Eric Laurenta121f902014-06-03 13:32:54 -07003417 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003418 } else {
3419 return BAD_VALUE;
3420 }
3421
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003422 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003423 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3424 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003425 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003426 audioPortConfig->toAudioPortConfig(&newConfig, config);
3427 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003428 }
Eric Laurenta121f902014-06-03 13:32:54 -07003429 if (status != NO_ERROR) {
3430 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003431 }
Eric Laurente1715a42014-05-20 11:30:42 -07003432
3433 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003434}
3435
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003436void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3437{
Eric Laurentd60560a2015-04-10 11:31:20 -07003438 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003439 clearAudioPatches(uid);
3440 clearSessionRoutes(uid);
3441}
3442
Eric Laurent6a94d692014-05-20 11:18:06 -07003443void AudioPolicyManager::clearAudioPatches(uid_t uid)
3444{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003445 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003446 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3447 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003448 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003449 }
3450 }
3451}
3452
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003453void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3454 audio_io_handle_t ouptutToSkip)
3455{
François Gaffie11d30102018-11-02 16:09:09 +01003456 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3457 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003458 for (size_t j = 0; j < mOutputs.size(); j++) {
3459 if (mOutputs.keyAt(j) == ouptutToSkip) {
3460 continue;
3461 }
3462 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3463 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3464 continue;
3465 }
3466 // If the default device for this strategy is on another output mix,
3467 // invalidate all tracks in this strategy to force re connection.
3468 // Otherwise select new device on the output mix.
3469 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003470 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003471 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3472 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3473 }
3474 }
3475 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003476 setOutputDevices(
3477 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003478 }
3479 }
3480}
3481
3482void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3483{
3484 // remove output routes associated with this uid
3485 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003486 for (size_t i = 0; i < mOutputs.size(); i++) {
3487 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003488 for (const auto& client : outputDesc->getClientIterable()) {
3489 if (client->hasPreferredDevice() && client->uid() == uid) {
3490 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3491 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003492 }
3493 }
3494 }
3495 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003496 for (const auto& strategy : affectedStrategies) {
3497 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003498 }
3499
3500 // remove input routes associated with this uid
3501 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003502 for (size_t i = 0; i < mInputs.size(); i++) {
3503 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003504 for (const auto& client : inputDesc->getClientIterable()) {
3505 if (client->hasPreferredDevice() && client->uid() == uid) {
3506 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3507 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003508 }
3509 }
3510 }
3511 // reroute inputs if necessary
3512 SortedVector<audio_io_handle_t> inputsToClose;
3513 for (size_t i = 0; i < mInputs.size(); i++) {
3514 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003515 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003516 inputsToClose.add(inputDesc->mIoHandle);
3517 }
3518 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003519 for (const auto& input : inputsToClose) {
3520 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003521 }
3522}
3523
Eric Laurentd60560a2015-04-10 11:31:20 -07003524void AudioPolicyManager::clearAudioSources(uid_t uid)
3525{
3526 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003527 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3528 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003529 stopAudioSource(mAudioSources.keyAt(i));
3530 }
3531 }
3532}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003533
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003534status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3535 audio_io_handle_t *ioHandle,
3536 audio_devices_t *device)
3537{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003538 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3539 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003540 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3541 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003542
François Gaffiedf372692015-03-19 10:43:27 +01003543 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003544}
3545
Eric Laurentd60560a2015-04-10 11:31:20 -07003546status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003547 const audio_attributes_t *attributes,
3548 audio_port_handle_t *portId,
3549 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003550{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003551 ALOGV("%s", __FUNCTION__);
3552 *portId = AUDIO_PORT_HANDLE_NONE;
3553
3554 if (source == NULL || attributes == NULL || portId == NULL) {
3555 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3556 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003557 return BAD_VALUE;
3558 }
3559
Eric Laurentd60560a2015-04-10 11:31:20 -07003560 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3561 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003562 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3563 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003564 return INVALID_OPERATION;
3565 }
3566
François Gaffie11d30102018-11-02 16:09:09 +01003567 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003568 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003569 String8(source->ext.device.address),
3570 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003571 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003572 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003573 return BAD_VALUE;
3574 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003575
3576 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003577
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003578 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003579 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003580
3581 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003582 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003583 streamTypefromAttributesInt(attributes),
3584 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003585
3586 status_t status = connectAudioSource(sourceDesc);
3587 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003588 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003589 }
3590 return status;
3591}
3592
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003593status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003594{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003595 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003596
3597 // make sure we only have one patch per source.
3598 disconnectAudioSource(sourceDesc);
3599
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003600 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003601 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003602 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003603 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003604
François Gaffie11d30102018-11-02 16:09:09 +01003605 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3606 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3607 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3608 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3609 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003610
3611 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003612
François Gaffie11d30102018-11-02 16:09:09 +01003613 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3614 srcDevice->getModuleVersionMajor() >= 3 &&
3615 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3616 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003617 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003618 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003619 // create patch between src device and output device
3620 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003621 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003622 audio_attributes_t resultAttr;
3623 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3624 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3625 config.sample_rate = sourceDesc->config().sample_rate;
3626 config.channel_mask = sourceDesc->config().channel_mask;
3627 config.format = sourceDesc->config().format;
3628 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3629 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3630 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3631 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003632 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003633 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003634 return INVALID_OPERATION;
3635 }
3636 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3637 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003638 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003639 return INVALID_OPERATION;
3640 }
Eric Laurent733ce942017-12-07 12:18:25 -08003641 status_t status = outputDesc->start();
3642 if (status != NO_ERROR) {
3643 return status;
3644 }
3645
Eric Laurentd60560a2015-04-10 11:31:20 -07003646 // create a special patch with no sink and two sources:
3647 // - the second source indicates to PatchPanel through which output mix this patch should
3648 // be connected as well as the stream type for volume control
3649 // - the sink is defined by whatever output device is currently selected for the output
3650 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003651 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003652 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003653 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003654 &afPatchHandle,
3655 0);
3656 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3657 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003658 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003659 if (status != NO_ERROR) {
3660 ALOGW("%s patch panel could not connect device patch, error %d",
3661 __FUNCTION__, status);
3662 return INVALID_OPERATION;
3663 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003664
3665 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3666 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3667 return INVALID_OPERATION;
3668 }
3669 outputDesc->addClient(sourceDesc);
3670
Eric Laurentd60560a2015-04-10 11:31:20 -07003671 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003672 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003673
3674 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003675 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003676 return status;
3677 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003678 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003679 if (delayMs != 0) {
3680 usleep(delayMs * 1000);
3681 }
3682 }
3683
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003684 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3685 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003686
3687 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003688}
3689
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003690status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003691{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003692 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3693 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003694 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003695 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003696 return BAD_VALUE;
3697 }
3698 status_t status = disconnectAudioSource(sourceDesc);
3699
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003700 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003701 return status;
3702}
3703
Andy Hung2ddee192015-12-18 17:34:44 -08003704status_t AudioPolicyManager::setMasterMono(bool mono)
3705{
3706 if (mMasterMono == mono) {
3707 return NO_ERROR;
3708 }
3709 mMasterMono = mono;
3710 // if enabling mono we close all offloaded devices, which will invalidate the
3711 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3712 // for recreating the new AudioTrack as non-offloaded PCM.
3713 //
3714 // If disabling mono, we leave all tracks as is: we don't know which clients
3715 // and tracks are able to be recreated as offloaded. The next "song" should
3716 // play back offloaded.
3717 if (mMasterMono) {
3718 Vector<audio_io_handle_t> offloaded;
3719 for (size_t i = 0; i < mOutputs.size(); ++i) {
3720 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3721 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3722 offloaded.push(desc->mIoHandle);
3723 }
3724 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003725 for (const auto& handle : offloaded) {
3726 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003727 }
3728 }
3729 // update master mono for all remaining outputs
3730 for (size_t i = 0; i < mOutputs.size(); ++i) {
3731 updateMono(mOutputs.keyAt(i));
3732 }
3733 return NO_ERROR;
3734}
3735
3736status_t AudioPolicyManager::getMasterMono(bool *mono)
3737{
3738 *mono = mMasterMono;
3739 return NO_ERROR;
3740}
3741
Eric Laurentac9cef52017-06-09 15:46:26 -07003742float AudioPolicyManager::getStreamVolumeDB(
3743 audio_stream_type_t stream, int index, audio_devices_t device)
3744{
3745 return computeVolume(stream, index, device);
3746}
3747
jiabin81772902018-04-02 17:52:27 -07003748status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3749 audio_format_t *surroundFormats,
3750 bool *surroundFormatsEnabled,
3751 bool reported)
3752{
3753 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3754 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3755 return BAD_VALUE;
3756 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003757 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3758 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003759
3760 size_t formatsWritten = 0;
3761 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003762 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003763 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003764 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003765 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003766 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3767 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3768 FormatVector supportedFormats =
3769 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3770 for (size_t j = 0; j < supportedFormats.size(); j++) {
3771 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3772 formats.insert(supportedFormats[j]);
3773 } else {
3774 for (const auto& pair : mConfig.getSurroundFormats()) {
3775 if (pair.second.count(supportedFormats[j]) != 0) {
3776 formats.insert(pair.first);
3777 break;
3778 }
3779 }
3780 }
3781 }
jiabin81772902018-04-02 17:52:27 -07003782 }
3783 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003784 for (const auto& pair : mConfig.getSurroundFormats()) {
3785 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003786 }
3787 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003788 *numSurroundFormats = formats.size();
3789 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3790 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003791 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003792 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003793 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003794 bool formatEnabled = true;
3795 switch (forceUse) {
3796 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3797 formatEnabled = mManualSurroundFormats.count(format) != 0;
3798 break;
3799 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3800 formatEnabled = false;
3801 break;
3802 default: // AUTO or ALWAYS => true
3803 break;
jiabin81772902018-04-02 17:52:27 -07003804 }
3805 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3806 }
jiabin81772902018-04-02 17:52:27 -07003807 }
3808 return NO_ERROR;
3809}
3810
3811status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3812{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003813 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003814 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3815 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003816 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003817 return BAD_VALUE;
3818 }
3819
Mikhail Naganov100f0122018-11-29 11:22:16 -08003820 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3821 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003822 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003823 return INVALID_OPERATION;
3824 }
3825
Mikhail Naganov100f0122018-11-29 11:22:16 -08003826 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003827 return NO_ERROR;
3828 }
3829
Mikhail Naganov100f0122018-11-29 11:22:16 -08003830 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003831 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003832 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003833 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003834 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003835 }
3836 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003837 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003838 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003839 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003840 }
3841 }
3842
3843 sp<SwAudioOutputDescriptor> outputDesc;
3844 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003845 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003846 AUDIO_DEVICE_OUT_HDMI);
3847 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3848 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003849 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003850 String8 name = hdmiOutputDevices[i]->getName();
3851 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3852 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3853 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003854 name.c_str(),
3855 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003856 if (status != NO_ERROR) {
3857 continue;
3858 }
3859 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3860 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3861 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003862 name.c_str(),
3863 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003864 profileUpdated |= (status == NO_ERROR);
3865 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003866 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003867 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003868 AUDIO_DEVICE_IN_HDMI);
3869 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3870 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003871 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003872 String8 name = hdmiInputDevices[i]->getName();
3873 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3874 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3875 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003876 name.c_str(),
3877 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003878 if (status != NO_ERROR) {
3879 continue;
3880 }
3881 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3882 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3883 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003884 name.c_str(),
3885 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003886 profileUpdated |= (status == NO_ERROR);
3887 }
3888
jiabin81772902018-04-02 17:52:27 -07003889 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003890 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003891 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003892 }
3893
3894 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3895}
3896
Eric Laurentf32108e2018-10-04 17:22:04 -07003897void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003898{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003899 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003900
Eric Laurenta9f86652018-11-28 17:23:11 -08003901 for (size_t i = 0; i < mInputs.size(); i++) {
3902 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3903 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003904 for (const auto& client : clients) {
3905 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003906 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003907 }
3908 }
3909 }
3910}
3911
jiabin6012f912018-11-02 17:06:30 -07003912bool AudioPolicyManager::isHapticPlaybackSupported()
3913{
3914 for (const auto& hwModule : mHwModules) {
3915 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3916 for (const auto &outProfile : outputProfiles) {
3917 struct audio_port audioPort;
3918 outProfile->toAudioPort(&audioPort);
3919 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3920 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3921 return true;
3922 }
3923 }
3924 }
3925 }
3926 return false;
3927}
3928
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003929status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003930{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003931 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003932
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003933 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003934 if (patchDesc == 0) {
3935 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003936 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003937 return BAD_VALUE;
3938 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003939 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003940
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003941 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003942 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003943 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003944 if (status == NO_ERROR) {
3945 swOutputDesc->stop();
3946 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003947 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3948 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003949 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003950 if (hwOutputDesc != 0) {
3951 // release patch between src device and output device
3952 // close Hwoutput and remove from mHwOutputs
3953 } else {
3954 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3955 }
3956 }
3957 return NO_ERROR;
3958}
3959
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003960sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003961 audio_io_handle_t output, routing_strategy strategy)
3962{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003963 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003964 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003965 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3966 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003967 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003968 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003969 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3970 source = sourceDesc;
3971 break;
3972 }
3973 }
3974 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003975}
3976
Eric Laurente552edb2014-03-10 17:42:56 -07003977// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003978// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003979// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003980uint32_t AudioPolicyManager::nextAudioPortGeneration()
3981{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003982 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003983}
3984
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003985// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3986static const char *kConfigLocationList[] =
3987 {"/odm/etc", "/vendor/etc", "/system/etc"};
3988static const int kConfigLocationListSize =
3989 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3990
3991static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3992 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003993 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003994 status_t ret;
3995
Petri Gyntherf497f292018-04-17 18:46:10 -07003996 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3997 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3998 // A2DP offload supported but disabled: try to use special XML file
3999 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4000 }
4001 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4002
4003 for (const char* fileName : fileNames) {
4004 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004005 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4006 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004007 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004008 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004009 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004010 return ret;
4011 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004012 }
4013 }
4014 return ret;
4015}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004016
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004017AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4018 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004019 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004020 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004021 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004022 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004023 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004024 mVolumeCurves(new VolumeCurvesCollection()),
4025 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004026 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004027 mAudioPortGeneration(1),
4028 mBeaconMuteRefCount(0),
4029 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004030 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004031 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004032 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004033 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004034{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004035}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004036
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004037AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4038 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4039{
4040 loadConfig();
4041 initialize();
4042}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004043
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004044// This check is to catch any legacy platform updating to Q without having
4045// switched to XML since its deprecation on O.
4046// TODO: after Q release, remove this check and flag as XML is now the only
4047// option and all legacy platform should have transitioned to XML.
4048#ifndef USE_XML_AUDIO_POLICY_CONF
4049#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004050#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004051
4052void AudioPolicyManager::loadConfig() {
4053 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004054 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004055 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004056 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004057}
4058
4059status_t AudioPolicyManager::initialize() {
4060 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004061
4062 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004063 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4064 if (!engineInstance) {
4065 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004066 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004067 }
4068 // Retrieve the Policy Manager Interface
4069 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4070 if (mEngine == NULL) {
4071 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004072 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004073 }
4074 mEngine->setObserver(this);
4075 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004076 if (status != NO_ERROR) {
4077 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4078 return status;
4079 }
François Gaffie2110e042015-03-24 08:41:51 +01004080
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004082 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004083 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004084 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004085 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4086 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004087 continue;
4088 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004089 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004090 // open all output streams needed to access attached devices
4091 // except for direct output streams that are only opened when they are actually
4092 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004093 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004094 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004095 if (!outProfile->canOpenNewIo()) {
4096 ALOGE("Invalid Output profile max open count %u for profile %s",
4097 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4098 continue;
4099 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004100 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004101 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004102 continue;
4103 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004104 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004105 mTtsOutputAvailable = true;
4106 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004107
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004108 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004109 continue;
4110 }
François Gaffie11d30102018-11-02 16:09:09 +01004111 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4112 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4113 sp<DeviceDescriptor> supportedDevice = 0;
4114 if (supportedDevices.contains(mDefaultOutputDevice)) {
4115 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004116 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004117 // choose first device present in profile's SupportedDevices also part of
4118 // mAvailableOutputDevices.
4119 if (availProfileDevices.isEmpty()) {
4120 continue;
4121 }
4122 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004123 }
François Gaffie11d30102018-11-02 16:09:09 +01004124 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004125 continue;
4126 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004127 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4128 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004129 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004130 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4131 AUDIO_STREAM_DEFAULT,
4132 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004133 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004134 ALOGW("Cannot open output stream for devices %s on hw module %s",
4135 supportedDevice->toString().c_str(), hwModule->getName());
4136 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004137 }
François Gaffie11d30102018-11-02 16:09:09 +01004138 for (const auto &device : availProfileDevices) {
4139 // give a valid ID to an attached device once confirmed it is reachable
4140 if (!device->isAttached()) {
4141 device->attach(hwModule);
4142 }
4143 }
4144 if (mPrimaryOutput == 0 &&
4145 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4146 mPrimaryOutput = outputDesc;
4147 }
4148 addOutput(output, outputDesc);
4149 setOutputDevices(outputDesc,
4150 DeviceVector(supportedDevice),
4151 true,
4152 0,
4153 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004154 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004155 // open input streams needed to access attached devices to validate
4156 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004157 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004158 if (!inProfile->canOpenNewIo()) {
4159 ALOGE("Invalid Input profile max open count %u for profile %s",
4160 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4161 continue;
4162 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004163 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004164 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004165 continue;
4166 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004167 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004168 // available input devices
4169 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4170 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4171 if (availProfileDevices.isEmpty()) {
4172 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004173 continue;
4174 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004175 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004176 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004177
Eric Laurentd78f1532014-09-16 16:38:20 -07004178 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004179 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004180 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004181 AUDIO_SOURCE_MIC,
4182 AUDIO_INPUT_FLAG_NONE,
4183 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004184 if (status != NO_ERROR) {
4185 ALOGW("Cannot open input stream for device %s on hw module %s",
4186 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004187 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004188 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004189 }
François Gaffie11d30102018-11-02 16:09:09 +01004190 for (const auto &device : availProfileDevices) {
4191 // give a valid ID to an attached device once confirmed it is reachable
4192 if (!device->isAttached()) {
4193 device->attach(hwModule);
4194 device->importAudioPort(inProfile, true);
4195 }
4196 }
4197 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004198 }
4199 }
4200 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004201 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004202 for (size_t i = 0; i < devices.size();) {
4203 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004204 if (!device->isAttached()) {
4205 ALOGW("device %s is unreachable", device->toString().c_str());
4206 devices.remove(device);
4207 continue;
4208 }
4209 // Device is now validated and can be appended to the available devices of the engine
4210 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004211 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004212 }
François Gaffie11d30102018-11-02 16:09:09 +01004213 };
4214 checkAndSetAvailable(mAvailableOutputDevices);
4215 checkAndSetAvailable(mAvailableInputDevices);
4216
Eric Laurent3a4311c2014-03-17 12:00:47 -07004217 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004218 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4219 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4220 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004221 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004222 }
jiabin9ff780e2018-03-19 18:19:52 -07004223 // If microphones address is empty, set it according to device type
4224 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004225 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004226 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004227 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004228 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004229 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004230 }
4231 }
4232 }
Eric Laurente552edb2014-03-10 17:42:56 -07004233
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004234 if (mPrimaryOutput == 0) {
4235 ALOGE("Failed to open primary output");
4236 status = NO_INIT;
4237 }
Eric Laurente552edb2014-03-10 17:42:56 -07004238
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004239 // Silence ALOGV statements
4240 property_set("log.tag." LOG_TAG, "D");
4241
Eric Laurente552edb2014-03-10 17:42:56 -07004242 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004243 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004244}
4245
Eric Laurente0720872014-03-11 09:30:41 -07004246AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004247{
Eric Laurente552edb2014-03-10 17:42:56 -07004248 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004249 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004250 }
4251 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004252 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004253 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004254 mAvailableOutputDevices.clear();
4255 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004256 mOutputs.clear();
4257 mInputs.clear();
4258 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004259 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004260 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004261}
4262
Eric Laurente0720872014-03-11 09:30:41 -07004263status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004264{
Eric Laurent87ffa392015-05-22 10:32:38 -07004265 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004266}
4267
Eric Laurente552edb2014-03-10 17:42:56 -07004268// ---
4269
Eric Laurent98e38192018-02-15 18:31:53 -08004270void AudioPolicyManager::addOutput(audio_io_handle_t output,
4271 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004272{
Eric Laurent1c333e22014-05-20 10:48:17 -07004273 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004274 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004275 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004276 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004277 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004278}
4279
François Gaffie53615e22015-03-19 09:24:12 +01004280void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4281{
4282 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004283 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004284}
4285
Eric Laurent98e38192018-02-15 18:31:53 -08004286void AudioPolicyManager::addInput(audio_io_handle_t input,
4287 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004288{
Eric Laurent1c333e22014-05-20 10:48:17 -07004289 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004290 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004291}
Eric Laurente552edb2014-03-10 17:42:56 -07004292
François Gaffie11d30102018-11-02 16:09:09 +01004293status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004294 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004295 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004296{
François Gaffie11d30102018-11-02 16:09:09 +01004297 audio_devices_t deviceType = device->type();
4298 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004299 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004300
François Gaffie11d30102018-11-02 16:09:09 +01004301 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004302 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004303 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004304 }
Eric Laurente552edb2014-03-10 17:42:56 -07004305
Eric Laurent3b73df72014-03-11 09:06:29 -07004306 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004307 // first list already open outputs that can be routed to this device
4308 for (size_t i = 0; i < mOutputs.size(); i++) {
4309 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004310 if (!desc->isDuplicated() && desc->supportsDevice(device)
4311 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004312 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4313 mOutputs.keyAt(i), device->toString().c_str());
4314 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004315 }
4316 }
4317 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004318 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004319 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004320 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4321 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004322 if (profile->supportsDevice(device)) {
4323 profiles.add(profile);
4324 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4325 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004326 }
4327 }
4328 }
4329
Eric Laurent7b279bb2015-12-14 10:18:23 -08004330 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004331
Eric Laurente552edb2014-03-10 17:42:56 -07004332 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004333 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004334 return BAD_VALUE;
4335 }
4336
4337 // open outputs for matching profiles if needed. Direct outputs are also opened to
4338 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4339 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004340 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004341
4342 // nothing to do if one output is already opened for this profile
4343 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004344 for (j = 0; j < outputs.size(); j++) {
4345 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004346 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004347 // matching profile: save the sample rates, format and channel masks supported
4348 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004349 if (audio_device_is_digital(deviceType)) {
4350 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004351 }
Eric Laurente552edb2014-03-10 17:42:56 -07004352 break;
4353 }
4354 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004355 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004356 continue;
4357 }
4358
Eric Laurent3974e3b2017-12-07 17:58:43 -08004359 if (!profile->canOpenNewIo()) {
4360 ALOGW("Max Output number %u already opened for this profile %s",
4361 profile->maxOpenCount, profile->getTagName().c_str());
4362 continue;
4363 }
4364
Eric Laurent83efe1c2017-07-09 16:51:08 -07004365 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004366 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004367 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004368 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004369 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004370 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004371
Eric Laurentfe231122017-11-17 17:48:06 -08004372 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004373 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004374 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004375 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004376 mpClientInterface->setParameters(output, String8(param));
4377 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004378 }
François Gaffie11d30102018-11-02 16:09:09 +01004379 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004380 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004381 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004382 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004383 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004384 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004385 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004386 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004387 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4388 profile->pickAudioProfile(
4389 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004390 config.offload_info.sample_rate = config.sample_rate;
4391 config.offload_info.channel_mask = config.channel_mask;
4392 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004393
François Gaffie11d30102018-11-02 16:09:09 +01004394 status_t status = desc->open(&config, DeviceVector(device),
4395 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004396 AUDIO_OUTPUT_FLAG_NONE, &output);
4397 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004398 output = AUDIO_IO_HANDLE_NONE;
4399 }
Eric Laurentd4692962014-05-05 18:13:44 -07004400 }
4401
Eric Laurentcf2c0212014-07-25 16:20:43 -07004402 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004403 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004404 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004405 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004406 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4407 policyMix->setOutput(desc);
4408 desc->mPolicyMix = policyMix->getMix();
4409 } else {
4410 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004411 address.string());
4412 }
François Gaffie036e1e92015-03-19 10:16:24 +01004413
Eric Laurent87ffa392015-05-22 10:32:38 -07004414 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4415 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004416 // no duplicated output for direct outputs and
4417 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004418 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004419
Eric Laurentd4692962014-05-05 18:13:44 -07004420 //TODO: configure audio effect output stage here
4421
4422 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004423 sp<SwAudioOutputDescriptor> dupOutputDesc =
4424 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4425 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4426 &duplicatedOutput);
4427 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004428 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004429 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004430 } else {
4431 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004432 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004433 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004434 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004436 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004437 }
Eric Laurente552edb2014-03-10 17:42:56 -07004438 }
4439 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004440 } else {
4441 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004442 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004443 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004444 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004445 profiles.removeAt(profile_index);
4446 profile_index--;
4447 } else {
4448 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004449 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004450 if (audio_device_is_digital(deviceType)) {
4451 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004452 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004453
François Gaffie11d30102018-11-02 16:09:09 +01004454 if (device_distinguishes_on_address(deviceType)) {
4455 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4456 device->toString().c_str());
4457 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4458 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004459 }
Eric Laurente552edb2014-03-10 17:42:56 -07004460 ALOGV("checkOutputsForDevice(): adding output %d", output);
4461 }
4462 }
4463
4464 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004465 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004466 return BAD_VALUE;
4467 }
Eric Laurentd4692962014-05-05 18:13:44 -07004468 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004469 // check if one opened output is not needed any more after disconnecting one device
4470 for (size_t i = 0; i < mOutputs.size(); i++) {
4471 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004472 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004473 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004474 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4475 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004476 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004477 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004478 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4479 mOutputs.keyAt(i));
4480 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004481 }
Eric Laurente552edb2014-03-10 17:42:56 -07004482 }
4483 }
Eric Laurentd4692962014-05-05 18:13:44 -07004484 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004485 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004486 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4487 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004488 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004489 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004490 "clearing direct output profile %zu on module %s",
4491 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004492 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004493 }
4494 }
4495 }
4496 }
4497 return NO_ERROR;
4498}
4499
François Gaffie11d30102018-11-02 16:09:09 +01004500status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004501 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004502 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004503{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004504 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004505
François Gaffie11d30102018-11-02 16:09:09 +01004506 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004507 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004508 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004509 }
4510
Eric Laurentd4692962014-05-05 18:13:44 -07004511 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4512 // first list already open inputs that can be routed to this device
4513 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4514 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004515 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004516 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4517 inputs.add(mInputs.keyAt(input_index));
4518 }
4519 }
4520
4521 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004522 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004523 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004524 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004525 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004526 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004527 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004528
François Gaffie11d30102018-11-02 16:09:09 +01004529 if (profile->supportsDevice(device)) {
4530 profiles.add(profile);
4531 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4532 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004533 }
4534 }
4535 }
4536
4537 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004538 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004539 return BAD_VALUE;
4540 }
4541
4542 // open inputs for matching profiles if needed. Direct inputs are also opened to
4543 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4544 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4545
Eric Laurent1c333e22014-05-20 10:48:17 -07004546 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004547
Eric Laurentd4692962014-05-05 18:13:44 -07004548 // nothing to do if one input is already opened for this profile
4549 size_t input_index;
4550 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4551 desc = mInputs.valueAt(input_index);
4552 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004553 if (audio_device_is_digital(device->type())) {
4554 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004555 }
Eric Laurentd4692962014-05-05 18:13:44 -07004556 break;
4557 }
4558 }
4559 if (input_index != mInputs.size()) {
4560 continue;
4561 }
4562
Eric Laurent3974e3b2017-12-07 17:58:43 -08004563 if (!profile->canOpenNewIo()) {
4564 ALOGW("Max Input number %u already opened for this profile %s",
4565 profile->maxOpenCount, profile->getTagName().c_str());
4566 continue;
4567 }
4568
Eric Laurentfe231122017-11-17 17:48:06 -08004569 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004570 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004571 status_t status = desc->open(nullptr,
4572 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004573 AUDIO_SOURCE_MIC,
4574 AUDIO_INPUT_FLAG_NONE,
4575 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004576
Eric Laurentcf2c0212014-07-25 16:20:43 -07004577 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004578 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004579 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004580 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004581 mpClientInterface->setParameters(input, String8(param));
4582 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004583 }
François Gaffie11d30102018-11-02 16:09:09 +01004584 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004585 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004586 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004587 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004588 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004589 }
4590
4591 if (input != 0) {
4592 addInput(input, desc);
4593 }
4594 } // endif input != 0
4595
Eric Laurentcf2c0212014-07-25 16:20:43 -07004596 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004597 ALOGW("%s could not open input for device %s", __func__,
4598 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004599 profiles.removeAt(profile_index);
4600 profile_index--;
4601 } else {
4602 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004603 if (audio_device_is_digital(device->type())) {
4604 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004605 }
Eric Laurentd4692962014-05-05 18:13:44 -07004606 ALOGV("checkInputsForDevice(): adding input %d", input);
4607 }
4608 } // end scan profiles
4609
4610 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004611 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004612 return BAD_VALUE;
4613 }
4614 } else {
4615 // Disconnect
4616 // check if one opened input is not needed any more after disconnecting one device
4617 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4618 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004619 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004620 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4621 mInputs.keyAt(input_index));
4622 inputs.add(mInputs.keyAt(input_index));
4623 }
4624 }
4625 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004626 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004627 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004628 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004629 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004630 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004631 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004632 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4633 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004634 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004635 }
4636 }
4637 }
4638 } // end disconnect
4639
4640 return NO_ERROR;
4641}
4642
4643
Eric Laurente0720872014-03-11 09:30:41 -07004644void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004645{
4646 ALOGV("closeOutput(%d)", output);
4647
Eric Laurentc75307b2015-03-17 15:29:32 -07004648 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004649 if (outputDesc == NULL) {
4650 ALOGW("closeOutput() unknown output %d", output);
4651 return;
4652 }
François Gaffie036e1e92015-03-19 10:16:24 +01004653 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004654
Eric Laurente552edb2014-03-10 17:42:56 -07004655 // look for duplicated outputs connected to the output being removed.
4656 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004657 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004658 if (dupOutputDesc->isDuplicated() &&
4659 (dupOutputDesc->mOutput1 == outputDesc ||
4660 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004661 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004662 if (dupOutputDesc->mOutput1 == outputDesc) {
4663 outputDesc2 = dupOutputDesc->mOutput2;
4664 } else {
4665 outputDesc2 = dupOutputDesc->mOutput1;
4666 }
4667 // As all active tracks on duplicated output will be deleted,
4668 // and as they were also referenced on the other output, the reference
4669 // count for their stream type must be adjusted accordingly on
4670 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004671 const bool wasActive = outputDesc2->isActive();
4672 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4673 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004674 }
Eric Laurent733ce942017-12-07 12:18:25 -08004675 // stop() will be a no op if the output is still active but is needed in case all
4676 // active streams refcounts where cleared above
4677 if (wasActive) {
4678 outputDesc2->stop();
4679 }
Eric Laurente552edb2014-03-10 17:42:56 -07004680 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4681 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4682
4683 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004684 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004685 }
4686 }
4687
Eric Laurent05b90f82014-08-27 15:32:29 -07004688 nextAudioPortGeneration();
4689
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004690 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004691 if (index >= 0) {
4692 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004693 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004694 mAudioPatches.removeItemsAt(index);
4695 mpClientInterface->onAudioPatchListUpdate();
4696 }
4697
Eric Laurentfe231122017-11-17 17:48:06 -08004698 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004699
François Gaffie53615e22015-03-19 09:24:12 +01004700 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004701 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004702
4703 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4704 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004705 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004706 bool directOutputOpen = false;
4707 for (size_t i = 0; i < mOutputs.size(); i++) {
4708 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4709 directOutputOpen = true;
4710 break;
4711 }
4712 }
4713 if (!directOutputOpen) {
4714 ALOGV("no direct outputs open, reset MSD patch");
4715 setMsdPatch();
4716 }
4717 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004718}
4719
4720void AudioPolicyManager::closeInput(audio_io_handle_t input)
4721{
4722 ALOGV("closeInput(%d)", input);
4723
4724 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4725 if (inputDesc == NULL) {
4726 ALOGW("closeInput() unknown input %d", input);
4727 return;
4728 }
4729
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004731
François Gaffie11d30102018-11-02 16:09:09 +01004732 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004733 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004734 if (index >= 0) {
4735 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004736 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004737 mAudioPatches.removeItemsAt(index);
4738 mpClientInterface->onAudioPatchListUpdate();
4739 }
4740
Eric Laurentfe231122017-11-17 17:48:06 -08004741 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004742 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004743
François Gaffie11d30102018-11-02 16:09:09 +01004744 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4745 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004746 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4747 SoundTrigger::setCaptureState(false);
4748 }
Eric Laurente552edb2014-03-10 17:42:56 -07004749}
4750
François Gaffie11d30102018-11-02 16:09:09 +01004751SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4752 const DeviceVector &devices,
4753 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004754{
4755 SortedVector<audio_io_handle_t> outputs;
4756
François Gaffie11d30102018-11-02 16:09:09 +01004757 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004758 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004759 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004760 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004761 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004762 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4763 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004764 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004765 outputs.add(openOutputs.keyAt(i));
4766 }
4767 }
4768 return outputs;
4769}
4770
Mikhail Naganov37977152018-07-11 15:54:44 -07004771void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4772{
4773 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4774 // output is suspended before any tracks are moved to it
4775 checkA2dpSuspend();
4776 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004777 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004778 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004779 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004780 setMsdPatch();
4781 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004782}
4783
Eric Laurente0720872014-03-11 09:30:41 -07004784void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004785{
François Gaffie11d30102018-11-02 16:09:09 +01004786 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4787 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4788 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4789 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004790
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004791 // also take into account external policy-related changes: add all outputs which are
4792 // associated with policies in the "before" and "after" output vectors
4793 ALOGVV("checkOutputForStrategy(): policy related outputs");
4794 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004795 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004796 if (desc != 0 && desc->mPolicyMix != NULL) {
4797 srcOutputs.add(desc->mIoHandle);
4798 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4799 }
4800 }
4801 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004802 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004803 if (desc != 0 && desc->mPolicyMix != NULL) {
4804 dstOutputs.add(desc->mIoHandle);
4805 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4806 }
4807 }
4808
Francois Gaffie716e1432019-01-14 16:58:59 +01004809 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004810 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4811 // audio from invalidated tracks will be rendered when unmuting
4812 uint32_t maxLatency = 0;
4813 for (audio_io_handle_t srcOut : srcOutputs) {
4814 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4815 if (desc != 0 && maxLatency < desc->latency()) {
4816 maxLatency = desc->latency();
4817 }
4818 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004819 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
4820 "%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4821 std::to_string(srcOutputs[0]).c_str(),
4822 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004823 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004824 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004825 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4826 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004827 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004828 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4829 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004830 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004831 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004832 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004833 if (source != 0){
4834 connectAudioSource(source);
4835 }
Eric Laurente552edb2014-03-10 17:42:56 -07004836 }
4837
4838 // Move effects associated to this strategy from previous output to new output
4839 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004840 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004841 }
4842 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004843 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004844 if (getStrategy((audio_stream_type_t)i) == strategy) {
4845 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004846 }
4847 }
4848 }
4849}
4850
Eric Laurente0720872014-03-11 09:30:41 -07004851void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004852{
François Gaffie2110e042015-03-24 08:41:51 +01004853 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004854 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004855 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004856 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004857 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004858 checkOutputForStrategy(STRATEGY_SONIFICATION);
4859 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004860 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004861 checkOutputForStrategy(STRATEGY_MEDIA);
4862 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004863 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004864}
4865
Eric Laurente0720872014-03-11 09:30:41 -07004866void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004867{
François Gaffie53615e22015-03-19 09:24:12 +01004868 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004869 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004870 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004871 return;
4872 }
4873
Eric Laurent3a4311c2014-03-17 12:00:47 -07004874 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004875 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4876 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4877 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004878
4879 // if suspended, restore A2DP output if:
4880 // ((SCO device is NOT connected) ||
4881 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4882 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004883 //
Eric Laurentf732e072016-08-03 19:30:28 -07004884 // if not suspended, suspend A2DP output if:
4885 // (SCO device is connected) &&
4886 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4887 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004888 //
4889 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004890 if (!isScoConnected ||
4891 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4892 AUDIO_POLICY_FORCE_BT_SCO) &&
4893 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4894 AUDIO_POLICY_FORCE_BT_SCO) &&
4895 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004896 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004897
4898 mpClientInterface->restoreOutput(a2dpOutput);
4899 mA2dpSuspended = false;
4900 }
4901 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004902 if (isScoConnected &&
4903 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4904 AUDIO_POLICY_FORCE_BT_SCO) ||
4905 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4906 AUDIO_POLICY_FORCE_BT_SCO) ||
4907 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004908 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004909
4910 mpClientInterface->suspendOutput(a2dpOutput);
4911 mA2dpSuspended = true;
4912 }
4913 }
4914}
4915
Eric Laurent97ac8712018-07-27 18:59:02 -07004916template <class IoDescriptor, class Filter>
4917sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4918 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4919{
4920 auto activeClients = desc->clientsList(true /*activeOnly*/);
4921 auto activeClientsWithRoute =
4922 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4923 active = activeClients.size() > 0;
4924 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4925 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4926 }
4927 return nullptr;
4928}
4929
4930template <class IoCollection, class Filter>
4931sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4932 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4933{
4934 sp<DeviceDescriptor> device;
4935 for (size_t i = 0; i < ioCollection.size(); i++) {
4936 auto desc = ioCollection.valueAt(i);
4937 bool active;
4938 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4939 if (active && curDevice == nullptr) {
4940 return nullptr;
4941 } else if (curDevice != nullptr) {
4942 device = curDevice;
4943 }
4944 }
4945 return device;
4946}
4947
François Gaffie11d30102018-11-02 16:09:09 +01004948DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4949 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004950{
François Gaffie11d30102018-11-02 16:09:09 +01004951 DeviceVector devices;
4952
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004953 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 if (index >= 0) {
4955 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4956 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004957 ALOGV("%s device %s forced by patch %d", __func__,
4958 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4959 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 }
4961 }
4962
Eric Laurent97ac8712018-07-27 18:59:02 -07004963 // Honor explicit routing requests only if no client using default routing is active on this
4964 // input: a specific app can not force routing for other apps by setting a preferred device.
4965 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004966 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004967 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004968 if (device != nullptr) {
4969 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004970 }
4971
Eric Laurente552edb2014-03-10 17:42:56 -07004972 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004973 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004974 // use device for strategy enforced audible
4975 // 2: we are in call or the strategy phone is active on the output:
4976 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004977 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004978 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004979 // 4: the strategy for enforced audible is active but not enforced on the output:
4980 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004981 // 5: the strategy accessibility is active on the output:
4982 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004983 // 6: the strategy "respectful" sonification is active on the output:
4984 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004985 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004986 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004987 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004988 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004989 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004990 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004991
4992 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4993 // with a refined rule considering mutually exclusive devices (using same backend)
4994 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004995 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004996 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01004997 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004998 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004999 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005000 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08005001 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01005002 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07005003 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005004 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08005005 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01005006 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005007 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01005008 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005009 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01005010 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005011 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01005012 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005013 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01005014 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005015 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01005016 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005017 }
5018
François Gaffie11d30102018-11-02 16:09:09 +01005019 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
5020 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005021}
5022
François Gaffie11d30102018-11-02 16:09:09 +01005023sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5024 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005025{
François Gaffie11d30102018-11-02 16:09:09 +01005026 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005027
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005028 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 if (index >= 0) {
5030 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5031 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005032 ALOGV("getNewInputDevice() device %s forced by patch %d",
5033 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5034 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 }
5036 }
5037
Eric Laurent97ac8712018-07-27 18:59:02 -07005038 // Honor explicit routing requests only if no client using default routing is active on this
5039 // input: a specific app can not force routing for other apps by setting a preferred device.
5040 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005041 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5042 if (device != nullptr) {
5043 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005044 }
5045
Eric Laurentdc95a252018-04-12 12:46:56 -07005046 // If we are not in call and no client is active on this input, this methods returns
5047 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005048 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5049 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5050 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005051 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005052 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
5053 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005054 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005055
Eric Laurente552edb2014-03-10 17:42:56 -07005056 return device;
5057}
5058
Eric Laurent794fde22016-03-11 09:50:45 -08005059bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5060 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005061 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005062}
5063
Eric Laurente0720872014-03-11 09:30:41 -07005064uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005065 return (uint32_t)getStrategy(stream);
5066}
5067
Eric Laurente0720872014-03-11 09:30:41 -07005068audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005069 // By checking the range of stream before calling getStrategy, we avoid
5070 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5071 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005072 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 return AUDIO_DEVICE_NONE;
5074 }
François Gaffie11d30102018-11-02 16:09:09 +01005075 DeviceVector activeDevices;
5076 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08005077 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5078 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005079 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005080 }
Eric Laurent794fde22016-03-11 09:50:45 -08005081 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01005082 DeviceVector curDevices =
5083 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
5084 devices.merge(curDevices);
5085 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005086 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005087 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005088 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005089 }
5090 }
Eric Laurente552edb2014-03-10 17:42:56 -07005091 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005092
Eric Laurentb0688d62018-08-14 15:49:18 -07005093 // Favor devices selected on active streams if any to report correct device in case of
5094 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005095 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005096 devices = activeDevices;
5097 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005098 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5099 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005100 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5101 if (!speakerSafeDevices.isEmpty()) {
5102 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5103 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005104 }
François Gaffie11d30102018-11-02 16:09:09 +01005105 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005106}
5107
François Gaffie2110e042015-03-24 08:41:51 +01005108routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5109{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005110 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005111 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005112}
5113
Eric Laurent97ac8712018-07-27 18:59:02 -07005114routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005115 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005116 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005117 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005118 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005119 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005120 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005121 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005122 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005123 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005124}
5125
Eric Laurente0720872014-03-11 09:30:41 -07005126void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005127 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005128 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005129 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5130 updateDevicesAndOutputs();
5131 break;
5132 default:
5133 break;
5134 }
5135}
5136
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005137uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005138
5139 // skip beacon mute management if a dedicated TTS output is available
5140 if (mTtsOutputAvailable) {
5141 return 0;
5142 }
5143
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005144 switch(event) {
5145 case STARTING_OUTPUT:
5146 mBeaconMuteRefCount++;
5147 break;
5148 case STOPPING_OUTPUT:
5149 if (mBeaconMuteRefCount > 0) {
5150 mBeaconMuteRefCount--;
5151 }
5152 break;
5153 case STARTING_BEACON:
5154 mBeaconPlayingRefCount++;
5155 break;
5156 case STOPPING_BEACON:
5157 if (mBeaconPlayingRefCount > 0) {
5158 mBeaconPlayingRefCount--;
5159 }
5160 break;
5161 }
5162
5163 if (mBeaconMuteRefCount > 0) {
5164 // any playback causes beacon to be muted
5165 return setBeaconMute(true);
5166 } else {
5167 // no other playback: unmute when beacon starts playing, mute when it stops
5168 return setBeaconMute(mBeaconPlayingRefCount == 0);
5169 }
5170}
5171
5172uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5173 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5174 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5175 // keep track of muted state to avoid repeating mute/unmute operations
5176 if (mBeaconMuted != mute) {
5177 // mute/unmute AUDIO_STREAM_TTS on all outputs
5178 ALOGV("\t muting %d", mute);
5179 uint32_t maxLatency = 0;
5180 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005181 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005182 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005183 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005184 0 /*delay*/, AUDIO_DEVICE_NONE);
5185 const uint32_t latency = desc->latency() * 2;
5186 if (latency > maxLatency) {
5187 maxLatency = latency;
5188 }
5189 }
5190 mBeaconMuted = mute;
5191 return maxLatency;
5192 }
5193 return 0;
5194}
5195
François Gaffie11d30102018-11-02 16:09:09 +01005196DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005197{
Eric Laurent97ac8712018-07-27 18:59:02 -07005198 // Honor explicit routing requests only if all active clients have a preferred route in which
5199 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005200 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5201 if (device != nullptr) {
5202 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005203 }
5204
Eric Laurente552edb2014-03-10 17:42:56 -07005205 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005206 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5207 mDevicesForStrategy[strategy].toString().c_str());
5208 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005209 }
François Gaffie11d30102018-11-02 16:09:09 +01005210 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005211}
5212
Eric Laurente0720872014-03-11 09:30:41 -07005213void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005214{
5215 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005216 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005217 }
5218 mPreviousOutputs = mOutputs;
5219}
5220
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005221uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005222 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005223 uint32_t delayMs)
5224{
5225 // mute/unmute strategies using an incompatible device combination
5226 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5227 // if unmuting, unmute only after the specified delay
5228 if (outputDesc->isDuplicated()) {
5229 return 0;
5230 }
5231
5232 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005233 audio_devices_t deviceType = outputDesc->devices().types();
5234 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005235
5236 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005237 audio_devices_t curDeviceType =
5238 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5239 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5240 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005241 bool doMute = false;
5242
5243 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5244 doMute = true;
5245 outputDesc->mStrategyMutedByDevice[i] = true;
5246 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5247 doMute = true;
5248 outputDesc->mStrategyMutedByDevice[i] = false;
5249 }
Eric Laurent99401132014-05-07 19:48:15 -07005250 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005251 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005252 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005253 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005254 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005255 continue;
5256 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005257 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005258 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005259 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005260 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005261 if (mute) {
5262 // FIXME: should not need to double latency if volume could be applied
5263 // immediately by the audioflinger mixer. We must account for the delay
5264 // between now and the next time the audioflinger thread for this output
5265 // will process a buffer (which corresponds to one buffer size,
5266 // usually 1/2 or 1/4 of the latency).
5267 if (muteWaitMs < desc->latency() * 2) {
5268 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005269 }
5270 }
5271 }
5272 }
5273 }
5274 }
5275
Eric Laurent99401132014-05-07 19:48:15 -07005276 // temporary mute output if device selection changes to avoid volume bursts due to
5277 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005278 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005279 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5280 // temporary mute duration is conservatively set to 4 times the reported latency
5281 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5282 if (muteWaitMs < tempMuteWaitMs) {
5283 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005284 }
Eric Laurentdc462862016-07-19 12:29:53 -07005285
Eric Laurent99401132014-05-07 19:48:15 -07005286 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005287 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005288 // make sure that we do not start the temporary mute period too early in case of
5289 // delayed device change
5290 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005291 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005292 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005293 }
5294 }
5295 }
5296
Eric Laurente552edb2014-03-10 17:42:56 -07005297 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5298 if (muteWaitMs > delayMs) {
5299 muteWaitMs -= delayMs;
5300 usleep(muteWaitMs * 1000);
5301 return muteWaitMs;
5302 }
5303 return 0;
5304}
5305
François Gaffie11d30102018-11-02 16:09:09 +01005306uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5307 const DeviceVector &devices,
5308 bool force,
5309 int delayMs,
5310 audio_patch_handle_t *patchHandle,
5311 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005312{
François Gaffie11d30102018-11-02 16:09:09 +01005313 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005314 uint32_t muteWaitMs;
5315
5316 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005317 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5318 nullptr /* patchHandle */, requiresMuteCheck);
5319 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5320 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005321 return muteWaitMs;
5322 }
Eric Laurente552edb2014-03-10 17:42:56 -07005323
5324 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005325 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005326
François Gaffie11d30102018-11-02 16:09:09 +01005327 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5328 // output profile
5329 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5330 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5331 return 0;
5332 }
Eric Laurente552edb2014-03-10 17:42:56 -07005333
François Gaffie11d30102018-11-02 16:09:09 +01005334 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005335
François Gaffie11d30102018-11-02 16:09:09 +01005336 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5337
5338 if (!filteredDevices.isEmpty()) {
5339 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005340 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005341
5342 // if the outputs are not materially active, there is no need to mute.
5343 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005344 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005345 } else {
5346 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5347 muteWaitMs = 0;
5348 }
Eric Laurente552edb2014-03-10 17:42:56 -07005349
5350 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005351 // the requested device is AUDIO_DEVICE_NONE
5352 // OR the requested device is the same as current device
5353 // AND force is not specified
5354 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005355 // Doing this check here allows the caller to call setOutputDevices() without conditions
5356 if ((!filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5357 !force && outputDesc->getPatchHandle() != 0) {
5358 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5359 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005360 return muteWaitMs;
5361 }
5362
François Gaffie11d30102018-11-02 16:09:09 +01005363 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005364
Eric Laurente552edb2014-03-10 17:42:56 -07005365 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005366 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005367 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005368 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005369 PatchBuilder patchBuilder;
5370 patchBuilder.addSource(outputDesc);
5371 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5372 for (const auto &filteredDevice : filteredDevices) {
5373 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005374 }
5375
François Gaffie11d30102018-11-02 16:09:09 +01005376 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005377 }
Eric Laurente552edb2014-03-10 17:42:56 -07005378
5379 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005380 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005381
5382 return muteWaitMs;
5383}
5384
Eric Laurentc75307b2015-03-17 15:29:32 -07005385status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005386 int delayMs,
5387 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005388{
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 ssize_t index;
5390 if (patchHandle) {
5391 index = mAudioPatches.indexOfKey(*patchHandle);
5392 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005393 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005394 }
5395 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005396 return INVALID_OPERATION;
5397 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005398 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5399 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005400 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005401 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005402 removeAudioPatch(patchDesc->mHandle);
5403 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005404 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005405 return status;
5406}
5407
5408status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005409 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005410 bool force,
5411 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005412{
5413 status_t status = NO_ERROR;
5414
Eric Laurent1f2f2232014-06-02 12:01:23 -07005415 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005416 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5417 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005418
François Gaffie11d30102018-11-02 16:09:09 +01005419 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005420 PatchBuilder patchBuilder;
5421 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005422 // AUDIO_SOURCE_HOTWORD is for internal use only:
5423 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005424 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5425 auto result = usecase;
5426 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5427 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5428 }
5429 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005430 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005431 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005432 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005433 }
5434 }
5435 return status;
5436}
5437
Eric Laurent6a94d692014-05-20 11:18:06 -07005438status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5439 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005440{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005441 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 ssize_t index;
5443 if (patchHandle) {
5444 index = mAudioPatches.indexOfKey(*patchHandle);
5445 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005446 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005447 }
5448 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005449 return INVALID_OPERATION;
5450 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005451 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5452 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005453 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005454 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005455 removeAudioPatch(patchDesc->mHandle);
5456 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005457 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005458 return status;
5459}
5460
François Gaffie11d30102018-11-02 16:09:09 +01005461sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005462 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005463 audio_format_t& format,
5464 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005465 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005466{
5467 // Choose an input profile based on the requested capture parameters: select the first available
5468 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005469 //
5470 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5471 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005472
Glenn Kasten730b9262018-03-29 15:01:26 -07005473 sp<IOProfile> firstInexact;
5474 uint32_t updatedSamplingRate = 0;
5475 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5476 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005477 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005478 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005479 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005480 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005481 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005482 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005483 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005484 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005485 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005486 &channelMask /*updatedChannelMask*/,
5487 // FIXME ugly cast
5488 (audio_output_flags_t) flags,
5489 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005490 return profile;
5491 }
François Gaffie11d30102018-11-02 16:09:09 +01005492 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005493 samplingRate,
5494 &updatedSamplingRate,
5495 format,
5496 &updatedFormat,
5497 channelMask,
5498 &updatedChannelMask,
5499 // FIXME ugly cast
5500 (audio_output_flags_t) flags,
5501 false /*exactMatchRequiredForInputFlags*/)) {
5502 firstInexact = profile;
5503 }
5504
Eric Laurente552edb2014-03-10 17:42:56 -07005505 }
5506 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005507 if (firstInexact != nullptr) {
5508 samplingRate = updatedSamplingRate;
5509 format = updatedFormat;
5510 channelMask = updatedChannelMask;
5511 return firstInexact;
5512 }
Eric Laurente552edb2014-03-10 17:42:56 -07005513 return NULL;
5514}
5515
Francois Gaffie716e1432019-01-14 16:58:59 +01005516sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5517 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005518{
Eric Laurent97ac8712018-07-27 18:59:02 -07005519 // Honor explicit routing requests only if all active clients have a preferred route in which
5520 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005521 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005522 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005523 if (device != nullptr) {
5524 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005525 }
5526
François Gaffie11d30102018-11-02 16:09:09 +01005527 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005528 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005529 policyMix);
5530 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005531 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005532}
5533
Francois Gaffie716e1432019-01-14 16:58:59 +01005534sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005535{
Francois Gaffie716e1432019-01-14 16:58:59 +01005536 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5537 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5538 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5539 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005540 String8(attributes.tags + strlen("addr=")),
5541 AUDIO_FORMAT_DEFAULT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005542 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005543 return mAvailableInputDevices.getDevice(device, String8(), AUDIO_FORMAT_DEFAULT);
Eric Laurente552edb2014-03-10 17:42:56 -07005544}
5545
Eric Laurente0720872014-03-11 09:30:41 -07005546float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005547 int index,
5548 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005549{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005550 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005551
5552 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5553 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5554 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5555 // the ringtone volume
5556 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5557 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5558 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5559 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5560 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5561 }
5562
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005563 // in-call: always cap volume by voice volume + some low headroom
5564 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005565 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005566 switch (stream) {
5567 case AUDIO_STREAM_SYSTEM:
5568 case AUDIO_STREAM_RING:
5569 case AUDIO_STREAM_MUSIC:
5570 case AUDIO_STREAM_ALARM:
5571 case AUDIO_STREAM_NOTIFICATION:
5572 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5573 case AUDIO_STREAM_DTMF:
5574 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005575 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005576 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005577 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005578 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005579 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005580 if (volumeDB > maxVoiceVolDb) {
5581 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5582 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5583 volumeDB = maxVoiceVolDb;
5584 }
5585 } break;
5586 default:
5587 break;
5588 }
5589 }
5590
Eric Laurente552edb2014-03-10 17:42:56 -07005591 // if a headset is connected, apply the following rules to ring tones and notifications
5592 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005593 // - always attenuate notifications volume by 6dB
5594 // - attenuate ring tones volume by 6dB unless music is not playing and
5595 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005596 // - if music is playing, always limit the volume to current music volume,
5597 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005598 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005599 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5600 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5601 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005602 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005603 AUDIO_DEVICE_OUT_USB_HEADSET |
5604 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005605 ((stream_strategy == STRATEGY_SONIFICATION)
5606 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005607 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005608 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005609 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005610 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005611 // when the phone is ringing we must consider that music could have been paused just before
5612 // by the music application and behave as if music was active if the last music track was
5613 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005614 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005615 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005616 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005617 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005618 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005619 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5620 musicDevice),
5621 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005622 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5623 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005624 if (volumeDB > minVolDB) {
5625 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005626 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005627 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005628 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5629 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5630 // on A2DP, also ensure notification volume is not too low compared to media when
5631 // intended to be played
5632 if ((volumeDB > -96.0f) &&
5633 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5634 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5635 stream, device,
5636 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5637 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5638 }
5639 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005640 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5641 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005642 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005643 }
5644 }
5645
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005646 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005647}
5648
Eric Laurent3839bc02018-07-10 18:33:34 -07005649int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5650 audio_stream_type_t srcStream,
5651 audio_stream_type_t dstStream)
5652{
5653 if (srcStream == dstStream) {
5654 return srcIndex;
5655 }
5656 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5657 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5658 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5659 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5660
5661 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5662}
5663
Eric Laurente0720872014-03-11 09:30:41 -07005664status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005665 int index,
5666 const sp<AudioOutputDescriptor>& outputDesc,
5667 audio_devices_t device,
5668 int delayMs,
5669 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005670{
Eric Laurente552edb2014-03-10 17:42:56 -07005671 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005672 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005673 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005674 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005675 return NO_ERROR;
5676 }
François Gaffie2110e042015-03-24 08:41:51 +01005677 audio_policy_forced_cfg_t forceUseForComm =
5678 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005679 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005680 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5681 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005682 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005683 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005684 return INVALID_OPERATION;
5685 }
5686
Eric Laurentc75307b2015-03-17 15:29:32 -07005687 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005688 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005689 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005690
Eric Laurentffbc80f2015-03-18 18:30:19 -07005691 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005692 if (outputDesc->isFixedVolume(device) ||
5693 // Force VoIP volume to max for bluetooth SCO
5694 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5695 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005696 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005697 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005698
Eric Laurentffbc80f2015-03-18 18:30:19 -07005699 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005700
Eric Laurent3b73df72014-03-11 09:06:29 -07005701 if (stream == AUDIO_STREAM_VOICE_CALL ||
5702 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005703 float voiceVolume;
5704 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005705 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005706 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005707 } else {
5708 voiceVolume = 1.0;
5709 }
5710
Eric Laurent18fba842016-03-31 14:41:26 -07005711 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005712 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5713 mLastVoiceVolume = voiceVolume;
5714 }
5715 }
5716
5717 return NO_ERROR;
5718}
5719
Eric Laurentc75307b2015-03-17 15:29:32 -07005720void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5721 audio_devices_t device,
5722 int delayMs,
5723 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005724{
Eric Laurentc75307b2015-03-17 15:29:32 -07005725 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005726
Eric Laurent794fde22016-03-11 09:50:45 -08005727 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005728 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005729 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005730 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005731 device,
5732 delayMs,
5733 force);
5734 }
5735}
5736
Eric Laurente0720872014-03-11 09:30:41 -07005737void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005738 bool on,
5739 const sp<AudioOutputDescriptor>& outputDesc,
5740 int delayMs,
5741 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005742{
Eric Laurent72249d52015-06-08 11:12:15 -07005743 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5744 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005745 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005746 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005747 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005748 }
5749 }
5750}
5751
Eric Laurente0720872014-03-11 09:30:41 -07005752void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005753 bool on,
5754 const sp<AudioOutputDescriptor>& outputDesc,
5755 int delayMs,
5756 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005757{
Eric Laurente552edb2014-03-10 17:42:56 -07005758 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005759 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005760 }
5761
Eric Laurentc75307b2015-03-17 15:29:32 -07005762 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5763 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005764
5765 if (on) {
5766 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005767 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005768 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005769 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005770 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005771 }
5772 }
5773 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5774 outputDesc->mMuteCount[stream]++;
5775 } else {
5776 if (outputDesc->mMuteCount[stream] == 0) {
5777 ALOGV("setStreamMute() unmuting non muted stream!");
5778 return;
5779 }
5780 if (--outputDesc->mMuteCount[stream] == 0) {
5781 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005782 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005783 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005784 device,
5785 delayMs);
5786 }
5787 }
5788}
5789
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005790audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5791{
5792 // flags to stream type mapping
5793 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5794 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5795 }
5796 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5797 return AUDIO_STREAM_BLUETOOTH_SCO;
5798 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005799 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5800 return AUDIO_STREAM_TTS;
5801 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005802
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005803 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005804}
Eric Laurente83b55d2014-11-14 10:06:21 -08005805
François Gaffie53615e22015-03-19 09:24:12 +01005806bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5807{
Eric Laurente83b55d2014-11-14 10:06:21 -08005808 // has flags that map to a strategy?
5809 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5810 return true;
5811 }
5812
5813 // has known usage?
5814 switch (paa->usage) {
5815 case AUDIO_USAGE_UNKNOWN:
5816 case AUDIO_USAGE_MEDIA:
5817 case AUDIO_USAGE_VOICE_COMMUNICATION:
5818 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5819 case AUDIO_USAGE_ALARM:
5820 case AUDIO_USAGE_NOTIFICATION:
5821 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5822 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5823 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5824 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5825 case AUDIO_USAGE_NOTIFICATION_EVENT:
5826 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5827 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5828 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5829 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005830 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005831 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005832 break;
5833 default:
5834 return false;
5835 }
5836 return true;
5837}
5838
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005839bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005840 routing_strategy strategy, uint32_t inPastMs,
5841 nsecs_t sysTime) const
5842{
5843 if ((sysTime == 0) && (inPastMs != 0)) {
5844 sysTime = systemTime();
5845 }
Eric Laurent794fde22016-03-11 09:50:45 -08005846 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005847 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005848 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005849 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5850 return true;
5851 }
5852 }
5853 return false;
5854}
5855
François Gaffie11d30102018-11-02 16:09:09 +01005856bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5857 routing_strategy strategy, uint32_t inPastMs,
5858 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005859{
5860 for (size_t i = 0; i < mOutputs.size(); i++) {
5861 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5862 if (outputDesc->sharesHwModuleWith(desc)
5863 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5864 return true;
5865 }
5866 }
5867 return false;
5868}
5869
François Gaffie2110e042015-03-24 08:41:51 +01005870audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5871{
5872 return mEngine->getForceUse(usage);
5873}
5874
5875bool AudioPolicyManager::isInCall()
5876{
5877 return isStateInCall(mEngine->getPhoneState());
5878}
5879
5880bool AudioPolicyManager::isStateInCall(int state)
5881{
5882 return is_state_in_call(state);
5883}
5884
Eric Laurentd60560a2015-04-10 11:31:20 -07005885void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5886{
5887 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005888 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5889 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5890 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5891 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005892 }
5893 }
5894
5895 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5896 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5897 bool release = false;
5898 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5899 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5900 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5901 source->ext.device.type == deviceDesc->type()) {
5902 release = true;
5903 }
5904 }
5905 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5906 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5907 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5908 sink->ext.device.type == deviceDesc->type()) {
5909 release = true;
5910 }
5911 }
5912 if (release) {
5913 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5914 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5915 }
5916 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005917
5918 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005919}
5920
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005921void AudioPolicyManager::modifySurroundFormats(
5922 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005923 std::unordered_set<audio_format_t> enforcedSurround(
5924 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005925 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5926 for (const auto& pair : mConfig.getSurroundFormats()) {
5927 allSurround.insert(pair.first);
5928 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5929 }
Phil Burk09bc4612016-02-24 15:58:15 -08005930
5931 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5932 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005933 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005934 // This is the resulting set of formats depending on the surround mode:
5935 // 'all surround' = allSurround
5936 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5937 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5938 // 'manual surround' = mManualSurroundFormats
5939 // AUTO: formats v 'enforced surround'
5940 // ALWAYS: formats v 'all surround' v 'enforced surround'
5941 // NEVER: formats ^ 'non-surround'
5942 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005943
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005944 std::unordered_set<audio_format_t> formatSet;
5945 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5946 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005947 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005948 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005949 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005950 formatSet.insert(*formatIter);
5951 }
5952 }
5953 } else {
5954 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5955 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005956 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005957
jiabin81772902018-04-02 17:52:27 -07005958 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005959 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005960 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5961 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5962 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005963 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005964 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5965 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5966 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005967 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005968 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005969 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005970 for (const auto& format : formatSet) {
5971 formatsPtr->push(format);
5972 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005973}
5974
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005975void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005976 ChannelsVector &channelMasks = *channelMasksPtr;
5977 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5978 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5979
5980 // If NEVER, then remove support for channelMasks > stereo.
5981 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5982 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5983 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5984 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5985 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5986 channelMasks.removeAt(maskIndex);
5987 } else {
5988 maskIndex++;
5989 }
5990 }
jiabin81772902018-04-02 17:52:27 -07005991 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5992 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5993 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005994 bool supports5dot1 = false;
5995 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005996 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005997 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5998 supports5dot1 = true;
5999 break;
6000 }
6001 }
6002 // If not then add 5.1 support.
6003 if (!supports5dot1) {
6004 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006005 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006006 }
Phil Burk09bc4612016-02-24 15:58:15 -08006007 }
6008}
6009
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006010void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006011 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006012 AudioProfileVector &profiles)
6013{
6014 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006015 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006016
François Gaffie112b0af2015-11-19 16:13:25 +01006017 // Format MUST be checked first to update the list of AudioProfile
6018 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006019 reply = mpClientInterface->getParameters(
6020 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006021 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006022 AudioParameter repliedParameters(reply);
6023 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006024 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006025 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6026 return;
6027 }
Phil Burk09bc4612016-02-24 15:58:15 -08006028 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006029 if (device == AUDIO_DEVICE_OUT_HDMI
6030 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006031 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006032 }
Phil Burk09bc4612016-02-24 15:58:15 -08006033 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006034 }
François Gaffie112b0af2015-11-19 16:13:25 +01006035
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006036 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006037 ChannelsVector channelMasks;
6038 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006039 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006040 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006041
6042 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006043 reply = mpClientInterface->getParameters(
6044 ioHandle,
6045 requestedParameters.toString() + ";" +
6046 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006047 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006048 AudioParameter repliedParameters(reply);
6049 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006050 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006051 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006052 }
6053 }
6054 if (profiles.hasDynamicChannelsFor(format)) {
6055 reply = mpClientInterface->getParameters(ioHandle,
6056 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006057 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006058 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006059 AudioParameter repliedParameters(reply);
6060 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006061 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006062 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006063 if (device == AUDIO_DEVICE_OUT_HDMI
6064 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006065 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006066 }
François Gaffie112b0af2015-11-19 16:13:25 +01006067 }
6068 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006069 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006070 }
6071}
Eric Laurentd60560a2015-04-10 11:31:20 -07006072
Mikhail Naganovdc769682018-05-04 15:34:08 -07006073status_t AudioPolicyManager::installPatch(const char *caller,
6074 audio_patch_handle_t *patchHandle,
6075 AudioIODescriptorInterface *ioDescriptor,
6076 const struct audio_patch *patch,
6077 int delayMs)
6078{
6079 ssize_t index = mAudioPatches.indexOfKey(
6080 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6081 *patchHandle : ioDescriptor->getPatchHandle());
6082 sp<AudioPatch> patchDesc;
6083 status_t status = installPatch(
6084 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6085 if (status == NO_ERROR) {
6086 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6087 }
6088 return status;
6089}
6090
6091status_t AudioPolicyManager::installPatch(const char *caller,
6092 ssize_t index,
6093 audio_patch_handle_t *patchHandle,
6094 const struct audio_patch *patch,
6095 int delayMs,
6096 uid_t uid,
6097 sp<AudioPatch> *patchDescPtr)
6098{
6099 sp<AudioPatch> patchDesc;
6100 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6101 if (index >= 0) {
6102 patchDesc = mAudioPatches.valueAt(index);
6103 afPatchHandle = patchDesc->mAfPatchHandle;
6104 }
6105
6106 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6107 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6108 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6109 if (status == NO_ERROR) {
6110 if (index < 0) {
6111 patchDesc = new AudioPatch(patch, uid);
6112 addAudioPatch(patchDesc->mHandle, patchDesc);
6113 } else {
6114 patchDesc->mPatch = *patch;
6115 }
6116 patchDesc->mAfPatchHandle = afPatchHandle;
6117 if (patchHandle) {
6118 *patchHandle = patchDesc->mHandle;
6119 }
6120 nextAudioPortGeneration();
6121 mpClientInterface->onAudioPatchListUpdate();
6122 }
6123 if (patchDescPtr) *patchDescPtr = patchDesc;
6124 return status;
6125}
6126
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006127} // namespace android