blob: 126a5f7e69ce250f3a2fcd4152b80d49392d1e51 [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 Gaffiec005e562018-11-06 15:04:49 +0100498 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100499 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100500
501 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100502 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700503
504 // release existing RX patch if any
505 if (mCallRxPatch != 0) {
506 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
507 mCallRxPatch.clear();
508 }
509 // release TX patch if any
510 if (mCallTxPatch != 0) {
511 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
512 mCallTxPatch.clear();
513 }
514
François Gaffie9eb18552018-11-05 10:33:26 +0100515 auto telephonyRxModule =
516 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
517 auto telephonyTxModule =
518 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
519 // retrieve Rx Source and Tx Sink device descriptors
520 sp<DeviceDescriptor> rxSourceDevice =
521 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
522 String8(),
523 AUDIO_FORMAT_DEFAULT);
524 sp<DeviceDescriptor> txSinkDevice =
525 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
526 String8(),
527 AUDIO_FORMAT_DEFAULT);
528
529 // RX and TX Telephony device are declared by Primary Audio HAL
530 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
531 (telephonyRxModule->getHalVersionMajor() >= 3)) {
532 if (rxSourceDevice == 0 || txSinkDevice == 0) {
533 // RX / TX Telephony device(s) is(are) not currently available
534 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
535 return muteWaitMs;
536 }
537 // do not create a patch (aka Sw Bridging) if Primary HW module has declared supporting a
538 // route between telephony RX to Sink device and Source device to telephony TX
539 const auto &primaryModule = telephonyRxModule;
540 createRxPatch = !primaryModule->supportsPatch(rxSourceDevice, rxDevices.itemAt(0));
541 createTxPatch = !primaryModule->supportsPatch(txSourceDevice, txSinkDevice);
542 } else {
543 // If the RX device is on the primary HW module, then use legacy routing method for
544 // voice calls via setOutputDevice() on primary output.
545 // Otherwise, create two audio patches for TX and RX path.
546 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
547 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700548 // If the TX device is also on the primary HW module, setOutputDevice() will take care
549 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100550 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
551 (txSinkDevice != 0);
552 }
553 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
554 // Otherwise, create two audio patches for TX and RX path.
555 if (!createRxPatch) {
556 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700557 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100558 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
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();
François Gaffiec005e562018-11-06 15:04:49 +0100681 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
682 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700683 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700684 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700685 // mute media and sonification strategies and delay device switch by the largest
686 // latency of any output where either strategy is active.
687 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100688 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
689 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
690 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700691 (delayMs < (int)desc->latency()*2)) {
692 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700693 }
François Gaffiec005e562018-11-06 15:04:49 +0100694 setStrategyMute(musicStrategy, true, desc);
695 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
696 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
697 nullptr, true /*fromCache*/).types());
698 setStrategyMute(sonificationStrategy, true, desc);
699 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
700 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
701 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700702 }
703 }
704
Eric Laurent87ffa392015-05-22 10:32:38 -0700705 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100706 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700707 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100708 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700709 // force routing command to audio hardware when ending call
710 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100711 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
712 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700713 }
Eric Laurente552edb2014-03-10 17:42:56 -0700714
Eric Laurent87ffa392015-05-22 10:32:38 -0700715 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100716 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700717 } else if (oldState == AUDIO_MODE_IN_CALL) {
718 if (mCallRxPatch != 0) {
719 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
720 mCallRxPatch.clear();
721 }
722 if (mCallTxPatch != 0) {
723 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
724 mCallTxPatch.clear();
725 }
François Gaffie11d30102018-11-02 16:09:09 +0100726 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700727 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100728 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700729 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700730 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700731
732 // reevaluate routing on all outputs in case tracks have been started during the call
733 for (size_t i = 0; i < mOutputs.size(); i++) {
734 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100735 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700736 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100737 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700738 }
739 }
740
Eric Laurente552edb2014-03-10 17:42:56 -0700741 if (isStateInCall(state)) {
742 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700743 // force reevaluating accessibility routing when call starts
744 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700745 }
746
747 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100748 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
749 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700750}
751
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700752audio_mode_t AudioPolicyManager::getPhoneState() {
753 return mEngine->getPhoneState();
754}
755
Eric Laurente0720872014-03-11 09:30:41 -0700756void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100757 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700758{
François Gaffie2110e042015-03-24 08:41:51 +0100759 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700760 if (config == mEngine->getForceUse(usage)) {
761 return;
762 }
Eric Laurente552edb2014-03-10 17:42:56 -0700763
François Gaffie2110e042015-03-24 08:41:51 +0100764 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
765 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
766 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700767 }
François Gaffie2110e042015-03-24 08:41:51 +0100768 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
769 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
770 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700771
772 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700773 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800774
Eric Laurentdc462862016-07-19 12:29:53 -0700775 //FIXME: workaround for truncated touch sounds
776 // to be removed when the problem is handled by system UI
777 uint32_t delayMs = 0;
778 uint32_t waitMs = 0;
779 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
780 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
781 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700782 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100783 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
784 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700785 }
Eric Laurente552edb2014-03-10 17:42:56 -0700786 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700787 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100788 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700789 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffiea807ef92018-11-05 10:44:33 +0100790 // As done in setDeviceConnectionState, we could also fix default device issue by
791 // preventing the force re-routing in case of default dev that distinguishes on address.
792 // Let's give back to engine full device choice decision however.
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{
François Gaffiec005e562018-11-06 15:04:49 +0100872 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800873
874 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
875 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
876 // format, flags, etc. This may result in some discrepancy for functions that utilize
877 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
878 // and AudioSystem::getOutputSamplingRate().
879
François Gaffie11d30102018-11-02 16:09:09 +0100880 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
881 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700882
François Gaffie11d30102018-11-02 16:09:09 +0100883 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
884 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000885 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700886}
887
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700888status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
889 const audio_attributes_t *srcAttr,
890 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700891{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700892 if (srcAttr != NULL) {
893 if (!isValidAttributes(srcAttr)) {
894 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
895 __func__,
896 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
897 srcAttr->tags);
898 return BAD_VALUE;
899 }
900 *dstAttr = *srcAttr;
901 } else {
902 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
903 ALOGE("%s: invalid stream type", __func__);
904 return BAD_VALUE;
905 }
François Gaffiec005e562018-11-06 15:04:49 +0100906 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700907 }
908 return NO_ERROR;
909}
910
911status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
912 audio_io_handle_t *output,
913 audio_session_t session,
914 const audio_attributes_t *attr,
915 audio_stream_type_t *stream,
916 uid_t uid,
917 const audio_config_t *config,
918 audio_output_flags_t *flags,
François Gaffief579db52018-11-13 11:25:16 +0100919 audio_port_handle_t *selectedDeviceId,
920 bool *isRequestedDeviceForExclusiveUse)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700921{
François Gaffiec005e562018-11-06 15:04:49 +0100922 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100923 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100924 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100925 const sp<DeviceDescriptor> requestedDevice =
926 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
927
928
Eric Laurent8fc147b2018-07-22 19:13:55 -0700929
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700930 status_t status = getAudioAttributes(resultAttr, attr, *stream);
931 if (status != NO_ERROR) {
932 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700933 }
François Gaffiec005e562018-11-06 15:04:49 +0100934 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700935
François Gaffiec005e562018-11-06 15:04:49 +0100936 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
937 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700938
François Gaffiec005e562018-11-06 15:04:49 +0100939 // 1/ First check for explicit routing (eg. setPreferredDevice): NOTE: now handled by engine
940 // 2/ If no explict route, is there a matching dynamic policy that applies?
941 // NOTE: new engine product strategy does not make use of dynamic routing, keep it for
942 // remote-submix and legacy
943 sp<SwAudioOutputDescriptor> desc;
944 if (requestedDevice == nullptr &&
945 mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
946 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
947 if (!audio_has_proportional_frames(config->format)) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700948 return BAD_VALUE;
949 }
François Gaffiec005e562018-11-06 15:04:49 +0100950 *output = desc->mIoHandle;
951 AudioMix *mix = desc->mPolicyMix;
952 sp<DeviceDescriptor> deviceDesc =
953 mAvailableOutputDevices.getDevice(mix->mDeviceType,
954 mix->mDeviceAddress,
955 AUDIO_FORMAT_DEFAULT);
956 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
957 ALOGV("getOutputForAttr() returns output %d", *output);
958 return NO_ERROR;
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700959 }
François Gaffiec005e562018-11-06 15:04:49 +0100960 // Virtual sources must always be dynamicaly or explicitly routed
961 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
962 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
963 return BAD_VALUE;
964 }
965 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
966 // in order to let the choice of the order to future vendor engine
967 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700968
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700969 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200970 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700971 }
972
Nadav Barb2f18162018-07-18 13:01:53 +0300973 // Set incall music only if device was explicitly set, and fallback to the device which is
974 // chosen by the engine if not.
975 // FIXME: provide a more generic approach which is not device specific and move this back
976 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200977 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffiec005e562018-11-06 15:04:49 +0100978 if (outputDevices.types() == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
979 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300980 audio_is_linear_pcm(config->format) &&
981 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100982 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300983 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +0100984 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +0300985 }
986 }
987
François Gaffiec005e562018-11-06 15:04:49 +0100988 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
989 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
990 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700991
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100992 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +0100993 if (!msdDevices.isEmpty()) {
994 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +0100995 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
996 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
997 ALOGV("%s() Using MSD devices %s instead of devices %s",
998 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
999 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001000 } else {
1001 *output = AUDIO_IO_HANDLE_NONE;
1002 }
1003 }
1004 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffiec005e562018-11-06 15:04:49 +01001005 *output = getOutputForDevices(outputDevices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001006 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001007 if (*output == AUDIO_IO_HANDLE_NONE) {
1008 return INVALID_OPERATION;
1009 }
Paul McLeanaa981192015-03-21 09:55:15 -07001010
François Gaffiec005e562018-11-06 15:04:49 +01001011 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001012
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001013 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1014
1015 return NO_ERROR;
1016}
1017
1018status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1019 audio_io_handle_t *output,
1020 audio_session_t session,
1021 audio_stream_type_t *stream,
1022 uid_t uid,
1023 const audio_config_t *config,
1024 audio_output_flags_t *flags,
1025 audio_port_handle_t *selectedDeviceId,
1026 audio_port_handle_t *portId)
1027{
1028 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1029 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1030 return INVALID_OPERATION;
1031 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001032 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001033 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001034 bool isRequestedDeviceForExclusiveUse = false;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001035 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
François Gaffief579db52018-11-13 11:25:16 +01001036 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001037 if (status != NO_ERROR) {
1038 return status;
1039 }
1040
Eric Laurent8fc147b2018-07-22 19:13:55 -07001041 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1042 .format = config->format,
1043 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001044 *portId = AudioPort::getNextUniqueId();
1045
Eric Laurent8fc147b2018-07-22 19:13:55 -07001046 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001047 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +01001048 requestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001049 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffief579db52018-11-13 11:25:16 +01001050 *flags, isRequestedDeviceForExclusiveUse);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001051 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001052 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001053
François Gaffiec005e562018-11-06 15:04:49 +01001054 ALOGV("%s() returns output %d selectedDeviceId %d for port ID %d", __func__,
1055 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001056
Eric Laurente83b55d2014-11-14 10:06:21 -08001057 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001058}
1059
François Gaffie11d30102018-11-02 16:09:09 +01001060audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1061 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001062 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001063 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001064 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001065 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001066{
Andy Hungc88b0642018-04-27 15:42:35 -07001067 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001068 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001069
Eric Laurente552edb2014-03-10 17:42:56 -07001070 // open a direct output if required by specified parameters
1071 //force direct flag if offload flag is set: offloading implies a direct output stream
1072 // and all common behaviors are driven by checking only the direct flag
1073 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001074 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1075 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
Nadav Bar766fb022018-01-07 12:18:03 +02001077 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1078 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001079 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001080 // only allow deep buffering for music stream type
1081 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001082 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001083 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001084 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001085 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1086 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001087 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001088 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001089 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001090 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001091 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001092 audio_is_linear_pcm(config->format) &&
1093 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001094 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001095 AUDIO_OUTPUT_FLAG_DIRECT);
1096 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001097 }
Eric Laurente552edb2014-03-10 17:42:56 -07001098
Nadav Bar766fb022018-01-07 12:18:03 +02001099
Eric Laurentb732cf52014-09-24 19:08:21 -07001100 sp<IOProfile> profile;
1101
1102 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001103 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001104 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001105 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1106 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001107 goto non_direct_output;
1108 }
1109
Andy Hung2ddee192015-12-18 17:34:44 -08001110 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1111 // This prevents creating an offloaded track and tearing it down immediately after start
1112 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001113 // FIXME: We should check the audio session here but we do not have it in this context.
1114 // This may prevent offloading in rare situations where effects are left active by apps
1115 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001116
Nadav Bar766fb022018-01-07 12:18:03 +02001117 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001118 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001119 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001120 config->sample_rate,
1121 config->format,
1122 config->channel_mask,
1123 (audio_output_flags_t)*flags,
1124 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001125 }
1126
Eric Laurent1c333e22014-05-20 10:48:17 -07001127 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001128 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1129 for (size_t i = 0; i < mOutputs.size(); i++) {
1130 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1131 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1132 // reuse direct output if currently open by the same client
1133 // and configured with same parameters
1134 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001135 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001136 (config->channel_mask == desc->mChannelMask) &&
1137 (session == desc->mDirectClientSession)) {
1138 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001139 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001140 mOutputs.keyAt(i), session);
1141 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001142 }
1143 }
1144 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001145
1146 if (!profile->canOpenNewIo()) {
1147 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001148 }
Eric Laurent861a6282015-05-18 15:40:16 -07001149
Eric Laurent3974e3b2017-12-07 17:58:43 -08001150 sp<SwAudioOutputDescriptor> outputDesc =
1151 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001152
François Gaffie11d30102018-11-02 16:09:09 +01001153 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001154
Dean Wheatley3023b382018-08-09 07:42:40 +10001155 // MSD patch may be using the only output stream that can service this request. Release
1156 // MSD patch to prioritize this request over any active output on MSD.
1157 AudioPatchCollection msdPatches = getMsdPatches();
1158 for (size_t i = 0; i < msdPatches.size(); i++) {
1159 const auto& patch = msdPatches[i];
1160 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1161 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1162 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001163 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001164 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1165 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1166 releaseAudioPatch(patch->mHandle, mUidCached);
1167 break;
1168 }
1169 }
1170 }
1171
François Gaffie11d30102018-11-02 16:09:09 +01001172 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001173
1174 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001175 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001176 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001177 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001178 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001179 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1180 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001181 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1182 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001183 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001184 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001185 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001186 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001187 if (audio_is_linear_pcm(config->format) &&
1188 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001189 goto non_direct_output;
1190 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001191 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001192 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001193 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001194 outputDesc->mDirectClientSession = session;
1195
Eric Laurente552edb2014-03-10 17:42:56 -07001196 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001197 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001198 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001199 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001200 return output;
1201 }
1202
Eric Laurentb732cf52014-09-24 19:08:21 -07001203non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001204
1205 // A request for HW A/V sync cannot fallback to a mixed output because time
1206 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001207 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001208 return AUDIO_IO_HANDLE_NONE;
1209 }
1210
Eric Laurente552edb2014-03-10 17:42:56 -07001211 // ignoring channel mask due to downmix capability in mixer
1212
1213 // open a non direct output
1214
1215 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001216 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001217 // get which output is suitable for the specified stream. The actual
1218 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001219 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001220
Eric Laurent8838a382014-09-08 16:44:28 -07001221 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001222 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001223 output = selectOutput(outputs, *flags, config->format,
1224 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001225 }
François Gaffie11d30102018-11-02 16:09:09 +01001226 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001227 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001228 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001229
Eric Laurente552edb2014-03-10 17:42:56 -07001230 return output;
1231}
1232
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001233sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001234 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1235 mAvailableInputDevices);
1236 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1237}
1238
1239DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1240 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1241 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001242}
1243
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001244const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1245 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001246 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1247 if (msdModule != 0) {
1248 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1249 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1250 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1251 const struct audio_port_config *source = &patch->mPatch.sources[j];
1252 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1253 source->ext.device.hw_module == msdModule->getHandle()) {
1254 msdPatches.addAudioPatch(patch->mHandle, patch);
1255 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001256 }
1257 }
1258 }
1259 return msdPatches;
1260}
1261
François Gaffie11d30102018-11-02 16:09:09 +01001262status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001263 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1264{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001265 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001266 if (msdModule == nullptr) {
1267 ALOGE("%s() unable to get MSD module", __func__);
1268 return NO_INIT;
1269 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001270 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001271 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001272 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001273 return NO_INIT;
1274 }
1275 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1276 if (inputProfiles.isEmpty()) {
1277 ALOGE("%s() no input profiles for MSD module", __func__);
1278 return NO_INIT;
1279 }
1280 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1281 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001282 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001283 return NO_INIT;
1284 }
1285 AudioProfileVector msdProfiles;
1286 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1287 for (const auto &inProfile : inputProfiles) {
1288 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1289 msdProfiles.appendVector(inProfile->getAudioProfiles());
1290 }
1291 }
1292 AudioProfileVector deviceProfiles;
1293 for (const auto &outProfile : outputProfiles) {
1294 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1295 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1296 }
1297 }
1298 struct audio_config_base bestSinkConfig;
1299 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1300 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1301 &bestSinkConfig);
1302 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001303 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1304 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001305 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001306 }
1307 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1308 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1309 sinkConfig->format = bestSinkConfig.format;
1310 // For encoded streams force direct flag to prevent downstream mixing.
1311 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1312 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1313 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1314 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1315 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1316 sourceConfig->format = bestSinkConfig.format;
1317 // Copy input stream directly without any processing (e.g. resampling).
1318 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1319 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1320 if (hwAvSync) {
1321 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1322 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1323 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1324 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1325 }
1326 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1327 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1328 sinkConfig->config_mask |= config_mask;
1329 sourceConfig->config_mask |= config_mask;
1330 return NO_ERROR;
1331}
1332
François Gaffie11d30102018-11-02 16:09:09 +01001333PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001334{
1335 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001336 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001337 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1338 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1339 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1340 // For now, we just forcefully try with HwAvSync first.
1341 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1342 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1343 getBestMsdAudioProfileFor(
1344 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1345 if (res == NO_ERROR) {
1346 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1347 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1348 }
1349 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1350 " supporting PCM format conversion.", __func__);
1351 return patchBuilder;
1352}
1353
François Gaffie11d30102018-11-02 16:09:09 +01001354status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1355 sp<DeviceDescriptor> device = outputDevice;
1356 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001357 // Use media strategy for unspecified output device. This should only
1358 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1359 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001360 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1361 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001362 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1363 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001364 }
François Gaffie11d30102018-11-02 16:09:09 +01001365 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1366 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001367 const struct audio_patch* patch = patchBuilder.patch();
1368 const AudioPatchCollection msdPatches = getMsdPatches();
1369 if (!msdPatches.isEmpty()) {
1370 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1371 "The current MSD prototype only supports one output patch");
1372 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1373 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1374 return NO_ERROR;
1375 }
1376 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1377 }
1378 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1379 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1380 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1381 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001382 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1383 device->toString().c_str(), patch->sources[0].format,
1384 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001385 return status;
1386}
1387
Eric Laurente0720872014-03-11 09:30:41 -07001388audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001389 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001390 audio_format_t format,
1391 audio_channel_mask_t channelMask,
1392 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001393{
1394 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001395 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001396 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001397 // 1: the output supporting haptic playback when requesting haptic playback
1398 // 2: the output with the highest number of requested policy flags
1399 // 3: the output with the bit depth the closest to the requested one
1400 // 4: the primary output
1401 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001402
1403 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001404 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001405 }
1406 if (outputs.size() == 1) {
1407 return outputs[0];
1408 }
1409
1410 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001411 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1412 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001413 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1414 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1415 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001416 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1417 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001418
Eric Laurente78b6762018-12-19 16:29:01 -08001419 // Flags which must be present on both the request and the selected output
1420 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1421 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1422
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001423 for (audio_io_handle_t output : outputs) {
1424 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001425 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001426 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1427 continue;
1428 }
jiabin40573322018-11-08 12:08:02 -08001429 // If haptic channel is specified, use the haptic output if present.
1430 // When using haptic output, same audio format and sample rate are required.
1431 if (hapticChannelCount > 0) {
1432 // If haptic channel is specified, use the first output that
1433 // support haptic playback.
1434 if (audio_channel_count_from_out_mask(
1435 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1436 && format == outputDesc->mFormat
1437 && samplingRate == outputDesc->mSamplingRate) {
1438 return output;
1439 }
1440 } else {
1441 // When haptic channel is not specified, skip haptic output.
1442 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1443 continue;
1444 }
1445 }
Eric Laurente78b6762018-12-19 16:29:01 -08001446 if ((kMandatedFlags & flags) !=
1447 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1448 continue;
1449 }
jiabin40573322018-11-08 12:08:02 -08001450
Eric Laurent8838a382014-09-08 16:44:28 -07001451 // if a valid format is specified, skip output if not compatible
1452 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001453 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001454 continue;
1455 }
Eric Laurente6930022016-02-11 10:20:40 -08001456 if (AudioPort::isBetterFormatMatch(
1457 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001458 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001459 bestFormat = outputDesc->mFormat;
1460 }
Eric Laurent8838a382014-09-08 16:44:28 -07001461 }
1462
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001463 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001464 if (commonFlags >= maxCommonFlags) {
1465 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001466 if (format != AUDIO_FORMAT_INVALID
1467 && AudioPort::isBetterFormatMatch(
1468 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001469 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001470 bestFormatForFlags = outputDesc->mFormat;
1471 }
1472 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001473 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001474 maxCommonFlags = commonFlags;
1475 bestFormatForFlags = outputDesc->mFormat;
1476 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001477 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001478 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001479 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001480 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001481 }
1482 }
1483 }
1484
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001485 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001486 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001487 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001488 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001489 return outputForFormat;
1490 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001491 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001492 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001493 }
1494
1495 return outputs[0];
1496}
1497
Eric Laurent8fc147b2018-07-22 19:13:55 -07001498status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001499{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001500 ALOGV("%s portId %d", __FUNCTION__, portId);
1501
1502 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1503 if (outputDesc == 0) {
1504 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001505 return BAD_VALUE;
1506 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001507 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001508
Eric Laurent8fc147b2018-07-22 19:13:55 -07001509 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001510 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001511
Eric Laurent733ce942017-12-07 12:18:25 -08001512 status_t status = outputDesc->start();
1513 if (status != NO_ERROR) {
1514 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001515 }
1516
Eric Laurent97ac8712018-07-27 18:59:02 -07001517 uint32_t delayMs;
1518 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001519
1520 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001521 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001522 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001523 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001524 if (delayMs != 0) {
1525 usleep(delayMs * 1000);
1526 }
1527
1528 return status;
1529}
1530
Eric Laurent97ac8712018-07-27 18:59:02 -07001531status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1532 const sp<TrackClientDescriptor>& client,
1533 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001534{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001535 // cannot start playback of STREAM_TTS if any other output is being used
1536 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001537
1538 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001539 audio_stream_type_t stream = client->stream();
François Gaffiec005e562018-11-06 15:04:49 +01001540 auto clientStrategy = client->strategy();
1541 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001542 if (stream == AUDIO_STREAM_TTS) {
1543 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001544 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001545 return INVALID_OPERATION;
1546 } else {
1547 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1548 }
1549 } else {
1550 // some playback other than beacon starts
1551 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1552 }
1553
Eric Laurent77305a62016-07-25 16:39:22 -07001554 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001555 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001556 bool force = !outputDesc->isActive() &&
1557 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001558
François Gaffie11d30102018-11-02 16:09:09 +01001559 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001560 AudioMix *policyMix = NULL;
1561 const char *address = NULL;
1562 if (outputDesc->mPolicyMix != NULL) {
1563 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001564 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001565 address = policyMix->mDeviceAddress.string();
1566 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001567 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001568 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001569 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001570 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001571 devices.add(mAvailableOutputDevices.getDevice(newDeviceType,
1572 String8(address), AUDIO_FORMAT_DEFAULT));
Eric Laurent97ac8712018-07-27 18:59:02 -07001573 }
1574
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001575 // requiresMuteCheck is false when we can bypass mute strategy.
1576 // It covers a common case when there is no materially active audio
1577 // and muting would result in unnecessary delay and dropped audio.
1578 const uint32_t outputLatencyMs = outputDesc->latency();
1579 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1580
Eric Laurente552edb2014-03-10 17:42:56 -07001581 // increment usage count for this stream on the requested output:
1582 // NOTE that the usage count is the same for duplicated output and hardware output which is
1583 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001584 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001585
1586 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001587 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1588 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001589 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001590 }
1591 }
Eric Laurente552edb2014-03-10 17:42:56 -07001592
François Gaffiec005e562018-11-06 15:04:49 +01001593 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001594 selectOutputForMusicEffects();
1595 }
1596
François Gaffie11d30102018-11-02 16:09:09 +01001597 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001598 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001599 if (devices.isEmpty()) {
1600 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001601 }
François Gaffiec005e562018-11-06 15:04:49 +01001602 bool shouldWait =
1603 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1604 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1605 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001606 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001607 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001608 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001609 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001610 // An output has a shared device if
1611 // - managed by the same hw module
1612 // - supports the currently selected device
1613 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001614 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001615
Eric Laurent77305a62016-07-25 16:39:22 -07001616 // force a device change if any other output is:
1617 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001618 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001619 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001620 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001621 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001622 // change the device currently selected by the other output.
1623 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001624 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001625 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001626 force = true;
1627 }
1628 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001629 // a notification so that audio focus effect can propagate, or that a mute/unmute
1630 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001631 const uint32_t latencyMs = desc->latency();
1632 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1633
1634 if (shouldWait && isActive && (waitMs < latencyMs)) {
1635 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001636 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001637
1638 // Require mute check if another output is on a shared device
1639 // and currently active to have proper drain and avoid pops.
1640 // Note restoring AudioTracks onto this output needs to invoke
1641 // a volume ramp if there is no mute.
1642 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001643 }
1644 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001645
1646 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001647 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001648
Eric Laurente552edb2014-03-10 17:42:56 -07001649 // apply volume rules for current stream and device if necessary
1650 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001651 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001652 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001653 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001654
1655 // update the outputs if starting an output with a stream that can affect notification
1656 // routing
1657 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001658
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001659 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001660 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001661 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1662 }
Eric Laurentdc462862016-07-19 12:29:53 -07001663
1664 if (waitMs > muteWaitMs) {
1665 *delayMs = waitMs - muteWaitMs;
1666 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001667
1668 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1669 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1670 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1671 // change occurs after the MixerThread starts and causes a stream volume
1672 // glitch.
1673 //
1674 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001675 }
Eric Laurentdc462862016-07-19 12:29:53 -07001676
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001677 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1678 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001679 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001680 }
1681
Eric Laurent97ac8712018-07-27 18:59:02 -07001682 // Automatically enable the remote submix input when output is started on a re routing mix
1683 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001684 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001685 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1686 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1687 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1688 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001689 "remote-submix",
1690 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001691 }
1692
Eric Laurente552edb2014-03-10 17:42:56 -07001693 return NO_ERROR;
1694}
1695
Eric Laurent8fc147b2018-07-22 19:13:55 -07001696status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001697{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001698 ALOGV("%s portId %d", __FUNCTION__, portId);
1699
1700 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1701 if (outputDesc == 0) {
1702 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001703 return BAD_VALUE;
1704 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001705 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001706
Eric Laurent97ac8712018-07-27 18:59:02 -07001707 ALOGV("stopOutput() output %d, stream %d, session %d",
1708 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001709
Eric Laurent97ac8712018-07-27 18:59:02 -07001710 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001711
Eric Laurent733ce942017-12-07 12:18:25 -08001712 if (status == NO_ERROR ) {
1713 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001714 }
1715 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001716}
1717
Eric Laurent97ac8712018-07-27 18:59:02 -07001718status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1719 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001720{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001721 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001722 audio_stream_type_t stream = client->stream();
1723
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001724 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1725
Eric Laurent592dd7b2018-08-05 18:58:48 -07001726 if (outputDesc->streamActiveCount(stream) > 0) {
1727 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001728 // Automatically disable the remote submix input when output is stopped on a
1729 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001730 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001731 outputDesc->mPolicyMix != NULL &&
1732 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1733 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1734 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1735 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001736 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001737 }
1738 }
1739 bool forceDeviceUpdate = false;
1740 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001741 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001742 forceDeviceUpdate = true;
1743 }
1744
Eric Laurente552edb2014-03-10 17:42:56 -07001745 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001746 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001747
Eric Laurente552edb2014-03-10 17:42:56 -07001748 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001749 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001750 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001751 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001752 // delay the device switch by twice the latency because stopOutput() is executed when
1753 // the track stop() command is received and at that time the audio track buffer can
1754 // still contain data that needs to be drained. The latency only covers the audio HAL
1755 // and kernel buffers. Also the latency does not always include additional delay in the
1756 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001757 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001758
1759 // force restoring the device selection on other active outputs if it differs from the
1760 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001761 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001762 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001763 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001764 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001765 desc->isActive() &&
1766 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001767 (newDevices != desc->devices())) {
1768 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1769 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001770
François Gaffie11d30102018-11-02 16:09:09 +01001771 setOutputDevices(desc, newDevices2, force, delayMs);
1772
Eric Laurent57de36c2016-09-28 16:59:11 -07001773 // re-apply device specific volume if not done by setOutputDevice()
1774 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001775 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001776 }
Eric Laurente552edb2014-03-10 17:42:56 -07001777 }
1778 }
1779 // update the outputs if stopping one with a stream that can affect notification routing
1780 handleNotificationRoutingForStream(stream);
1781 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001782
1783 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1784 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001785 setStrategyMute(streamToStrategy(AUDIO_STREAM_RING), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001786 }
1787
François Gaffiec005e562018-11-06 15:04:49 +01001788 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001789 selectOutputForMusicEffects();
1790 }
Eric Laurente552edb2014-03-10 17:42:56 -07001791 return NO_ERROR;
1792 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001793 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001794 return INVALID_OPERATION;
1795 }
1796}
1797
Eric Laurent8fc147b2018-07-22 19:13:55 -07001798void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001799{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001800 ALOGV("%s portId %d", __FUNCTION__, portId);
1801
1802 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1803 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001804 // If an output descriptor is closed due to a device routing change,
1805 // then there are race conditions with releaseOutput from tracks
1806 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1807 // destroyed shortly thereafter.
1808 //
1809 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001810 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001811 return;
1812 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001813
1814 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001815
Eric Laurent8fc147b2018-07-22 19:13:55 -07001816 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1817 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001818 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001819 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001820 return;
1821 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001822 if (--outputDesc->mDirectOpenCount == 0) {
1823 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001824 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001825 }
1826 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001827 // stopOutput() needs to be successfully called before releaseOutput()
1828 // otherwise there may be inaccurate stream reference counts.
1829 // This is checked in outputDesc->removeClient below.
1830 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001831}
1832
Eric Laurentcaf7f482014-11-25 17:50:47 -08001833status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1834 audio_io_handle_t *input,
1835 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001836 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001837 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001838 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001839 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001840 input_type_t *inputType,
1841 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001842{
François Gaffiec005e562018-11-06 15:04:49 +01001843 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1844 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1845 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001846
Eric Laurentad2e7b92017-09-14 20:06:42 -07001847 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001848 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001849 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001850 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001851 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001852 sp<AudioInputDescriptor> inputDesc;
1853 sp<RecordClientDescriptor> clientDesc;
1854 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001855 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001856
1857 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1858 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1859 return INVALID_OPERATION;
1860 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001861
Francois Gaffie716e1432019-01-14 16:58:59 +01001862 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1863 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001864 }
1865
Paul McLean466dc8e2015-04-17 13:15:36 -06001866 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001867 sp<DeviceDescriptor> explicitRoutingDevice =
1868 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001869
Eric Laurentad2e7b92017-09-14 20:06:42 -07001870 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1871 // possible
1872 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1873 *input != AUDIO_IO_HANDLE_NONE) {
1874 ssize_t index = mInputs.indexOfKey(*input);
1875 if (index < 0) {
1876 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1877 status = BAD_VALUE;
1878 goto error;
1879 }
1880 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001881 RecordClientVector clients = inputDesc->getClientsForSession(session);
1882 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001883 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1884 status = BAD_VALUE;
1885 goto error;
1886 }
1887 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1888 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001889 // corresponds to a new client and is only permitted from the same UID.
1890 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001891 if (clients.size() > 1) {
1892 for (const auto& client : clients) {
1893 // The client map is ordered by key values (portId) and portIds are allocated
1894 // incrementaly. So the first client in this list is the one opened by audio flinger
1895 // when the mmap stream is created and should be ignored as it does not correspond
1896 // to an actual client
1897 if (client == *clients.cbegin()) {
1898 continue;
1899 }
1900 if (uid != client->uid() && !client->isSilenced()) {
1901 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1902 uid, client->portId(), client->uid());
1903 status = INVALID_OPERATION;
1904 goto error;
1905 }
Eric Laurent331679c2018-04-16 17:03:16 -07001906 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001907 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001908 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001909 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001910
Eric Laurent8f42ea12018-08-08 09:08:25 -07001911 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001912 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001913 }
1914
1915 *input = AUDIO_IO_HANDLE_NONE;
1916 *inputType = API_INPUT_INVALID;
1917
Francois Gaffie716e1432019-01-14 16:58:59 +01001918 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001919
Francois Gaffie716e1432019-01-14 16:58:59 +01001920 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1921 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1922 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001923 if (status != NO_ERROR) {
1924 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001925 }
1926 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001927 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001928 String8(attr->tags + strlen("addr=")),
1929 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001930 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001931 if (explicitRoutingDevice != nullptr) {
1932 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001933 } else {
François Gaffiec005e562018-11-06 15:04:49 +01001934 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001935 }
François Gaffie11d30102018-11-02 16:09:09 +01001936 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001937 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001938 status = BAD_VALUE;
1939 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001940 }
François Gaffie11d30102018-11-02 16:09:09 +01001941 if (policyMix != nullptr) {
1942 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1943 // there is an external policy, but this input is attached to a mix of recorders,
1944 // meaning it receives audio injected into the framework, so the recorder doesn't
1945 // know about it and is therefore considered "legacy"
1946 *inputType = API_INPUT_LEGACY;
1947 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001948 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001949 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001950 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001951 } else {
1952 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001953 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001954
Eric Laurent599c7582015-12-07 18:05:55 -08001955 }
1956
François Gaffiec005e562018-11-06 15:04:49 +01001957 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08001958 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001959 status = INVALID_OPERATION;
1960 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001961 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001962
Eric Laurent8f42ea12018-08-08 09:08:25 -07001963exit:
1964
François Gaffiec005e562018-11-06 15:04:49 +01001965 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1966 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001967
Francois Gaffie716e1432019-01-14 16:58:59 +01001968 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001969 mSoundTriggerSessions.indexOfKey(session) > 0;
1970 *portId = AudioPort::getNextUniqueId();
1971
François Gaffie11d30102018-11-02 16:09:09 +01001972 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001973 requestedDeviceId, attributes.source, flags,
1974 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001975 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001976 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001977
1978 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1979 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001980
Eric Laurent599c7582015-12-07 18:05:55 -08001981 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001982
1983error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001984 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001985}
1986
1987
François Gaffie11d30102018-11-02 16:09:09 +01001988audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08001989 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01001990 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08001991 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001992 audio_input_flags_t flags,
1993 AudioMix *policyMix)
1994{
1995 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01001996 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08001997 bool isSoundTrigger = false;
1998
François Gaffiec005e562018-11-06 15:04:49 +01001999 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002000 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2001 if (index >= 0) {
2002 input = mSoundTriggerSessions.valueFor(session);
2003 isSoundTrigger = true;
2004 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2005 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2006 } else {
2007 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002008 }
François Gaffiec005e562018-11-06 15:04:49 +01002009 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002010 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002011 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002012 }
2013
Andy Hungf129b032015-04-07 13:45:50 -07002014 // find a compatible input profile (not necessarily identical in parameters)
2015 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002016 // sampling rate and flags may be updated by getInputProfile
2017 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2018 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002019 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002020 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002021 audio_input_flags_t profileFlags = flags;
2022 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002023 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002024 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002025 profileFlags);
2026 if (profile != 0) {
2027 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002028 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2029 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002030 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2031 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2032 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002033 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2034 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2035 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002036 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002037 }
Eric Laurente552edb2014-03-10 17:42:56 -07002038 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002039 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002040 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002041 if (samplingRate == 0) {
2042 samplingRate = profileSamplingRate;
2043 }
Eric Laurente552edb2014-03-10 17:42:56 -07002044
Eric Laurent322b4d22015-04-03 15:57:54 -07002045 if (profile->getModuleHandle() == 0) {
2046 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002047 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002048 }
2049
Eric Laurent3974e3b2017-12-07 17:58:43 -08002050 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002051 for (size_t i = 0; i < mInputs.size(); ) {
2052 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2053 if (desc->mProfile != profile) {
2054 continue;
2055 }
2056 // if sound trigger, reuse input if used by other sound trigger on same session
2057 // else
2058 // reuse input if active client app is not in IDLE state
2059 //
2060 RecordClientVector clients = desc->clientsList();
2061 bool doClose = false;
2062 for (const auto& client : clients) {
2063 if (isSoundTrigger != client->isSoundTrigger()) {
2064 continue;
2065 }
2066 if (client->isSoundTrigger()) {
2067 if (session == client->session()) {
2068 return desc->mIoHandle;
2069 }
2070 continue;
2071 }
2072 if (client->active() && client->appState() != APP_STATE_IDLE) {
2073 return desc->mIoHandle;
2074 }
2075 doClose = true;
2076 }
2077 if (doClose) {
2078 closeInput(desc->mIoHandle);
2079 } else {
2080 i++;
2081 }
2082 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002083 }
2084
Eric Laurentfe231122017-11-17 17:48:06 -08002085 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002086
Eric Laurentfe231122017-11-17 17:48:06 -08002087 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2088 lConfig.sample_rate = profileSamplingRate;
2089 lConfig.channel_mask = profileChannelMask;
2090 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002091
François Gaffie11d30102018-11-02 16:09:09 +01002092 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002093
2094 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002095 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002096 (profileSamplingRate != lConfig.sample_rate) ||
2097 !audio_formats_match(profileFormat, lConfig.format) ||
2098 (profileChannelMask != lConfig.channel_mask)) {
2099 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002100 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002101 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002102 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002103 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002104 }
Eric Laurent599c7582015-12-07 18:05:55 -08002105 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002106 }
2107
Eric Laurentc722f302014-12-10 11:21:49 -08002108 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002109
Eric Laurent599c7582015-12-07 18:05:55 -08002110 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002111 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002112
Eric Laurent599c7582015-12-07 18:05:55 -08002113 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002114}
2115
Eric Laurent4eb58f12018-12-07 16:41:02 -08002116status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002117{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002118 ALOGV("%s portId %d", __FUNCTION__, portId);
2119
2120 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2121 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002122 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002123 return BAD_VALUE;
2124 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002125 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002126 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002127 if (client->active()) {
2128 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2129 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002130 }
2131
Eric Laurent8f42ea12018-08-08 09:08:25 -07002132 audio_session_t session = client->session();
2133
Eric Laurent4eb58f12018-12-07 16:41:02 -08002134 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002135
Eric Laurent4eb58f12018-12-07 16:41:02 -08002136 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002137
Eric Laurent4eb58f12018-12-07 16:41:02 -08002138 status_t status = inputDesc->start();
2139 if (status != NO_ERROR) {
2140 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002141 }
Eric Laurente552edb2014-03-10 17:42:56 -07002142
Eric Laurent4eb58f12018-12-07 16:41:02 -08002143 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002144 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002145 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002146
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 // indicate active capture to sound trigger service if starting capture from a mic on
2148 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002149 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002150 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002151
Eric Laurent8f42ea12018-08-08 09:08:25 -07002152 if (inputDesc->activeCount() == 1) {
2153 // if input maps to a dynamic policy with an activity listener, notify of state change
2154 if ((inputDesc->mPolicyMix != NULL)
2155 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2156 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2157 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002158 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002159
François Gaffie11d30102018-11-02 16:09:09 +01002160 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2161 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002162 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2163 SoundTrigger::setCaptureState(true);
2164 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002165
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166 // automatically enable the remote submix output when input is started if not
2167 // used by a policy mix of type MIX_TYPE_RECORDERS
2168 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002169 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002170 String8 address = String8("");
2171 if (inputDesc->mPolicyMix == NULL) {
2172 address = String8("0");
2173 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2174 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002175 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002176 if (address != "") {
2177 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2178 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002179 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002180 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002181 }
Eric Laurente552edb2014-03-10 17:42:56 -07002182 }
2183
Eric Laurent8f42ea12018-08-08 09:08:25 -07002184 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002185
Eric Laurente552edb2014-03-10 17:42:56 -07002186 return NO_ERROR;
2187}
2188
Eric Laurent8fc147b2018-07-22 19:13:55 -07002189status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002190{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002191 ALOGV("%s portId %d", __FUNCTION__, portId);
2192
2193 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2194 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002195 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002196 return BAD_VALUE;
2197 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002198 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002199 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002200 if (!client->active()) {
2201 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002202 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002203 }
2204
Eric Laurent8f42ea12018-08-08 09:08:25 -07002205 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002206
Eric Laurent8f42ea12018-08-08 09:08:25 -07002207 inputDesc->stop();
2208 if (inputDesc->isActive()) {
2209 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2210 } else {
2211 // if input maps to a dynamic policy with an activity listener, notify of state change
2212 if ((inputDesc->mPolicyMix != NULL)
2213 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2214 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2215 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002216 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002217
2218 // automatically disable the remote submix output when input is stopped if not
2219 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002220 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002221 String8 address = String8("");
2222 if (inputDesc->mPolicyMix == NULL) {
2223 address = String8("0");
2224 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2225 address = inputDesc->mPolicyMix->mDeviceAddress;
2226 }
2227 if (address != "") {
2228 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2229 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002230 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002231 }
2232 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002233 resetInputDevice(input);
2234
2235 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2236 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002237 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2238 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002239 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2240 SoundTrigger::setCaptureState(false);
2241 }
2242 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002243 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002244 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002245}
2246
Eric Laurent8fc147b2018-07-22 19:13:55 -07002247void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002248{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002249 ALOGV("%s portId %d", __FUNCTION__, portId);
2250
2251 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2252 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002253 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002254 return;
2255 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002256 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002257 audio_io_handle_t input = inputDesc->mIoHandle;
2258
Eric Laurent8f42ea12018-08-08 09:08:25 -07002259 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002260
Andy Hung39efb7a2018-09-26 15:39:28 -07002261 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002262
Andy Hung39efb7a2018-09-26 15:39:28 -07002263 if (inputDesc->getClientCount() > 0) {
2264 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002265 return;
2266 }
2267
Eric Laurent05b90f82014-08-27 15:32:29 -07002268 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002269 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002270 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002271}
2272
Eric Laurent8f42ea12018-08-08 09:08:25 -07002273void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002274{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002275 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002276
2277 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002278 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002279 }
2280}
2281
Eric Laurent8f42ea12018-08-08 09:08:25 -07002282void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2283{
2284 stopInput(portId);
2285 releaseInput(portId);
2286}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002287
Eric Laurentd4692962014-05-05 18:13:44 -07002288void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002289 bool patchRemoved = false;
2290
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002291 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002292 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002293 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002294 if (patch_index >= 0) {
2295 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002296 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002297 mAudioPatches.removeItemsAt(patch_index);
2298 patchRemoved = true;
2299 }
Eric Laurentfe231122017-11-17 17:48:06 -08002300 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002301 }
2302 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002303 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002304 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002305
2306 if (patchRemoved) {
2307 mpClientInterface->onAudioPatchListUpdate();
2308 }
Eric Laurentd4692962014-05-05 18:13:44 -07002309}
2310
Eric Laurente0720872014-03-11 09:30:41 -07002311void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002312 int indexMin,
2313 int indexMax)
2314{
2315 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002316 if (indexMin < 0 || indexMax < 0) {
2317 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2318 return;
2319 }
François Gaffied1ab2bd2015-12-02 18:20:06 +01002320 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002321
2322 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002323 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2324 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002325 continue;
2326 }
2327 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002328 }
Eric Laurente552edb2014-03-10 17:42:56 -07002329}
2330
Eric Laurente0720872014-03-11 09:30:41 -07002331status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002332 int index,
2333 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002334{
2335
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002336 // VOICE_CALL and BLUETOOTH_SCO stream have minVolumeIndex > 0 but
2337 // can be muted directly by an app that has MODIFY_PHONE_STATE permission.
Nadav Bar7c605f62017-12-25 00:01:52 +02002338 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002339 !((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
2340 index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002341 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002342 return BAD_VALUE;
2343 }
2344 if (!audio_is_output_device(device)) {
2345 return BAD_VALUE;
2346 }
2347
2348 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002349 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002350
Eric Laurent1fd372e2016-04-06 14:23:53 -07002351 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002352 stream, device, index);
2353
Eric Laurent28d09f02016-03-08 10:43:05 -08002354 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002355 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2356 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002357 continue;
2358 }
2359 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2360 }
Eric Laurente552edb2014-03-10 17:42:56 -07002361
Eric Laurent1fd372e2016-04-06 14:23:53 -07002362 // update volume on all outputs and streams matching the following:
2363 // - The requested stream (or a stream matching for volume control) is active on the output
François Gaffiec005e562018-11-06 15:04:49 +01002364 // - The device (or devices) selected by the engine for this stream includes
Eric Laurent1fd372e2016-04-06 14:23:53 -07002365 // the requested device
2366 // - For non default requested device, currently selected device on the output is either the
François Gaffiec005e562018-11-06 15:04:49 +01002367 // requested device or one of the devices selected by the engine for this stream
Eric Laurent5a2b6292016-04-14 18:05:57 -07002368 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2369 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002370 status_t status = NO_ERROR;
2371 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002372 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002373 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002374 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002375 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002376 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002377 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002378 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002379 continue;
2380 }
François Gaffiec005e562018-11-06 15:04:49 +01002381 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(
2382 mEngine->getOutputDevicesForStream((audio_stream_type_t)curStream,
2383 false /*fromCache*/).types());
Eric Laurente76f29c2016-09-14 17:17:53 -07002384 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2385 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002386 continue;
2387 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002388 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002389 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002390 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002391 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002392 } else {
2393 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002394 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002395 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002396 // rescale index before applying to curStream as ranges may be different for
2397 // stream and curStream
2398 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002399 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002400 //FIXME: workaround for truncated touch sounds
2401 // delayed volume change for system stream to be removed when the problem is
2402 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002403 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002404 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002405 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002406 if (volStatus != NO_ERROR) {
2407 status = volStatus;
2408 }
2409 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002410 }
Eric Laurente552edb2014-03-10 17:42:56 -07002411 }
2412 return status;
2413}
2414
Eric Laurente0720872014-03-11 09:30:41 -07002415status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002416 int *index,
2417 audio_devices_t device)
2418{
2419 if (index == NULL) {
2420 return BAD_VALUE;
2421 }
2422 if (!audio_is_output_device(device)) {
2423 return BAD_VALUE;
2424 }
François Gaffiec005e562018-11-06 15:04:49 +01002425 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2426 // stream by the engine.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002427 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
François Gaffiec005e562018-11-06 15:04:49 +01002428 device = mEngine->getOutputDevicesForStream(stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002429 }
François Gaffiedfd74092015-03-19 12:10:59 +01002430 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002431
François Gaffied1ab2bd2015-12-02 18:20:06 +01002432 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002433 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2434 return NO_ERROR;
2435}
2436
Eric Laurent36829f92017-04-07 19:04:42 -07002437audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002438{
2439 // select one output among several suitable for global effects.
2440 // The priority is as follows:
2441 // 1: An offloaded output. If the effect ends up not being offloadable,
2442 // AudioFlinger will invalidate the track and the offloaded output
2443 // will be closed causing the effect to be moved to a PCM output.
2444 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002445 // 3: The primary output
2446 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002447
François Gaffiec005e562018-11-06 15:04:49 +01002448 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2449 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002450 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002451
Eric Laurent36829f92017-04-07 19:04:42 -07002452 if (outputs.size() == 0) {
2453 return AUDIO_IO_HANDLE_NONE;
2454 }
Eric Laurente552edb2014-03-10 17:42:56 -07002455
Eric Laurent36829f92017-04-07 19:04:42 -07002456 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2457 bool activeOnly = true;
2458
2459 while (output == AUDIO_IO_HANDLE_NONE) {
2460 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2461 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2462 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2463
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002464 for (audio_io_handle_t output : outputs) {
2465 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002466 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2467 continue;
2468 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002469 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2470 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002471 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002472 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002473 }
2474 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002475 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002476 }
2477 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002478 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002479 }
2480 }
2481 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2482 output = outputOffloaded;
2483 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2484 output = outputDeepBuffer;
2485 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2486 output = outputPrimary;
2487 } else {
2488 output = outputs[0];
2489 }
2490 activeOnly = false;
2491 }
2492
2493 if (output != mMusicEffectOutput) {
2494 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2495 mMusicEffectOutput = output;
2496 }
2497
2498 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002499 return output;
2500}
2501
Eric Laurent36829f92017-04-07 19:04:42 -07002502audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2503{
2504 return selectOutputForMusicEffects();
2505}
2506
Eric Laurente0720872014-03-11 09:30:41 -07002507status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002508 audio_io_handle_t io,
2509 uint32_t strategy,
2510 int session,
2511 int id)
2512{
2513 ssize_t index = mOutputs.indexOfKey(io);
2514 if (index < 0) {
2515 index = mInputs.indexOfKey(io);
2516 if (index < 0) {
2517 ALOGW("registerEffect() unknown io %d", io);
2518 return INVALID_OPERATION;
2519 }
2520 }
François Gaffiec005e562018-11-06 15:04:49 +01002521 return mEffects.registerEffect(desc, io, session, id,
2522 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2523 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002524}
2525
Eric Laurentc241b0d2018-11-28 09:08:49 -08002526status_t AudioPolicyManager::unregisterEffect(int id)
2527{
2528 if (mEffects.getEffect(id) == nullptr) {
2529 return INVALID_OPERATION;
2530 }
2531
2532 if (mEffects.isEffectEnabled(id)) {
2533 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2534 setEffectEnabled(id, false);
2535 }
2536 return mEffects.unregisterEffect(id);
2537}
2538
2539status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2540{
2541 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2542 if (effect == nullptr) {
2543 return INVALID_OPERATION;
2544 }
2545
2546 status_t status = mEffects.setEffectEnabled(id, enabled);
2547 if (status == NO_ERROR) {
2548 mInputs.trackEffectEnabled(effect, enabled);
2549 }
2550 return status;
2551}
2552
Eric Laurentc75307b2015-03-17 15:29:32 -07002553bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2554{
Eric Laurent28d09f02016-03-08 10:43:05 -08002555 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002556 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2557 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002558 continue;
2559 }
2560 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2561 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002562 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002563}
2564
2565bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2566{
2567 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2568}
2569
Eric Laurente0720872014-03-11 09:30:41 -07002570bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002571{
2572 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002573 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002574 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002575 return true;
2576 }
2577 }
2578 return false;
2579}
2580
Eric Laurent275e8e92014-11-30 15:14:47 -08002581// Register a list of custom mixes with their attributes and format.
2582// When a mix is registered, corresponding input and output profiles are
2583// added to the remote submix hw module. The profile contains only the
2584// parameters (sampling rate, format...) specified by the mix.
2585// The corresponding input remote submix device is also connected.
2586//
2587// When a remote submix device is connected, the address is checked to select the
2588// appropriate profile and the corresponding input or output stream is opened.
2589//
2590// When capture starts, getInputForAttr() will:
2591// - 1 look for a mix matching the address passed in attribtutes tags if any
2592// - 2 if none found, getDeviceForInputSource() will:
2593// - 2.1 look for a mix matching the attributes source
2594// - 2.2 if none found, default to device selection by policy rules
2595// At this time, the corresponding output remote submix device is also connected
2596// and active playback use cases can be transferred to this mix if needed when reconnecting
2597// after AudioTracks are invalidated
2598//
2599// When playback starts, getOutputForAttr() will:
2600// - 1 look for a mix matching the address passed in attribtutes tags if any
2601// - 2 if none found, look for a mix matching the attributes usage
2602// - 3 if none found, default to device and output selection by policy rules.
2603
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002604status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002605{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002606 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2607 status_t res = NO_ERROR;
2608
2609 sp<HwModule> rSubmixModule;
2610 // examine each mix's route type
2611 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002612 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002613 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002614 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002616 break;
2617 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002618 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002619 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002620 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002621 rSubmixModule = mHwModules.getModuleFromName(
2622 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2623 if (rSubmixModule == 0) {
2624 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2625 i);
2626 res = INVALID_OPERATION;
2627 break;
2628 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002629 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002630
Eric Laurent97ac8712018-07-27 18:59:02 -07002631 String8 address = mix.mDeviceAddress;
2632 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2633 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2634 } else {
2635 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2636 }
François Gaffie036e1e92015-03-19 10:16:24 +01002637
Eric Laurent97ac8712018-07-27 18:59:02 -07002638 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002639 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002640 res = INVALID_OPERATION;
2641 break;
2642 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002643 audio_config_t outputConfig = mix.mFormat;
2644 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002645 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2646 // stereo and let audio flinger do the channel conversion if needed.
2647 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2648 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2649 rSubmixModule->addOutputProfile(address, &outputConfig,
2650 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2651 rSubmixModule->addInputProfile(address, &inputConfig,
2652 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002653
Eric Laurent97ac8712018-07-27 18:59:02 -07002654 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002655 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2656 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002657 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002658 } else {
2659 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_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 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002663 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2664 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002665 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002666 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002667 i, mixes.size(), type, address.string());
2668
2669 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2670 mix.mDeviceType, mix.mDeviceAddress,
2671 String8(), AUDIO_FORMAT_DEFAULT);
2672 if (device == nullptr) {
2673 res = INVALID_OPERATION;
2674 break;
2675 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002676
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002677 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002678 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2679 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002680
2681 if (desc->supportedDevices().contains(device)) {
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",
Eric Laurent2c80be02019-01-23 18:06:37 -08002693 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002694 res = INVALID_OPERATION;
2695 break;
2696 } else if (!foundOutput) {
2697 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002698 i, type, 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);
François Gaffiec005e562018-11-06 15:04:49 +01002862
2863 dst->appendFormat("\nPolicy Engine dump:\n");
2864 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002865}
2866
2867status_t AudioPolicyManager::dump(int fd)
2868{
2869 String8 result;
2870 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002871 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002872 return NO_ERROR;
2873}
2874
2875// This function checks for the parameters which can be offloaded.
2876// This can be enhanced depending on the capability of the DSP and policy
2877// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002878bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002879{
2880 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002881 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002882 offloadInfo.sample_rate, offloadInfo.channel_mask,
2883 offloadInfo.format,
2884 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2885 offloadInfo.has_video);
2886
Andy Hung2ddee192015-12-18 17:34:44 -08002887 if (mMasterMono) {
2888 return false; // no offloading if mono is set.
2889 }
2890
Eric Laurente552edb2014-03-10 17:42:56 -07002891 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002892 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2893 ALOGV("offload disabled by audio.offload.disable");
2894 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002895 }
2896
2897 // Check if stream type is music, then only allow offload as of now.
2898 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2899 {
2900 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2901 return false;
2902 }
2903
2904 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002905 const bool allowOffloadWithVideo =
2906 property_get_bool("audio.offload.video", false /* default_value */);
2907 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002908 ALOGV("isOffloadSupported: has_video == true, returning false");
2909 return false;
2910 }
2911
2912 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002913 const int min_duration_secs = property_get_int32(
2914 "audio.offload.min.duration.secs", -1 /* default_value */);
2915 if (min_duration_secs >= 0) {
2916 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2917 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2918 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002919 return false;
2920 }
2921 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2922 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2923 return false;
2924 }
2925
2926 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2927 // creating an offloaded track and tearing it down immediately after start when audioflinger
2928 // detects there is an active non offloadable effect.
2929 // FIXME: We should check the audio session here but we do not have it in this context.
2930 // This may prevent offloading in rare situations where effects are left active by apps
2931 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002932 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002933 return false;
2934 }
2935
2936 // See if there is a profile to support this.
2937 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002938 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002939 offloadInfo.sample_rate,
2940 offloadInfo.format,
2941 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002942 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2943 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002944 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2945 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002946}
2947
Michael Chana94fbb22018-04-24 14:31:19 +10002948bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2949 const audio_attributes_t& attributes) {
2950 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2951 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002952 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002953 config.sample_rate,
2954 config.format,
2955 config.channel_mask,
2956 output_flags,
2957 true /* directOnly */);
2958 ALOGV("%s() profile %sfound with name: %s, "
2959 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2960 __FUNCTION__, profile != 0 ? "" : "NOT ",
2961 (profile != 0 ? profile->getTagName().string() : "null"),
2962 config.sample_rate, config.format, config.channel_mask, output_flags);
2963 return (profile != 0);
2964}
2965
Eric Laurent6a94d692014-05-20 11:18:06 -07002966status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2967 audio_port_type_t type,
2968 unsigned int *num_ports,
2969 struct audio_port *ports,
2970 unsigned int *generation)
2971{
2972 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2973 generation == NULL) {
2974 return BAD_VALUE;
2975 }
2976 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2977 if (ports == NULL) {
2978 *num_ports = 0;
2979 }
2980
2981 size_t portsWritten = 0;
2982 size_t portsMax = *num_ports;
2983 *num_ports = 0;
2984 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002985 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2986 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002987 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002988 for (const auto& dev : mAvailableOutputDevices) {
2989 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002990 continue;
2991 }
2992 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002993 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002994 }
2995 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 }
2998 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002999 for (const auto& dev : mAvailableInputDevices) {
3000 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003001 continue;
3002 }
3003 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003004 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003005 }
3006 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003008 }
3009 }
3010 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3011 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3012 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3013 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3014 }
3015 *num_ports += mInputs.size();
3016 }
3017 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003018 size_t numOutputs = 0;
3019 for (size_t i = 0; i < mOutputs.size(); i++) {
3020 if (!mOutputs[i]->isDuplicated()) {
3021 numOutputs++;
3022 if (portsWritten < portsMax) {
3023 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3024 }
3025 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003026 }
Eric Laurent84c70242014-06-23 08:46:27 -07003027 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003028 }
3029 }
3030 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003031 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003032 return NO_ERROR;
3033}
3034
Eric Laurent99fcae42018-05-17 16:59:18 -07003035status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003036{
Eric Laurent99fcae42018-05-17 16:59:18 -07003037 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3038 return BAD_VALUE;
3039 }
3040 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3041 if (dev != 0) {
3042 dev->toAudioPort(port);
3043 return NO_ERROR;
3044 }
3045 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3046 if (dev != 0) {
3047 dev->toAudioPort(port);
3048 return NO_ERROR;
3049 }
3050 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3051 if (out != 0) {
3052 out->toAudioPort(port);
3053 return NO_ERROR;
3054 }
3055 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3056 if (in != 0) {
3057 in->toAudioPort(port);
3058 return NO_ERROR;
3059 }
3060 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003061}
3062
Eric Laurent6a94d692014-05-20 11:18:06 -07003063status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3064 audio_patch_handle_t *handle,
3065 uid_t uid)
3066{
3067 ALOGV("createAudioPatch()");
3068
3069 if (handle == NULL || patch == NULL) {
3070 return BAD_VALUE;
3071 }
3072 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3073
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003074 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003075 return BAD_VALUE;
3076 }
3077 // only one source per audio patch supported for now
3078 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003079 return INVALID_OPERATION;
3080 }
Eric Laurent874c42872014-08-08 15:13:39 -07003081
3082 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003083 return INVALID_OPERATION;
3084 }
Eric Laurent874c42872014-08-08 15:13:39 -07003085 for (size_t i = 0; i < patch->num_sinks; i++) {
3086 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3087 return INVALID_OPERATION;
3088 }
3089 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003090
3091 sp<AudioPatch> patchDesc;
3092 ssize_t index = mAudioPatches.indexOfKey(*handle);
3093
Eric Laurent6a94d692014-05-20 11:18:06 -07003094 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3095 patch->sources[0].role,
3096 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003097#if LOG_NDEBUG == 0
3098 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003099 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003100 patch->sinks[i].role,
3101 patch->sinks[i].type);
3102 }
3103#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003104
3105 if (index >= 0) {
3106 patchDesc = mAudioPatches.valueAt(index);
3107 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3108 mUidCached, patchDesc->mUid, uid);
3109 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3110 return INVALID_OPERATION;
3111 }
3112 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003113 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003114 }
3115
3116 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003117 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003118 if (outputDesc == NULL) {
3119 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3120 return BAD_VALUE;
3121 }
Eric Laurent84c70242014-06-23 08:46:27 -07003122 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3123 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 if (patchDesc != 0) {
3125 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3126 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3127 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3128 return BAD_VALUE;
3129 }
3130 }
Eric Laurent874c42872014-08-08 15:13:39 -07003131 DeviceVector devices;
3132 for (size_t i = 0; i < patch->num_sinks; i++) {
3133 // Only support mix to devices connection
3134 // TODO add support for mix to mix connection
3135 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3136 ALOGV("createAudioPatch() source mix but sink is not a device");
3137 return INVALID_OPERATION;
3138 }
3139 sp<DeviceDescriptor> devDesc =
3140 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3141 if (devDesc == 0) {
3142 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3143 return BAD_VALUE;
3144 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003145
François Gaffie11d30102018-11-02 16:09:09 +01003146 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003147 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003148 NULL, // updatedSamplingRate
3149 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003150 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003151 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003152 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003153 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003154 ALOGV("createAudioPatch() profile not supported for device %08x",
3155 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003156 return INVALID_OPERATION;
3157 }
3158 devices.add(devDesc);
3159 }
3160 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 return INVALID_OPERATION;
3162 }
Eric Laurent874c42872014-08-08 15:13:39 -07003163
Eric Laurent6a94d692014-05-20 11:18:06 -07003164 // TODO: reconfigure output format and channels here
3165 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003166 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003167 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003168 index = mAudioPatches.indexOfKey(*handle);
3169 if (index >= 0) {
3170 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3171 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3172 }
3173 patchDesc = mAudioPatches.valueAt(index);
3174 patchDesc->mUid = uid;
3175 ALOGV("createAudioPatch() success");
3176 } else {
3177 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3178 return INVALID_OPERATION;
3179 }
3180 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3181 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3182 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003183 // only one sink supported when connecting an input device to a mix
3184 if (patch->num_sinks > 1) {
3185 return INVALID_OPERATION;
3186 }
François Gaffie53615e22015-03-19 09:24:12 +01003187 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003188 if (inputDesc == NULL) {
3189 return BAD_VALUE;
3190 }
3191 if (patchDesc != 0) {
3192 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3193 return BAD_VALUE;
3194 }
3195 }
François Gaffie11d30102018-11-02 16:09:09 +01003196 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003198 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003199 return BAD_VALUE;
3200 }
3201
François Gaffie11d30102018-11-02 16:09:09 +01003202 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003203 patch->sinks[0].sample_rate,
3204 NULL, /*updatedSampleRate*/
3205 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003206 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003207 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003208 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003209 // FIXME for the parameter type,
3210 // and the NONE
3211 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003212 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003213 return INVALID_OPERATION;
3214 }
3215 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003216 ALOGV("%s() setting device %s on output %d", __func__,
3217 device->toString().c_str(), inputDesc->mIoHandle);
3218 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003219 index = mAudioPatches.indexOfKey(*handle);
3220 if (index >= 0) {
3221 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3222 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3223 }
3224 patchDesc = mAudioPatches.valueAt(index);
3225 patchDesc->mUid = uid;
3226 ALOGV("createAudioPatch() success");
3227 } else {
3228 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3229 return INVALID_OPERATION;
3230 }
3231 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3232 // device to device connection
3233 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003234 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003235 return BAD_VALUE;
3236 }
3237 }
François Gaffie11d30102018-11-02 16:09:09 +01003238 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003239 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003240 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003241 return BAD_VALUE;
3242 }
Eric Laurent874c42872014-08-08 15:13:39 -07003243
Eric Laurent6a94d692014-05-20 11:18:06 -07003244 //update source and sink with our own data as the data passed in the patch may
3245 // be incomplete.
3246 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003247 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003248
Eric Laurent874c42872014-08-08 15:13:39 -07003249 for (size_t i = 0; i < patch->num_sinks; i++) {
3250 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3251 ALOGV("createAudioPatch() source device but one sink is not a device");
3252 return INVALID_OPERATION;
3253 }
3254
François Gaffie11d30102018-11-02 16:09:09 +01003255 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003256 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003257 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003258 return BAD_VALUE;
3259 }
François Gaffie11d30102018-11-02 16:09:09 +01003260 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003261
Eric Laurent3bcf8592015-04-03 12:13:24 -07003262 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003263 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003264 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003265 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003266 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3267 (srcDevice->getModuleVersionMajor() < 3) ||
3268 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003269 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003270 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003271 return INVALID_OPERATION;
3272 }
Eric Laurent874c42872014-08-08 15:13:39 -07003273 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003274 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003275 // if the sink device is reachable via an opened output stream, request to go via
3276 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003277 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003278 if (output != AUDIO_IO_HANDLE_NONE) {
3279 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3280 if (outputDesc->isDuplicated()) {
3281 return INVALID_OPERATION;
3282 }
3283 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003284 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003285 newPatch.num_sources = 2;
3286 }
Eric Laurent83b88082014-06-20 18:31:16 -07003287 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003288 }
3289 // TODO: check from routing capabilities in config file and other conflicting patches
3290
Mikhail Naganovdc769682018-05-04 15:34:08 -07003291 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3292 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003293 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3294 status);
3295 return INVALID_OPERATION;
3296 }
3297 } else {
3298 return BAD_VALUE;
3299 }
3300 } else {
3301 return BAD_VALUE;
3302 }
3303 return NO_ERROR;
3304}
3305
3306status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3307 uid_t uid)
3308{
3309 ALOGV("releaseAudioPatch() patch %d", handle);
3310
3311 ssize_t index = mAudioPatches.indexOfKey(handle);
3312
3313 if (index < 0) {
3314 return BAD_VALUE;
3315 }
3316 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3317 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3318 mUidCached, patchDesc->mUid, uid);
3319 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3320 return INVALID_OPERATION;
3321 }
3322
3323 struct audio_patch *patch = &patchDesc->mPatch;
3324 patchDesc->mUid = mUidCached;
3325 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003326 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003327 if (outputDesc == NULL) {
3328 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3329 return BAD_VALUE;
3330 }
3331
François Gaffie11d30102018-11-02 16:09:09 +01003332 setOutputDevices(outputDesc,
3333 getNewOutputDevices(outputDesc, true /*fromCache*/),
3334 true,
3335 0,
3336 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003337 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3338 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003339 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003340 if (inputDesc == NULL) {
3341 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3342 return BAD_VALUE;
3343 }
3344 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003345 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003346 true,
3347 NULL);
3348 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003349 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3350 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3351 status, patchDesc->mAfPatchHandle);
3352 removeAudioPatch(patchDesc->mHandle);
3353 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003354 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003355 } else {
3356 return BAD_VALUE;
3357 }
3358 } else {
3359 return BAD_VALUE;
3360 }
3361 return NO_ERROR;
3362}
3363
3364status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3365 struct audio_patch *patches,
3366 unsigned int *generation)
3367{
François Gaffie53615e22015-03-19 09:24:12 +01003368 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003369 return BAD_VALUE;
3370 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003371 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003372 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003373}
3374
Eric Laurente1715a42014-05-20 11:30:42 -07003375status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003376{
Eric Laurente1715a42014-05-20 11:30:42 -07003377 ALOGV("setAudioPortConfig()");
3378
3379 if (config == NULL) {
3380 return BAD_VALUE;
3381 }
3382 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3383 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003384 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3385 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003386 }
3387
Eric Laurenta121f902014-06-03 13:32:54 -07003388 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003389 if (config->type == AUDIO_PORT_TYPE_MIX) {
3390 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003392 if (outputDesc == NULL) {
3393 return BAD_VALUE;
3394 }
Eric Laurent84c70242014-06-23 08:46:27 -07003395 ALOG_ASSERT(!outputDesc->isDuplicated(),
3396 "setAudioPortConfig() called on duplicated output %d",
3397 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003398 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003399 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003400 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003401 if (inputDesc == NULL) {
3402 return BAD_VALUE;
3403 }
Eric Laurenta121f902014-06-03 13:32:54 -07003404 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003405 } else {
3406 return BAD_VALUE;
3407 }
3408 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3409 sp<DeviceDescriptor> deviceDesc;
3410 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3411 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3412 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3413 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3414 } else {
3415 return BAD_VALUE;
3416 }
3417 if (deviceDesc == NULL) {
3418 return BAD_VALUE;
3419 }
Eric Laurenta121f902014-06-03 13:32:54 -07003420 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003421 } else {
3422 return BAD_VALUE;
3423 }
3424
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003425 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003426 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3427 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003428 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003429 audioPortConfig->toAudioPortConfig(&newConfig, config);
3430 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003431 }
Eric Laurenta121f902014-06-03 13:32:54 -07003432 if (status != NO_ERROR) {
3433 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003434 }
Eric Laurente1715a42014-05-20 11:30:42 -07003435
3436 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003437}
3438
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003439void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3440{
Eric Laurentd60560a2015-04-10 11:31:20 -07003441 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003442 clearAudioPatches(uid);
3443 clearSessionRoutes(uid);
3444}
3445
Eric Laurent6a94d692014-05-20 11:18:06 -07003446void AudioPolicyManager::clearAudioPatches(uid_t uid)
3447{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003448 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003449 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3450 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003451 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003452 }
3453 }
3454}
3455
François Gaffiec005e562018-11-06 15:04:49 +01003456void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003457{
François Gaffiec005e562018-11-06 15:04:49 +01003458 // Take the first attributes following the product strategy as it is used to retrieve the routed
3459 // device. All attributes wihin a strategy follows the same "routing strategy"
3460 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
3461 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01003462 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003463 for (size_t j = 0; j < mOutputs.size(); j++) {
3464 if (mOutputs.keyAt(j) == ouptutToSkip) {
3465 continue;
3466 }
3467 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01003468 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003469 continue;
3470 }
3471 // If the default device for this strategy is on another output mix,
3472 // invalidate all tracks in this strategy to force re connection.
3473 // Otherwise select new device on the output mix.
3474 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01003475 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
3476 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003477 }
3478 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003479 setOutputDevices(
3480 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003481 }
3482 }
3483}
3484
3485void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3486{
3487 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01003488 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003489 for (size_t i = 0; i < mOutputs.size(); i++) {
3490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003491 for (const auto& client : outputDesc->getClientIterable()) {
3492 if (client->hasPreferredDevice() && client->uid() == uid) {
3493 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01003494 auto clientStrategy = client->strategy();
3495 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
3496 end(affectedStrategies)) {
3497 continue;
3498 }
3499 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003500 }
3501 }
3502 }
3503 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003504 for (const auto& strategy : affectedStrategies) {
3505 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003506 }
3507
3508 // remove input routes associated with this uid
3509 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003510 for (size_t i = 0; i < mInputs.size(); i++) {
3511 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003512 for (const auto& client : inputDesc->getClientIterable()) {
3513 if (client->hasPreferredDevice() && client->uid() == uid) {
3514 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3515 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003516 }
3517 }
3518 }
3519 // reroute inputs if necessary
3520 SortedVector<audio_io_handle_t> inputsToClose;
3521 for (size_t i = 0; i < mInputs.size(); i++) {
3522 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003523 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003524 inputsToClose.add(inputDesc->mIoHandle);
3525 }
3526 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003527 for (const auto& input : inputsToClose) {
3528 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003529 }
3530}
3531
Eric Laurentd60560a2015-04-10 11:31:20 -07003532void AudioPolicyManager::clearAudioSources(uid_t uid)
3533{
3534 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003535 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3536 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003537 stopAudioSource(mAudioSources.keyAt(i));
3538 }
3539 }
3540}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003541
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003542status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3543 audio_io_handle_t *ioHandle,
3544 audio_devices_t *device)
3545{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003546 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3547 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003548 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01003549 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003550
François Gaffiedf372692015-03-19 10:43:27 +01003551 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003552}
3553
Eric Laurentd60560a2015-04-10 11:31:20 -07003554status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003555 const audio_attributes_t *attributes,
3556 audio_port_handle_t *portId,
3557 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003558{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003559 ALOGV("%s", __FUNCTION__);
3560 *portId = AUDIO_PORT_HANDLE_NONE;
3561
3562 if (source == NULL || attributes == NULL || portId == NULL) {
3563 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3564 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003565 return BAD_VALUE;
3566 }
3567
Eric Laurentd60560a2015-04-10 11:31:20 -07003568 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3569 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003570 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3571 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003572 return INVALID_OPERATION;
3573 }
3574
François Gaffie11d30102018-11-02 16:09:09 +01003575 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003576 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003577 String8(source->ext.device.address),
3578 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003579 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003580 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003581 return BAD_VALUE;
3582 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003583
3584 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003585
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003586 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003587 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003588
3589 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003590 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
François Gaffiec005e562018-11-06 15:04:49 +01003591 mEngine->getStreamTypeForAttributes(*attributes),
3592 mEngine->getProductStrategyForAttributes(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003593
3594 status_t status = connectAudioSource(sourceDesc);
3595 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003596 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003597 }
3598 return status;
3599}
3600
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003601status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003602{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003603 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003604
3605 // make sure we only have one patch per source.
3606 disconnectAudioSource(sourceDesc);
3607
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003608 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003609 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003610 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003611
François Gaffiec005e562018-11-06 15:04:49 +01003612 DeviceVector sinkDevices =
3613 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
3614 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01003615 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3616 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3617 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003618
3619 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003620
François Gaffie11d30102018-11-02 16:09:09 +01003621 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3622 srcDevice->getModuleVersionMajor() >= 3 &&
3623 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3624 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003625 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003626 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003627 // create patch between src device and output device
3628 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003629 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003630 audio_attributes_t resultAttr;
3631 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3632 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3633 config.sample_rate = sourceDesc->config().sample_rate;
3634 config.channel_mask = sourceDesc->config().channel_mask;
3635 config.format = sourceDesc->config().format;
3636 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3637 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffief579db52018-11-13 11:25:16 +01003638 bool isRequestedDeviceForExclusiveUse = false;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003639 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
François Gaffief579db52018-11-13 11:25:16 +01003640 &attributes, &stream, sourceDesc->uid(), &config, &flags,
3641 &selectedDeviceId, &isRequestedDeviceForExclusiveUse);
Eric Laurentd60560a2015-04-10 11:31:20 -07003642 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003643 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003644 return INVALID_OPERATION;
3645 }
3646 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3647 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003648 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003649 return INVALID_OPERATION;
3650 }
Eric Laurent733ce942017-12-07 12:18:25 -08003651 status_t status = outputDesc->start();
3652 if (status != NO_ERROR) {
3653 return status;
3654 }
3655
Eric Laurentd60560a2015-04-10 11:31:20 -07003656 // create a special patch with no sink and two sources:
3657 // - the second source indicates to PatchPanel through which output mix this patch should
3658 // be connected as well as the stream type for volume control
3659 // - the sink is defined by whatever output device is currently selected for the output
3660 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003661 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003662 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003663 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003664 &afPatchHandle,
3665 0);
3666 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3667 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003668 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003669 if (status != NO_ERROR) {
3670 ALOGW("%s patch panel could not connect device patch, error %d",
3671 __FUNCTION__, status);
3672 return INVALID_OPERATION;
3673 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003674
3675 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3676 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3677 return INVALID_OPERATION;
3678 }
3679 outputDesc->addClient(sourceDesc);
3680
Eric Laurentd60560a2015-04-10 11:31:20 -07003681 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003682 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003683
3684 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003685 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003686 return status;
3687 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003688 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003689 if (delayMs != 0) {
3690 usleep(delayMs * 1000);
3691 }
3692 }
3693
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003694 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3695 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003696
3697 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003698}
3699
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003700status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003701{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003702 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3703 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003704 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003705 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003706 return BAD_VALUE;
3707 }
3708 status_t status = disconnectAudioSource(sourceDesc);
3709
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003710 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003711 return status;
3712}
3713
Andy Hung2ddee192015-12-18 17:34:44 -08003714status_t AudioPolicyManager::setMasterMono(bool mono)
3715{
3716 if (mMasterMono == mono) {
3717 return NO_ERROR;
3718 }
3719 mMasterMono = mono;
3720 // if enabling mono we close all offloaded devices, which will invalidate the
3721 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3722 // for recreating the new AudioTrack as non-offloaded PCM.
3723 //
3724 // If disabling mono, we leave all tracks as is: we don't know which clients
3725 // and tracks are able to be recreated as offloaded. The next "song" should
3726 // play back offloaded.
3727 if (mMasterMono) {
3728 Vector<audio_io_handle_t> offloaded;
3729 for (size_t i = 0; i < mOutputs.size(); ++i) {
3730 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3731 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3732 offloaded.push(desc->mIoHandle);
3733 }
3734 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003735 for (const auto& handle : offloaded) {
3736 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003737 }
3738 }
3739 // update master mono for all remaining outputs
3740 for (size_t i = 0; i < mOutputs.size(); ++i) {
3741 updateMono(mOutputs.keyAt(i));
3742 }
3743 return NO_ERROR;
3744}
3745
3746status_t AudioPolicyManager::getMasterMono(bool *mono)
3747{
3748 *mono = mMasterMono;
3749 return NO_ERROR;
3750}
3751
Eric Laurentac9cef52017-06-09 15:46:26 -07003752float AudioPolicyManager::getStreamVolumeDB(
3753 audio_stream_type_t stream, int index, audio_devices_t device)
3754{
3755 return computeVolume(stream, index, device);
3756}
3757
jiabin81772902018-04-02 17:52:27 -07003758status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3759 audio_format_t *surroundFormats,
3760 bool *surroundFormatsEnabled,
3761 bool reported)
3762{
3763 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3764 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3765 return BAD_VALUE;
3766 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003767 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3768 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003769
3770 size_t formatsWritten = 0;
3771 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003772 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003773 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003774 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003775 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003776 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3777 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3778 FormatVector supportedFormats =
3779 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3780 for (size_t j = 0; j < supportedFormats.size(); j++) {
3781 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3782 formats.insert(supportedFormats[j]);
3783 } else {
3784 for (const auto& pair : mConfig.getSurroundFormats()) {
3785 if (pair.second.count(supportedFormats[j]) != 0) {
3786 formats.insert(pair.first);
3787 break;
3788 }
3789 }
3790 }
3791 }
jiabin81772902018-04-02 17:52:27 -07003792 }
3793 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003794 for (const auto& pair : mConfig.getSurroundFormats()) {
3795 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003796 }
3797 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003798 *numSurroundFormats = formats.size();
3799 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3800 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003801 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003802 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003803 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003804 bool formatEnabled = true;
3805 switch (forceUse) {
3806 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3807 formatEnabled = mManualSurroundFormats.count(format) != 0;
3808 break;
3809 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3810 formatEnabled = false;
3811 break;
3812 default: // AUTO or ALWAYS => true
3813 break;
jiabin81772902018-04-02 17:52:27 -07003814 }
3815 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3816 }
jiabin81772902018-04-02 17:52:27 -07003817 }
3818 return NO_ERROR;
3819}
3820
3821status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3822{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003823 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003824 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3825 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003826 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003827 return BAD_VALUE;
3828 }
3829
Mikhail Naganov100f0122018-11-29 11:22:16 -08003830 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3831 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003832 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003833 return INVALID_OPERATION;
3834 }
3835
Mikhail Naganov100f0122018-11-29 11:22:16 -08003836 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003837 return NO_ERROR;
3838 }
3839
Mikhail Naganov100f0122018-11-29 11:22:16 -08003840 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003841 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003842 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003843 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003844 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003845 }
3846 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003847 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003848 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003849 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003850 }
3851 }
3852
3853 sp<SwAudioOutputDescriptor> outputDesc;
3854 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003855 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003856 AUDIO_DEVICE_OUT_HDMI);
3857 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3858 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003859 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003860 String8 name = hdmiOutputDevices[i]->getName();
3861 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3862 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3863 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003864 name.c_str(),
3865 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003866 if (status != NO_ERROR) {
3867 continue;
3868 }
3869 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3870 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3871 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003872 name.c_str(),
3873 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003874 profileUpdated |= (status == NO_ERROR);
3875 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003876 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003877 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003878 AUDIO_DEVICE_IN_HDMI);
3879 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3880 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003881 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003882 String8 name = hdmiInputDevices[i]->getName();
3883 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3884 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3885 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003886 name.c_str(),
3887 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003888 if (status != NO_ERROR) {
3889 continue;
3890 }
3891 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3892 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3893 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003894 name.c_str(),
3895 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003896 profileUpdated |= (status == NO_ERROR);
3897 }
3898
jiabin81772902018-04-02 17:52:27 -07003899 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003900 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003901 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003902 }
3903
3904 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3905}
3906
Eric Laurentf32108e2018-10-04 17:22:04 -07003907void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003908{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003909 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003910
Eric Laurenta9f86652018-11-28 17:23:11 -08003911 for (size_t i = 0; i < mInputs.size(); i++) {
3912 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3913 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003914 for (const auto& client : clients) {
3915 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003916 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003917 }
3918 }
3919 }
3920}
3921
jiabin6012f912018-11-02 17:06:30 -07003922bool AudioPolicyManager::isHapticPlaybackSupported()
3923{
3924 for (const auto& hwModule : mHwModules) {
3925 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3926 for (const auto &outProfile : outputProfiles) {
3927 struct audio_port audioPort;
3928 outProfile->toAudioPort(&audioPort);
3929 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3930 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3931 return true;
3932 }
3933 }
3934 }
3935 }
3936 return false;
3937}
3938
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003939status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003940{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003941 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003942
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003943 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003944 if (patchDesc == 0) {
3945 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003946 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003947 return BAD_VALUE;
3948 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003949 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003950
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003951 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003952 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003953 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003954 if (status == NO_ERROR) {
3955 swOutputDesc->stop();
3956 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003957 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3958 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003959 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003960 if (hwOutputDesc != 0) {
3961 // release patch between src device and output device
3962 // close Hwoutput and remove from mHwOutputs
3963 } else {
3964 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3965 }
3966 }
3967 return NO_ERROR;
3968}
3969
François Gaffiec005e562018-11-06 15:04:49 +01003970sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
3971 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07003972{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003973 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003974 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003975 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003976 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01003977 if (followsSameRouting(attr, sourceDesc->attributes()) &&
3978 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003979 source = sourceDesc;
3980 break;
3981 }
3982 }
3983 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003984}
3985
Eric Laurente552edb2014-03-10 17:42:56 -07003986// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003987// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003988// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003989uint32_t AudioPolicyManager::nextAudioPortGeneration()
3990{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003991 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003992}
3993
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003994// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3995static const char *kConfigLocationList[] =
3996 {"/odm/etc", "/vendor/etc", "/system/etc"};
3997static const int kConfigLocationListSize =
3998 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3999
4000static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4001 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004002 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004003 status_t ret;
4004
Petri Gyntherf497f292018-04-17 18:46:10 -07004005 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
4006 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4007 // A2DP offload supported but disabled: try to use special XML file
4008 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4009 }
4010 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4011
4012 for (const char* fileName : fileNames) {
4013 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004014 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4015 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004016 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004017 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004018 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004019 return ret;
4020 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004021 }
4022 }
4023 return ret;
4024}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004025
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004026AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4027 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004028 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004029 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004030 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004031 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004032 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004033 mVolumeCurves(new VolumeCurvesCollection()),
4034 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004035 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004036 mAudioPortGeneration(1),
4037 mBeaconMuteRefCount(0),
4038 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004039 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004040 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004041 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004042 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004043{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004044}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004045
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004046AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4047 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4048{
4049 loadConfig();
4050 initialize();
4051}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004052
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004053// This check is to catch any legacy platform updating to Q without having
4054// switched to XML since its deprecation on O.
4055// TODO: after Q release, remove this check and flag as XML is now the only
4056// option and all legacy platform should have transitioned to XML.
4057#ifndef USE_XML_AUDIO_POLICY_CONF
4058#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004059#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004060
4061void AudioPolicyManager::loadConfig() {
4062 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004063 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004064 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004065 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004066}
4067
4068status_t AudioPolicyManager::initialize() {
4069 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004070
4071 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004072 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4073 if (!engineInstance) {
4074 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004075 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004076 }
4077 // Retrieve the Policy Manager Interface
4078 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4079 if (mEngine == NULL) {
4080 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004081 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004082 }
4083 mEngine->setObserver(this);
4084 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004085 if (status != NO_ERROR) {
4086 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4087 return status;
4088 }
François Gaffie2110e042015-03-24 08:41:51 +01004089
Eric Laurent3a4311c2014-03-17 12:00:47 -07004090 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004091 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004092 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004093 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004094 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4095 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004096 continue;
4097 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004098 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004099 // open all output streams needed to access attached devices
4100 // except for direct output streams that are only opened when they are actually
4101 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004102 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004103 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004104 if (!outProfile->canOpenNewIo()) {
4105 ALOGE("Invalid Output profile max open count %u for profile %s",
4106 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4107 continue;
4108 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004109 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004110 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 continue;
4112 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004113 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004114 mTtsOutputAvailable = true;
4115 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004116
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004117 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004118 continue;
4119 }
François Gaffie11d30102018-11-02 16:09:09 +01004120 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4121 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4122 sp<DeviceDescriptor> supportedDevice = 0;
4123 if (supportedDevices.contains(mDefaultOutputDevice)) {
4124 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004125 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004126 // choose first device present in profile's SupportedDevices also part of
4127 // mAvailableOutputDevices.
4128 if (availProfileDevices.isEmpty()) {
4129 continue;
4130 }
4131 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004132 }
François Gaffie11d30102018-11-02 16:09:09 +01004133 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004134 continue;
4135 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004136 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4137 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004138 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004139 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4140 AUDIO_STREAM_DEFAULT,
4141 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004142 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004143 ALOGW("Cannot open output stream for devices %s on hw module %s",
4144 supportedDevice->toString().c_str(), hwModule->getName());
4145 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004146 }
François Gaffie11d30102018-11-02 16:09:09 +01004147 for (const auto &device : availProfileDevices) {
4148 // give a valid ID to an attached device once confirmed it is reachable
4149 if (!device->isAttached()) {
4150 device->attach(hwModule);
4151 }
4152 }
4153 if (mPrimaryOutput == 0 &&
4154 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4155 mPrimaryOutput = outputDesc;
4156 }
4157 addOutput(output, outputDesc);
4158 setOutputDevices(outputDesc,
4159 DeviceVector(supportedDevice),
4160 true,
4161 0,
4162 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004163 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004164 // open input streams needed to access attached devices to validate
4165 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004166 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004167 if (!inProfile->canOpenNewIo()) {
4168 ALOGE("Invalid Input profile max open count %u for profile %s",
4169 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4170 continue;
4171 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004172 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004173 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004174 continue;
4175 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004176 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004177 // available input devices
4178 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4179 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4180 if (availProfileDevices.isEmpty()) {
4181 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004182 continue;
4183 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004184 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004185 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004186
Eric Laurentd78f1532014-09-16 16:38:20 -07004187 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004188 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004189 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004190 AUDIO_SOURCE_MIC,
4191 AUDIO_INPUT_FLAG_NONE,
4192 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004193 if (status != NO_ERROR) {
4194 ALOGW("Cannot open input stream for device %s on hw module %s",
4195 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004196 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004197 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004198 }
François Gaffie11d30102018-11-02 16:09:09 +01004199 for (const auto &device : availProfileDevices) {
4200 // give a valid ID to an attached device once confirmed it is reachable
4201 if (!device->isAttached()) {
4202 device->attach(hwModule);
4203 device->importAudioPort(inProfile, true);
4204 }
4205 }
4206 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004207 }
4208 }
4209 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004210 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004211 for (size_t i = 0; i < devices.size();) {
4212 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004213 if (!device->isAttached()) {
4214 ALOGW("device %s is unreachable", device->toString().c_str());
4215 devices.remove(device);
4216 continue;
4217 }
4218 // Device is now validated and can be appended to the available devices of the engine
4219 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004220 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004221 }
François Gaffie11d30102018-11-02 16:09:09 +01004222 };
4223 checkAndSetAvailable(mAvailableOutputDevices);
4224 checkAndSetAvailable(mAvailableInputDevices);
4225
Eric Laurent3a4311c2014-03-17 12:00:47 -07004226 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004227 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4228 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4229 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004230 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004231 }
jiabin9ff780e2018-03-19 18:19:52 -07004232 // If microphones address is empty, set it according to device type
4233 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004234 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004235 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004236 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004237 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004238 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004239 }
4240 }
4241 }
Eric Laurente552edb2014-03-10 17:42:56 -07004242
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004243 if (mPrimaryOutput == 0) {
4244 ALOGE("Failed to open primary output");
4245 status = NO_INIT;
4246 }
Eric Laurente552edb2014-03-10 17:42:56 -07004247
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004248 // Silence ALOGV statements
4249 property_set("log.tag." LOG_TAG, "D");
4250
Eric Laurente552edb2014-03-10 17:42:56 -07004251 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004252 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004253}
4254
Eric Laurente0720872014-03-11 09:30:41 -07004255AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004256{
Eric Laurente552edb2014-03-10 17:42:56 -07004257 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004258 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004259 }
4260 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004261 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004262 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004263 mAvailableOutputDevices.clear();
4264 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004265 mOutputs.clear();
4266 mInputs.clear();
4267 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004268 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004269 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004270}
4271
Eric Laurente0720872014-03-11 09:30:41 -07004272status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004273{
Eric Laurent87ffa392015-05-22 10:32:38 -07004274 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004275}
4276
Eric Laurente552edb2014-03-10 17:42:56 -07004277// ---
4278
Eric Laurent98e38192018-02-15 18:31:53 -08004279void AudioPolicyManager::addOutput(audio_io_handle_t output,
4280 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004281{
Eric Laurent1c333e22014-05-20 10:48:17 -07004282 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004283 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004284 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004285 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004286 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004287}
4288
François Gaffie53615e22015-03-19 09:24:12 +01004289void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4290{
4291 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004292 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004293}
4294
Eric Laurent98e38192018-02-15 18:31:53 -08004295void AudioPolicyManager::addInput(audio_io_handle_t input,
4296 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004297{
Eric Laurent1c333e22014-05-20 10:48:17 -07004298 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004299 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004300}
Eric Laurente552edb2014-03-10 17:42:56 -07004301
François Gaffie11d30102018-11-02 16:09:09 +01004302status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004303 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004304 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004305{
François Gaffie11d30102018-11-02 16:09:09 +01004306 audio_devices_t deviceType = device->type();
4307 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004308 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004309
François Gaffie11d30102018-11-02 16:09:09 +01004310 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004311 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004312 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004313 }
Eric Laurente552edb2014-03-10 17:42:56 -07004314
Eric Laurent3b73df72014-03-11 09:06:29 -07004315 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004316 // first list already open outputs that can be routed to this device
4317 for (size_t i = 0; i < mOutputs.size(); i++) {
4318 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004319 if (!desc->isDuplicated() && desc->supportsDevice(device)
4320 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004321 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4322 mOutputs.keyAt(i), device->toString().c_str());
4323 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004324 }
4325 }
4326 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004327 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004328 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004329 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4330 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004331 if (profile->supportsDevice(device)) {
4332 profiles.add(profile);
4333 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4334 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004335 }
4336 }
4337 }
4338
Eric Laurent7b279bb2015-12-14 10:18:23 -08004339 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004340
Eric Laurente552edb2014-03-10 17:42:56 -07004341 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004342 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004343 return BAD_VALUE;
4344 }
4345
4346 // open outputs for matching profiles if needed. Direct outputs are also opened to
4347 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4348 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004349 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004350
4351 // nothing to do if one output is already opened for this profile
4352 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004353 for (j = 0; j < outputs.size(); j++) {
4354 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004355 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004356 // matching profile: save the sample rates, format and channel masks supported
4357 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004358 if (audio_device_is_digital(deviceType)) {
4359 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004360 }
Eric Laurente552edb2014-03-10 17:42:56 -07004361 break;
4362 }
4363 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004364 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004365 continue;
4366 }
4367
Eric Laurent3974e3b2017-12-07 17:58:43 -08004368 if (!profile->canOpenNewIo()) {
4369 ALOGW("Max Output number %u already opened for this profile %s",
4370 profile->maxOpenCount, profile->getTagName().c_str());
4371 continue;
4372 }
4373
Eric Laurent83efe1c2017-07-09 16:51:08 -07004374 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004375 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004376 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004377 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004378 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004379 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004380
Eric Laurentfe231122017-11-17 17:48:06 -08004381 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004382 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004383 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004384 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004385 mpClientInterface->setParameters(output, String8(param));
4386 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004387 }
François Gaffie11d30102018-11-02 16:09:09 +01004388 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004389 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004390 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004391 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004392 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004393 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004394 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004395 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004396 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4397 profile->pickAudioProfile(
4398 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004399 config.offload_info.sample_rate = config.sample_rate;
4400 config.offload_info.channel_mask = config.channel_mask;
4401 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004402
François Gaffie11d30102018-11-02 16:09:09 +01004403 status_t status = desc->open(&config, DeviceVector(device),
4404 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004405 AUDIO_OUTPUT_FLAG_NONE, &output);
4406 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004407 output = AUDIO_IO_HANDLE_NONE;
4408 }
Eric Laurentd4692962014-05-05 18:13:44 -07004409 }
4410
Eric Laurentcf2c0212014-07-25 16:20:43 -07004411 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004412 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004413 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004414 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004415 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4416 policyMix->setOutput(desc);
4417 desc->mPolicyMix = policyMix->getMix();
4418 } else {
4419 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004420 address.string());
4421 }
François Gaffie036e1e92015-03-19 10:16:24 +01004422
Eric Laurent87ffa392015-05-22 10:32:38 -07004423 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4424 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004425 // no duplicated output for direct outputs and
4426 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004427 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004428
Eric Laurentd4692962014-05-05 18:13:44 -07004429 //TODO: configure audio effect output stage here
4430
4431 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004432 sp<SwAudioOutputDescriptor> dupOutputDesc =
4433 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4434 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4435 &duplicatedOutput);
4436 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004437 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004438 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004439 } else {
4440 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004441 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004442 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004443 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004444 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004445 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004446 }
Eric Laurente552edb2014-03-10 17:42:56 -07004447 }
4448 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004449 } else {
4450 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004451 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004452 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004453 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004454 profiles.removeAt(profile_index);
4455 profile_index--;
4456 } else {
4457 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004458 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004459 if (audio_device_is_digital(deviceType)) {
4460 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004461 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004462
François Gaffie11d30102018-11-02 16:09:09 +01004463 if (device_distinguishes_on_address(deviceType)) {
4464 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4465 device->toString().c_str());
4466 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4467 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004468 }
Eric Laurente552edb2014-03-10 17:42:56 -07004469 ALOGV("checkOutputsForDevice(): adding output %d", output);
4470 }
4471 }
4472
4473 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004474 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004475 return BAD_VALUE;
4476 }
Eric Laurentd4692962014-05-05 18:13:44 -07004477 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004478 // check if one opened output is not needed any more after disconnecting one device
4479 for (size_t i = 0; i < mOutputs.size(); i++) {
4480 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004481 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004482 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004483 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4484 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004485 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004486 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004487 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4488 mOutputs.keyAt(i));
4489 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004490 }
Eric Laurente552edb2014-03-10 17:42:56 -07004491 }
4492 }
Eric Laurentd4692962014-05-05 18:13:44 -07004493 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004494 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004495 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4496 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004497 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004498 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004499 "clearing direct output profile %zu on module %s",
4500 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004501 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004502 }
4503 }
4504 }
4505 }
4506 return NO_ERROR;
4507}
4508
François Gaffie11d30102018-11-02 16:09:09 +01004509status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004510 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004511 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004512{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004513 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004514
François Gaffie11d30102018-11-02 16:09:09 +01004515 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004516 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004517 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004518 }
4519
Eric Laurentd4692962014-05-05 18:13:44 -07004520 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4521 // first list already open inputs that can be routed to this device
4522 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4523 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004524 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004525 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4526 inputs.add(mInputs.keyAt(input_index));
4527 }
4528 }
4529
4530 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004531 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004532 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004533 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004534 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004535 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004536 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004537
François Gaffie11d30102018-11-02 16:09:09 +01004538 if (profile->supportsDevice(device)) {
4539 profiles.add(profile);
4540 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4541 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004542 }
4543 }
4544 }
4545
4546 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004547 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004548 return BAD_VALUE;
4549 }
4550
4551 // open inputs for matching profiles if needed. Direct inputs are also opened to
4552 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4553 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4554
Eric Laurent1c333e22014-05-20 10:48:17 -07004555 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004556
Eric Laurentd4692962014-05-05 18:13:44 -07004557 // nothing to do if one input is already opened for this profile
4558 size_t input_index;
4559 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4560 desc = mInputs.valueAt(input_index);
4561 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004562 if (audio_device_is_digital(device->type())) {
4563 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004564 }
Eric Laurentd4692962014-05-05 18:13:44 -07004565 break;
4566 }
4567 }
4568 if (input_index != mInputs.size()) {
4569 continue;
4570 }
4571
Eric Laurent3974e3b2017-12-07 17:58:43 -08004572 if (!profile->canOpenNewIo()) {
4573 ALOGW("Max Input number %u already opened for this profile %s",
4574 profile->maxOpenCount, profile->getTagName().c_str());
4575 continue;
4576 }
4577
Eric Laurentfe231122017-11-17 17:48:06 -08004578 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004579 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004580 status_t status = desc->open(nullptr,
4581 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004582 AUDIO_SOURCE_MIC,
4583 AUDIO_INPUT_FLAG_NONE,
4584 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004585
Eric Laurentcf2c0212014-07-25 16:20:43 -07004586 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004587 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004588 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004589 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004590 mpClientInterface->setParameters(input, String8(param));
4591 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004592 }
François Gaffie11d30102018-11-02 16:09:09 +01004593 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004594 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004595 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004596 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004597 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004598 }
4599
4600 if (input != 0) {
4601 addInput(input, desc);
4602 }
4603 } // endif input != 0
4604
Eric Laurentcf2c0212014-07-25 16:20:43 -07004605 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004606 ALOGW("%s could not open input for device %s", __func__,
4607 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004608 profiles.removeAt(profile_index);
4609 profile_index--;
4610 } else {
4611 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004612 if (audio_device_is_digital(device->type())) {
4613 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004614 }
Eric Laurentd4692962014-05-05 18:13:44 -07004615 ALOGV("checkInputsForDevice(): adding input %d", input);
4616 }
4617 } // end scan profiles
4618
4619 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004620 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004621 return BAD_VALUE;
4622 }
4623 } else {
4624 // Disconnect
4625 // check if one opened input is not needed any more after disconnecting one device
4626 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4627 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004628 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004629 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4630 mInputs.keyAt(input_index));
4631 inputs.add(mInputs.keyAt(input_index));
4632 }
4633 }
4634 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004635 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004636 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004637 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004638 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004639 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004640 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004641 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4642 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004643 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004644 }
4645 }
4646 }
4647 } // end disconnect
4648
4649 return NO_ERROR;
4650}
4651
4652
Eric Laurente0720872014-03-11 09:30:41 -07004653void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004654{
4655 ALOGV("closeOutput(%d)", output);
4656
Eric Laurentc75307b2015-03-17 15:29:32 -07004657 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004658 if (outputDesc == NULL) {
4659 ALOGW("closeOutput() unknown output %d", output);
4660 return;
4661 }
François Gaffie036e1e92015-03-19 10:16:24 +01004662 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004663
Eric Laurente552edb2014-03-10 17:42:56 -07004664 // look for duplicated outputs connected to the output being removed.
4665 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004666 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004667 if (dupOutputDesc->isDuplicated() &&
4668 (dupOutputDesc->mOutput1 == outputDesc ||
4669 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004670 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004671 if (dupOutputDesc->mOutput1 == outputDesc) {
4672 outputDesc2 = dupOutputDesc->mOutput2;
4673 } else {
4674 outputDesc2 = dupOutputDesc->mOutput1;
4675 }
4676 // As all active tracks on duplicated output will be deleted,
4677 // and as they were also referenced on the other output, the reference
4678 // count for their stream type must be adjusted accordingly on
4679 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004680 const bool wasActive = outputDesc2->isActive();
4681 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4682 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004683 }
Eric Laurent733ce942017-12-07 12:18:25 -08004684 // stop() will be a no op if the output is still active but is needed in case all
4685 // active streams refcounts where cleared above
4686 if (wasActive) {
4687 outputDesc2->stop();
4688 }
Eric Laurente552edb2014-03-10 17:42:56 -07004689 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4690 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4691
4692 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004693 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 }
4695 }
4696
Eric Laurent05b90f82014-08-27 15:32:29 -07004697 nextAudioPortGeneration();
4698
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004699 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004700 if (index >= 0) {
4701 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004702 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004703 mAudioPatches.removeItemsAt(index);
4704 mpClientInterface->onAudioPatchListUpdate();
4705 }
4706
Eric Laurentfe231122017-11-17 17:48:06 -08004707 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004708
François Gaffie53615e22015-03-19 09:24:12 +01004709 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004710 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004711
4712 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4713 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004714 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004715 bool directOutputOpen = false;
4716 for (size_t i = 0; i < mOutputs.size(); i++) {
4717 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4718 directOutputOpen = true;
4719 break;
4720 }
4721 }
4722 if (!directOutputOpen) {
4723 ALOGV("no direct outputs open, reset MSD patch");
4724 setMsdPatch();
4725 }
4726 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004727}
4728
4729void AudioPolicyManager::closeInput(audio_io_handle_t input)
4730{
4731 ALOGV("closeInput(%d)", input);
4732
4733 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4734 if (inputDesc == NULL) {
4735 ALOGW("closeInput() unknown input %d", input);
4736 return;
4737 }
4738
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004740
François Gaffie11d30102018-11-02 16:09:09 +01004741 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004742 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004743 if (index >= 0) {
4744 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004745 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004746 mAudioPatches.removeItemsAt(index);
4747 mpClientInterface->onAudioPatchListUpdate();
4748 }
4749
Eric Laurentfe231122017-11-17 17:48:06 -08004750 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004751 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004752
François Gaffie11d30102018-11-02 16:09:09 +01004753 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4754 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004755 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4756 SoundTrigger::setCaptureState(false);
4757 }
Eric Laurente552edb2014-03-10 17:42:56 -07004758}
4759
François Gaffie11d30102018-11-02 16:09:09 +01004760SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4761 const DeviceVector &devices,
4762 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004763{
4764 SortedVector<audio_io_handle_t> outputs;
4765
François Gaffie11d30102018-11-02 16:09:09 +01004766 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004767 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004768 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004769 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004770 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004771 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4772 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004773 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004774 outputs.add(openOutputs.keyAt(i));
4775 }
4776 }
4777 return outputs;
4778}
4779
Mikhail Naganov37977152018-07-11 15:54:44 -07004780void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4781{
4782 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4783 // output is suspended before any tracks are moved to it
4784 checkA2dpSuspend();
4785 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004786 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004787 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004788 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004789 setMsdPatch();
4790 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004791}
4792
François Gaffiec005e562018-11-06 15:04:49 +01004793bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
4794 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07004795{
François Gaffiec005e562018-11-06 15:04:49 +01004796 return mEngine->getProductStrategyForAttributes(lAttr) ==
4797 mEngine->getProductStrategyForAttributes(rAttr);
4798}
4799
4800void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
4801{
4802 auto psId = mEngine->getProductStrategyForAttributes(attr);
4803
4804 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
4805 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01004806 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4807 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004808
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004809 // also take into account external policy-related changes: add all outputs which are
4810 // associated with policies in the "before" and "after" output vectors
François Gaffiec005e562018-11-06 15:04:49 +01004811 ALOGVV("%s(): policy related outputs", __func__);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004812 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004813 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004814 if (desc != 0 && desc->mPolicyMix != NULL) {
4815 srcOutputs.add(desc->mIoHandle);
4816 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4817 }
4818 }
4819 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004820 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004821 if (desc != 0 && desc->mPolicyMix != NULL) {
4822 dstOutputs.add(desc->mIoHandle);
4823 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4824 }
4825 }
4826
François Gaffiec005e562018-11-06 15:04:49 +01004827 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004828 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4829 // audio from invalidated tracks will be rendered when unmuting
4830 uint32_t maxLatency = 0;
4831 for (audio_io_handle_t srcOut : srcOutputs) {
4832 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4833 if (desc != 0 && maxLatency < desc->latency()) {
4834 maxLatency = desc->latency();
4835 }
4836 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004837 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01004838 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004839 std::to_string(srcOutputs[0]).c_str(),
4840 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004841 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004842 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004843 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
François Gaffiec005e562018-11-06 15:04:49 +01004844 if (desc != 0 && desc->isStrategyActive(psId)) {
4845 setStrategyMute(psId, true, desc);
4846 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01004847 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004848 }
François Gaffiec005e562018-11-06 15:04:49 +01004849 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07004850 if (source != 0){
4851 connectAudioSource(source);
4852 }
Eric Laurente552edb2014-03-10 17:42:56 -07004853 }
4854
François Gaffiec005e562018-11-06 15:04:49 +01004855 // Move effects associated to this stream from previous output to new output
4856 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07004857 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004858 }
François Gaffiec005e562018-11-06 15:04:49 +01004859 // Move tracks associated to this stream (and linked) from previous output to new output
4860 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
4861 mpClientInterface->invalidateStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004862 }
4863 }
4864}
4865
Eric Laurente0720872014-03-11 09:30:41 -07004866void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004867{
François Gaffiec005e562018-11-06 15:04:49 +01004868 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
4869 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
4870 checkOutputForAttributes(attributes);
4871 }
Eric Laurente552edb2014-03-10 17:42:56 -07004872}
4873
Eric Laurente0720872014-03-11 09:30:41 -07004874void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004875{
François Gaffie53615e22015-03-19 09:24:12 +01004876 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004877 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004878 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004879 return;
4880 }
4881
Eric Laurent3a4311c2014-03-17 12:00:47 -07004882 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004883 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4884 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4885 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004886
4887 // if suspended, restore A2DP output if:
4888 // ((SCO device is NOT connected) ||
4889 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4890 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004891 //
Eric Laurentf732e072016-08-03 19:30:28 -07004892 // if not suspended, suspend A2DP output if:
4893 // (SCO device is connected) &&
4894 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4895 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004896 //
4897 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004898 if (!isScoConnected ||
4899 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4900 AUDIO_POLICY_FORCE_BT_SCO) &&
4901 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4902 AUDIO_POLICY_FORCE_BT_SCO) &&
4903 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004904 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004905
4906 mpClientInterface->restoreOutput(a2dpOutput);
4907 mA2dpSuspended = false;
4908 }
4909 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004910 if (isScoConnected &&
4911 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4912 AUDIO_POLICY_FORCE_BT_SCO) ||
4913 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4914 AUDIO_POLICY_FORCE_BT_SCO) ||
4915 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004916 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004917
4918 mpClientInterface->suspendOutput(a2dpOutput);
4919 mA2dpSuspended = true;
4920 }
4921 }
4922}
4923
François Gaffie11d30102018-11-02 16:09:09 +01004924DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4925 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004926{
François Gaffie11d30102018-11-02 16:09:09 +01004927 DeviceVector devices;
4928
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004929 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 if (index >= 0) {
4931 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4932 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004933 ALOGV("%s device %s forced by patch %d", __func__,
4934 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4935 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 }
4937 }
4938
Eric Laurent97ac8712018-07-27 18:59:02 -07004939 // Honor explicit routing requests only if no client using default routing is active on this
4940 // input: a specific app can not force routing for other apps by setting a preferred device.
4941 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004942 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01004943 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004944 if (device != nullptr) {
4945 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004946 }
4947
François Gaffiea807ef92018-11-05 10:44:33 +01004948 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
4949 // of setForceUse / Default Bus device here
4950 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
4951 if (device != nullptr) {
4952 return DeviceVector(device);
4953 }
4954
François Gaffiec005e562018-11-06 15:04:49 +01004955 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
4956 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
4957 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07004958
François Gaffiec005e562018-11-06 15:04:49 +01004959 if ((hasVoiceStream(streams) &&
4960 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) ||
4961 (hasStream(streams, AUDIO_STREAM_ALARM) &&
4962 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
4963 outputDesc->isStrategyActive(productStrategy)) {
4964 // Retrieval of devices for voice DL is done on primary output profile, cannot
4965 // check the route (would force modifying configuration file for this profile)
4966 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
4967 break;
4968 }
Eric Laurente552edb2014-03-10 17:42:56 -07004969 }
François Gaffiec005e562018-11-06 15:04:49 +01004970 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01004971 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07004972}
4973
François Gaffie11d30102018-11-02 16:09:09 +01004974sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
4975 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004976{
François Gaffie11d30102018-11-02 16:09:09 +01004977 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07004978
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004979 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004980 if (index >= 0) {
4981 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4982 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004983 ALOGV("getNewInputDevice() device %s forced by patch %d",
4984 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
4985 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 }
4987 }
4988
Eric Laurent97ac8712018-07-27 18:59:02 -07004989 // Honor explicit routing requests only if no client using default routing is active on this
4990 // input: a specific app can not force routing for other apps by setting a preferred device.
4991 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01004992 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4993 if (device != nullptr) {
4994 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07004995 }
4996
Eric Laurentdc95a252018-04-12 12:46:56 -07004997 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08004998 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01004999 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5000 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5001 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005002 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005003 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005004 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005005 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005006
Eric Laurente552edb2014-03-10 17:42:56 -07005007 return device;
5008}
5009
Eric Laurent794fde22016-03-11 09:50:45 -08005010bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5011 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005012 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005013}
5014
Eric Laurente0720872014-03-11 09:30:41 -07005015audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005016 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005017 // getOutputDevicesForStream's behavior for invalid streams.
5018 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5019 // device for music stream), but we want to return the empty set.
5020 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 return AUDIO_DEVICE_NONE;
5022 }
François Gaffie11d30102018-11-02 16:09:09 +01005023 DeviceVector activeDevices;
5024 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01005025 for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
5026 curStream = (audio_stream_type_t) (curStream + 1)) {
5027 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005028 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 }
François Gaffiec005e562018-11-06 15:04:49 +01005030 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005031 devices.merge(curDevices);
5032 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005033 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005034 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005035 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005036 }
5037 }
Eric Laurente552edb2014-03-10 17:42:56 -07005038 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005039
Eric Laurentb0688d62018-08-14 15:49:18 -07005040 // Favor devices selected on active streams if any to report correct device in case of
5041 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005042 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005043 devices = activeDevices;
5044 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005045 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5046 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005047 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5048 if (!speakerSafeDevices.isEmpty()) {
5049 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5050 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005051 }
François Gaffie11d30102018-11-02 16:09:09 +01005052 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005053}
5054
Eric Laurente0720872014-03-11 09:30:41 -07005055void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005056 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005057 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005058 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005059 updateDevicesAndOutputs();
5060 break;
5061 default:
5062 break;
5063 }
5064}
5065
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005066uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005067
5068 // skip beacon mute management if a dedicated TTS output is available
5069 if (mTtsOutputAvailable) {
5070 return 0;
5071 }
5072
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005073 switch(event) {
5074 case STARTING_OUTPUT:
5075 mBeaconMuteRefCount++;
5076 break;
5077 case STOPPING_OUTPUT:
5078 if (mBeaconMuteRefCount > 0) {
5079 mBeaconMuteRefCount--;
5080 }
5081 break;
5082 case STARTING_BEACON:
5083 mBeaconPlayingRefCount++;
5084 break;
5085 case STOPPING_BEACON:
5086 if (mBeaconPlayingRefCount > 0) {
5087 mBeaconPlayingRefCount--;
5088 }
5089 break;
5090 }
5091
5092 if (mBeaconMuteRefCount > 0) {
5093 // any playback causes beacon to be muted
5094 return setBeaconMute(true);
5095 } else {
5096 // no other playback: unmute when beacon starts playing, mute when it stops
5097 return setBeaconMute(mBeaconPlayingRefCount == 0);
5098 }
5099}
5100
5101uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5102 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5103 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5104 // keep track of muted state to avoid repeating mute/unmute operations
5105 if (mBeaconMuted != mute) {
5106 // mute/unmute AUDIO_STREAM_TTS on all outputs
5107 ALOGV("\t muting %d", mute);
5108 uint32_t maxLatency = 0;
5109 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005110 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005111 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005113 0 /*delay*/, AUDIO_DEVICE_NONE);
5114 const uint32_t latency = desc->latency() * 2;
5115 if (latency > maxLatency) {
5116 maxLatency = latency;
5117 }
5118 }
5119 mBeaconMuted = mute;
5120 return maxLatency;
5121 }
5122 return 0;
5123}
5124
Eric Laurente0720872014-03-11 09:30:41 -07005125void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005126{
François Gaffiec005e562018-11-06 15:04:49 +01005127 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005128 mPreviousOutputs = mOutputs;
5129}
5130
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005131uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005132 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005133 uint32_t delayMs)
5134{
5135 // mute/unmute strategies using an incompatible device combination
5136 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5137 // if unmuting, unmute only after the specified delay
5138 if (outputDesc->isDuplicated()) {
5139 return 0;
5140 }
5141
5142 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005143 DeviceVector devices = outputDesc->devices();
5144 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005145
François Gaffiec005e562018-11-06 15:04:49 +01005146 auto productStrategies = mEngine->getOrderedProductStrategies();
5147 for (const auto &productStrategy : productStrategies) {
5148 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5149 DeviceVector curDevices =
5150 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5151 curDevices = curDevices.filter(outputDesc->supportedDevices());
5152 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005153 bool doMute = false;
5154
François Gaffiec005e562018-11-06 15:04:49 +01005155 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005156 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005157 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5158 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005159 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005160 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005161 }
Eric Laurent99401132014-05-07 19:48:15 -07005162 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005163 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005164 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005165 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005166 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005167 continue;
5168 }
François Gaffiec005e562018-11-06 15:04:49 +01005169 ALOGVV("%s() %s (curDevice %s)", __func__,
5170 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5171 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5172 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005173 if (mute) {
5174 // FIXME: should not need to double latency if volume could be applied
5175 // immediately by the audioflinger mixer. We must account for the delay
5176 // between now and the next time the audioflinger thread for this output
5177 // will process a buffer (which corresponds to one buffer size,
5178 // usually 1/2 or 1/4 of the latency).
5179 if (muteWaitMs < desc->latency() * 2) {
5180 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005181 }
5182 }
5183 }
5184 }
5185 }
5186 }
5187
Eric Laurent99401132014-05-07 19:48:15 -07005188 // temporary mute output if device selection changes to avoid volume bursts due to
5189 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005190 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005191 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5192 // temporary mute duration is conservatively set to 4 times the reported latency
5193 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5194 if (muteWaitMs < tempMuteWaitMs) {
5195 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005196 }
Eric Laurentdc462862016-07-19 12:29:53 -07005197
François Gaffiec005e562018-11-06 15:04:49 +01005198 for (const auto &productStrategy : productStrategies) {
5199 if (outputDesc->isStrategyActive(productStrategy)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005200 // make sure that we do not start the temporary mute period too early in case of
5201 // delayed device change
François Gaffiec005e562018-11-06 15:04:49 +01005202 setStrategyMute(productStrategy, true, outputDesc, delayMs);
5203 setStrategyMute(productStrategy, false, outputDesc, delayMs + tempMuteDurationMs,
5204 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005205 }
5206 }
5207 }
5208
Eric Laurente552edb2014-03-10 17:42:56 -07005209 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5210 if (muteWaitMs > delayMs) {
5211 muteWaitMs -= delayMs;
5212 usleep(muteWaitMs * 1000);
5213 return muteWaitMs;
5214 }
5215 return 0;
5216}
5217
François Gaffie11d30102018-11-02 16:09:09 +01005218uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5219 const DeviceVector &devices,
5220 bool force,
5221 int delayMs,
5222 audio_patch_handle_t *patchHandle,
5223 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005224{
François Gaffie11d30102018-11-02 16:09:09 +01005225 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005226 uint32_t muteWaitMs;
5227
5228 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005229 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5230 nullptr /* patchHandle */, requiresMuteCheck);
5231 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5232 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005233 return muteWaitMs;
5234 }
Eric Laurente552edb2014-03-10 17:42:56 -07005235
5236 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005237 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005238
François Gaffie11d30102018-11-02 16:09:09 +01005239 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5240 // output profile
5241 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5242 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5243 return 0;
5244 }
Eric Laurente552edb2014-03-10 17:42:56 -07005245
François Gaffie11d30102018-11-02 16:09:09 +01005246 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005247
François Gaffie11d30102018-11-02 16:09:09 +01005248 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5249
5250 if (!filteredDevices.isEmpty()) {
5251 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005252 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005253
5254 // if the outputs are not materially active, there is no need to mute.
5255 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005256 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005257 } else {
5258 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5259 muteWaitMs = 0;
5260 }
Eric Laurente552edb2014-03-10 17:42:56 -07005261
5262 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005263 // the requested device is AUDIO_DEVICE_NONE
5264 // OR the requested device is the same as current device
5265 // AND force is not specified
5266 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005267 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005268 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005269 !force && outputDesc->getPatchHandle() != 0) {
5270 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5271 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005272 return muteWaitMs;
5273 }
5274
François Gaffie11d30102018-11-02 16:09:09 +01005275 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005276
Eric Laurente552edb2014-03-10 17:42:56 -07005277 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005278 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005279 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005280 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005281 PatchBuilder patchBuilder;
5282 patchBuilder.addSource(outputDesc);
5283 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5284 for (const auto &filteredDevice : filteredDevices) {
5285 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005286 }
5287
François Gaffie11d30102018-11-02 16:09:09 +01005288 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005289 }
Eric Laurente552edb2014-03-10 17:42:56 -07005290
5291 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005292 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005293
5294 return muteWaitMs;
5295}
5296
Eric Laurentc75307b2015-03-17 15:29:32 -07005297status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005298 int delayMs,
5299 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005300{
Eric Laurent6a94d692014-05-20 11:18:06 -07005301 ssize_t index;
5302 if (patchHandle) {
5303 index = mAudioPatches.indexOfKey(*patchHandle);
5304 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005305 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 }
5307 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005308 return INVALID_OPERATION;
5309 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5311 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005312 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005313 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 removeAudioPatch(patchDesc->mHandle);
5315 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005316 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005317 return status;
5318}
5319
5320status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005321 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 bool force,
5323 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005324{
5325 status_t status = NO_ERROR;
5326
Eric Laurent1f2f2232014-06-02 12:01:23 -07005327 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005328 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5329 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005330
François Gaffie11d30102018-11-02 16:09:09 +01005331 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005332 PatchBuilder patchBuilder;
5333 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005334 // AUDIO_SOURCE_HOTWORD is for internal use only:
5335 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005336 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5337 auto result = usecase;
5338 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5339 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5340 }
5341 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005342 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005343 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005344 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005345 }
5346 }
5347 return status;
5348}
5349
Eric Laurent6a94d692014-05-20 11:18:06 -07005350status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5351 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005352{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005353 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 ssize_t index;
5355 if (patchHandle) {
5356 index = mAudioPatches.indexOfKey(*patchHandle);
5357 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005358 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 }
5360 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005361 return INVALID_OPERATION;
5362 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005363 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5364 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005365 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005366 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 removeAudioPatch(patchDesc->mHandle);
5368 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005369 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005370 return status;
5371}
5372
François Gaffie11d30102018-11-02 16:09:09 +01005373sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005374 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005375 audio_format_t& format,
5376 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005377 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005378{
5379 // Choose an input profile based on the requested capture parameters: select the first available
5380 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005381 //
5382 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5383 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005384
Glenn Kasten730b9262018-03-29 15:01:26 -07005385 sp<IOProfile> firstInexact;
5386 uint32_t updatedSamplingRate = 0;
5387 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5388 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005389 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005390 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005391 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005392 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005393 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005394 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005395 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005396 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005397 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005398 &channelMask /*updatedChannelMask*/,
5399 // FIXME ugly cast
5400 (audio_output_flags_t) flags,
5401 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005402 return profile;
5403 }
François Gaffie11d30102018-11-02 16:09:09 +01005404 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005405 samplingRate,
5406 &updatedSamplingRate,
5407 format,
5408 &updatedFormat,
5409 channelMask,
5410 &updatedChannelMask,
5411 // FIXME ugly cast
5412 (audio_output_flags_t) flags,
5413 false /*exactMatchRequiredForInputFlags*/)) {
5414 firstInexact = profile;
5415 }
5416
Eric Laurente552edb2014-03-10 17:42:56 -07005417 }
5418 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005419 if (firstInexact != nullptr) {
5420 samplingRate = updatedSamplingRate;
5421 format = updatedFormat;
5422 channelMask = updatedChannelMask;
5423 return firstInexact;
5424 }
Eric Laurente552edb2014-03-10 17:42:56 -07005425 return NULL;
5426}
5427
Eric Laurente0720872014-03-11 09:30:41 -07005428float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005429 int index,
5430 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005431{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005432 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005433
5434 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5435 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5436 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5437 // the ringtone volume
5438 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5439 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5440 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5441 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5442 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5443 }
5444
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005445 // in-call: always cap volume by voice volume + some low headroom
5446 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005447 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005448 switch (stream) {
5449 case AUDIO_STREAM_SYSTEM:
5450 case AUDIO_STREAM_RING:
5451 case AUDIO_STREAM_MUSIC:
5452 case AUDIO_STREAM_ALARM:
5453 case AUDIO_STREAM_NOTIFICATION:
5454 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5455 case AUDIO_STREAM_DTMF:
5456 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005457 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005458 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005459 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005460 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005461 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005462 if (volumeDB > maxVoiceVolDb) {
5463 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5464 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5465 volumeDB = maxVoiceVolDb;
5466 }
5467 } break;
5468 default:
5469 break;
5470 }
5471 }
5472
Eric Laurente552edb2014-03-10 17:42:56 -07005473 // if a headset is connected, apply the following rules to ring tones and notifications
5474 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005475 // - always attenuate notifications volume by 6dB
5476 // - attenuate ring tones volume by 6dB unless music is not playing and
5477 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005478 // - if music is playing, always limit the volume to current music volume,
5479 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurente552edb2014-03-10 17:42:56 -07005480 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5481 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5482 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005483 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005484 AUDIO_DEVICE_OUT_USB_HEADSET |
5485 AUDIO_DEVICE_OUT_HEARING_AID)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005486 ((stream == AUDIO_STREAM_ALARM || stream == AUDIO_STREAM_RING)
5487 || (stream == AUDIO_STREAM_NOTIFICATION)
Eric Laurent3b73df72014-03-11 09:06:29 -07005488 || (stream == AUDIO_STREAM_SYSTEM)
François Gaffiec005e562018-11-06 15:04:49 +01005489 || ((stream == AUDIO_STREAM_ENFORCED_AUDIBLE) &&
5490 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
5491 AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005492 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005493 // when the phone is ringing we must consider that music could have been paused just before
5494 // by the music application and behave as if music was active if the last music track was
5495 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005496 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005497 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005498 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
François Gaffiec005e562018-11-06 15:04:49 +01005499 audio_devices_t musicDevice =
5500 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
5501 nullptr, true /*fromCache*/).types();
Eric Laurentffbc80f2015-03-18 18:30:19 -07005502 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005503 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5504 musicDevice),
5505 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005506 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5507 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005508 if (volumeDB > minVolDB) {
5509 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005510 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005511 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005512 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5513 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5514 // on A2DP, also ensure notification volume is not too low compared to media when
5515 // intended to be played
5516 if ((volumeDB > -96.0f) &&
5517 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5518 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5519 stream, device,
5520 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5521 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5522 }
5523 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005524 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffiec005e562018-11-06 15:04:49 +01005525 (stream != AUDIO_STREAM_ALARM && stream != AUDIO_STREAM_RING)) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005526 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005527 }
5528 }
5529
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005530 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005531}
5532
Eric Laurent3839bc02018-07-10 18:33:34 -07005533int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5534 audio_stream_type_t srcStream,
5535 audio_stream_type_t dstStream)
5536{
5537 if (srcStream == dstStream) {
5538 return srcIndex;
5539 }
5540 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5541 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5542 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5543 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5544
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005545 // preserve mute request or correct range
5546 if (srcIndex < minSrc) {
5547 if (srcIndex == 0) {
5548 return 0;
5549 }
5550 srcIndex = minSrc;
5551 } else if (srcIndex > maxSrc) {
5552 srcIndex = maxSrc;
5553 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005554 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5555}
5556
Eric Laurente0720872014-03-11 09:30:41 -07005557status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005558 int index,
5559 const sp<AudioOutputDescriptor>& outputDesc,
5560 audio_devices_t device,
5561 int delayMs,
5562 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005563{
Eric Laurente552edb2014-03-10 17:42:56 -07005564 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005565 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005566 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005567 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005568 return NO_ERROR;
5569 }
François Gaffie2110e042015-03-24 08:41:51 +01005570 audio_policy_forced_cfg_t forceUseForComm =
5571 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005572 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005573 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5574 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005575 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005576 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005577 return INVALID_OPERATION;
5578 }
5579
Eric Laurentc75307b2015-03-17 15:29:32 -07005580 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005581 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005582 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005583
Eric Laurentffbc80f2015-03-18 18:30:19 -07005584 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005585 if (outputDesc->isFixedVolume(device) ||
5586 // Force VoIP volume to max for bluetooth SCO
5587 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5588 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005589 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005590 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005591
Eric Laurentffbc80f2015-03-18 18:30:19 -07005592 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005593
Eric Laurent3b73df72014-03-11 09:06:29 -07005594 if (stream == AUDIO_STREAM_VOICE_CALL ||
5595 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005596 float voiceVolume;
5597 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005598 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005599 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005600 } else {
5601 voiceVolume = 1.0;
5602 }
5603
Eric Laurent18fba842016-03-31 14:41:26 -07005604 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005605 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5606 mLastVoiceVolume = voiceVolume;
5607 }
5608 }
5609
5610 return NO_ERROR;
5611}
5612
Eric Laurentc75307b2015-03-17 15:29:32 -07005613void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5614 audio_devices_t device,
5615 int delayMs,
5616 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005617{
Eric Laurentc75307b2015-03-17 15:29:32 -07005618 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005619
Eric Laurent794fde22016-03-11 09:50:45 -08005620 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005621 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005622 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005623 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005624 device,
5625 delayMs,
5626 force);
5627 }
5628}
5629
François Gaffiec005e562018-11-06 15:04:49 +01005630void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
5631 bool on,
5632 const sp<AudioOutputDescriptor>& outputDesc,
5633 int delayMs,
5634 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005635{
François Gaffiec005e562018-11-06 15:04:49 +01005636 for (auto stream: mEngine->getStreamTypesForProductStrategy(strategy)) {
5637 ALOGVV("%s() stream %d, mute %d, output ID %d", __FUNCTION__, stream, on,
5638 outputDesc->getId());
5639 setStreamMute(stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005640 }
5641}
5642
Eric Laurente0720872014-03-11 09:30:41 -07005643void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005644 bool on,
5645 const sp<AudioOutputDescriptor>& outputDesc,
5646 int delayMs,
5647 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005648{
Eric Laurente552edb2014-03-10 17:42:56 -07005649 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005650 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005651 }
5652
Eric Laurentc75307b2015-03-17 15:29:32 -07005653 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5654 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005655
5656 if (on) {
5657 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005658 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005659 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005660 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005661 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005662 }
5663 }
5664 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5665 outputDesc->mMuteCount[stream]++;
5666 } else {
5667 if (outputDesc->mMuteCount[stream] == 0) {
5668 ALOGV("setStreamMute() unmuting non muted stream!");
5669 return;
5670 }
5671 if (--outputDesc->mMuteCount[stream] == 0) {
5672 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005673 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005674 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005675 device,
5676 delayMs);
5677 }
5678 }
5679}
5680
François Gaffie53615e22015-03-19 09:24:12 +01005681bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5682{
François Gaffiec005e562018-11-06 15:04:49 +01005683 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08005684 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5685 return true;
5686 }
5687
5688 // has known usage?
5689 switch (paa->usage) {
5690 case AUDIO_USAGE_UNKNOWN:
5691 case AUDIO_USAGE_MEDIA:
5692 case AUDIO_USAGE_VOICE_COMMUNICATION:
5693 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5694 case AUDIO_USAGE_ALARM:
5695 case AUDIO_USAGE_NOTIFICATION:
5696 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5697 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5698 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5699 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5700 case AUDIO_USAGE_NOTIFICATION_EVENT:
5701 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5702 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5703 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5704 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005705 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005706 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005707 break;
5708 default:
5709 return false;
5710 }
5711 return true;
5712}
5713
François Gaffie2110e042015-03-24 08:41:51 +01005714audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5715{
5716 return mEngine->getForceUse(usage);
5717}
5718
5719bool AudioPolicyManager::isInCall()
5720{
5721 return isStateInCall(mEngine->getPhoneState());
5722}
5723
5724bool AudioPolicyManager::isStateInCall(int state)
5725{
5726 return is_state_in_call(state);
5727}
5728
Eric Laurentd60560a2015-04-10 11:31:20 -07005729void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5730{
5731 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005732 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5733 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5734 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5735 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005736 }
5737 }
5738
5739 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5740 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5741 bool release = false;
5742 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5743 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5744 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5745 source->ext.device.type == deviceDesc->type()) {
5746 release = true;
5747 }
5748 }
5749 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5750 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5751 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5752 sink->ext.device.type == deviceDesc->type()) {
5753 release = true;
5754 }
5755 }
5756 if (release) {
5757 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5758 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5759 }
5760 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005761
5762 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005763}
5764
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005765void AudioPolicyManager::modifySurroundFormats(
5766 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005767 std::unordered_set<audio_format_t> enforcedSurround(
5768 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005769 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5770 for (const auto& pair : mConfig.getSurroundFormats()) {
5771 allSurround.insert(pair.first);
5772 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5773 }
Phil Burk09bc4612016-02-24 15:58:15 -08005774
5775 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5776 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005777 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005778 // This is the resulting set of formats depending on the surround mode:
5779 // 'all surround' = allSurround
5780 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5781 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5782 // 'manual surround' = mManualSurroundFormats
5783 // AUTO: formats v 'enforced surround'
5784 // ALWAYS: formats v 'all surround' v 'enforced surround'
5785 // NEVER: formats ^ 'non-surround'
5786 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005787
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005788 std::unordered_set<audio_format_t> formatSet;
5789 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5790 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005791 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005792 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005793 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005794 formatSet.insert(*formatIter);
5795 }
5796 }
5797 } else {
5798 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5799 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005800 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005801
jiabin81772902018-04-02 17:52:27 -07005802 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005803 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005804 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5805 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5806 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005807 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005808 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5809 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5810 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005811 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005812 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005813 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005814 for (const auto& format : formatSet) {
5815 formatsPtr->push(format);
5816 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005817}
5818
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005819void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005820 ChannelsVector &channelMasks = *channelMasksPtr;
5821 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5822 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5823
5824 // If NEVER, then remove support for channelMasks > stereo.
5825 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5826 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5827 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5828 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5829 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5830 channelMasks.removeAt(maskIndex);
5831 } else {
5832 maskIndex++;
5833 }
5834 }
jiabin81772902018-04-02 17:52:27 -07005835 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5836 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5837 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005838 bool supports5dot1 = false;
5839 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005840 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005841 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5842 supports5dot1 = true;
5843 break;
5844 }
5845 }
5846 // If not then add 5.1 support.
5847 if (!supports5dot1) {
5848 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005849 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005850 }
Phil Burk09bc4612016-02-24 15:58:15 -08005851 }
5852}
5853
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005854void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005855 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005856 AudioProfileVector &profiles)
5857{
5858 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005859 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005860
François Gaffie112b0af2015-11-19 16:13:25 +01005861 // Format MUST be checked first to update the list of AudioProfile
5862 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005863 reply = mpClientInterface->getParameters(
5864 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005865 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005866 AudioParameter repliedParameters(reply);
5867 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005868 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005869 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5870 return;
5871 }
Phil Burk09bc4612016-02-24 15:58:15 -08005872 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005873 if (device == AUDIO_DEVICE_OUT_HDMI
5874 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005875 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005876 }
Phil Burk09bc4612016-02-24 15:58:15 -08005877 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005878 }
François Gaffie112b0af2015-11-19 16:13:25 +01005879
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005880 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005881 ChannelsVector channelMasks;
5882 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005883 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005884 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005885
5886 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005887 reply = mpClientInterface->getParameters(
5888 ioHandle,
5889 requestedParameters.toString() + ";" +
5890 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005891 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005892 AudioParameter repliedParameters(reply);
5893 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005894 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005895 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005896 }
5897 }
5898 if (profiles.hasDynamicChannelsFor(format)) {
5899 reply = mpClientInterface->getParameters(ioHandle,
5900 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005901 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005902 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005903 AudioParameter repliedParameters(reply);
5904 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005905 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005906 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005907 if (device == AUDIO_DEVICE_OUT_HDMI
5908 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005909 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005910 }
François Gaffie112b0af2015-11-19 16:13:25 +01005911 }
5912 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005913 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005914 }
5915}
Eric Laurentd60560a2015-04-10 11:31:20 -07005916
Mikhail Naganovdc769682018-05-04 15:34:08 -07005917status_t AudioPolicyManager::installPatch(const char *caller,
5918 audio_patch_handle_t *patchHandle,
5919 AudioIODescriptorInterface *ioDescriptor,
5920 const struct audio_patch *patch,
5921 int delayMs)
5922{
5923 ssize_t index = mAudioPatches.indexOfKey(
5924 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5925 *patchHandle : ioDescriptor->getPatchHandle());
5926 sp<AudioPatch> patchDesc;
5927 status_t status = installPatch(
5928 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5929 if (status == NO_ERROR) {
5930 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5931 }
5932 return status;
5933}
5934
5935status_t AudioPolicyManager::installPatch(const char *caller,
5936 ssize_t index,
5937 audio_patch_handle_t *patchHandle,
5938 const struct audio_patch *patch,
5939 int delayMs,
5940 uid_t uid,
5941 sp<AudioPatch> *patchDescPtr)
5942{
5943 sp<AudioPatch> patchDesc;
5944 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5945 if (index >= 0) {
5946 patchDesc = mAudioPatches.valueAt(index);
5947 afPatchHandle = patchDesc->mAfPatchHandle;
5948 }
5949
5950 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5951 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5952 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5953 if (status == NO_ERROR) {
5954 if (index < 0) {
5955 patchDesc = new AudioPatch(patch, uid);
5956 addAudioPatch(patchDesc->mHandle, patchDesc);
5957 } else {
5958 patchDesc->mPatch = *patch;
5959 }
5960 patchDesc->mAfPatchHandle = afPatchHandle;
5961 if (patchHandle) {
5962 *patchHandle = patchDesc->mHandle;
5963 }
5964 nextAudioPortGeneration();
5965 mpClientInterface->onAudioPatchListUpdate();
5966 }
5967 if (patchDescPtr) *patchDescPtr = patchDesc;
5968 return status;
5969}
5970
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005971} // namespace android