blob: 02b85b43a9a6471d630ad92544d84c8acc79544d [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>
Kevin Rocard153f92d2018-12-18 18:33:28 -080039#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080040#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110041#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070042
François Gaffie2110e042015-03-24 08:41:51 +010043#include <AudioPolicyManagerInterface.h>
44#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070045#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070047#include <media/AudioParameter.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
Kevin Rocard153f92d2018-12-18 18:33:28 -0800911status_t AudioPolicyManager::getOutputForAttrInt(
912 audio_attributes_t *resultAttr,
913 audio_io_handle_t *output,
914 audio_session_t session,
915 const audio_attributes_t *attr,
916 audio_stream_type_t *stream,
917 uid_t uid,
918 const audio_config_t *config,
919 audio_output_flags_t *flags,
920 audio_port_handle_t *selectedDeviceId,
921 bool *isRequestedDeviceForExclusiveUse,
922 std::vector<sp<SwAudioOutputDescriptor>> *secondaryDescs)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700923{
François Gaffiec005e562018-11-06 15:04:49 +0100924 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100925 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100926 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100927 const sp<DeviceDescriptor> requestedDevice =
928 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
929
930
Eric Laurent8fc147b2018-07-22 19:13:55 -0700931
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700932 status_t status = getAudioAttributes(resultAttr, attr, *stream);
933 if (status != NO_ERROR) {
934 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700935 }
François Gaffiec005e562018-11-06 15:04:49 +0100936 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700937
François Gaffiec005e562018-11-06 15:04:49 +0100938 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
939 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700940
Kevin Rocard153f92d2018-12-18 18:33:28 -0800941 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
942 // otherwise, fallback to the dynamic policies, if none match, query the engine.
943 // Secondary outputs are always found by dynamic policies as the engine do not support them
944 sp<SwAudioOutputDescriptor> policyDesc;
945 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, policyDesc, secondaryDescs) != NO_ERROR) {
946 policyDesc = nullptr; // reset getOutputForAttr in case of failure
947 secondaryDescs->clear();
948 }
949 // Explicit routing is higher priority then any dynamic policy primary output
950 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && policyDesc != nullptr;
951
952 // FIXME: in case of RENDER policy, the output capabilities should be checked
953 if ((usePrimaryOutputFromPolicyMixes || !secondaryDescs->empty())
954 && !audio_has_proportional_frames(config->format)) {
955 ALOGW("%s: audio loopback only supports proportional frames", __func__);
956 return BAD_VALUE;
957 }
958 if (usePrimaryOutputFromPolicyMixes) {
959 *output = policyDesc->mIoHandle;
960 AudioMix *mix = policyDesc->mPolicyMix;
François Gaffiec005e562018-11-06 15:04:49 +0100961 sp<DeviceDescriptor> deviceDesc =
962 mAvailableOutputDevices.getDevice(mix->mDeviceType,
963 mix->mDeviceAddress,
964 AUDIO_FORMAT_DEFAULT);
965 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
966 ALOGV("getOutputForAttr() returns output %d", *output);
967 return NO_ERROR;
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700968 }
François Gaffiec005e562018-11-06 15:04:49 +0100969 // Virtual sources must always be dynamicaly or explicitly routed
970 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
971 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
972 return BAD_VALUE;
973 }
974 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
975 // in order to let the choice of the order to future vendor engine
976 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700977
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700978 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200979 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700980 }
981
Nadav Barb2f18162018-07-18 13:01:53 +0300982 // Set incall music only if device was explicitly set, and fallback to the device which is
983 // chosen by the engine if not.
984 // FIXME: provide a more generic approach which is not device specific and move this back
985 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200986 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffiec005e562018-11-06 15:04:49 +0100987 if (outputDevices.types() == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
988 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300989 audio_is_linear_pcm(config->format) &&
990 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100991 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300992 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +0100993 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +0300994 }
995 }
996
François Gaffiec005e562018-11-06 15:04:49 +0100997 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
998 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
999 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001000
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001001 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001002 if (!msdDevices.isEmpty()) {
1003 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001004 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1005 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1006 ALOGV("%s() Using MSD devices %s instead of devices %s",
1007 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1008 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001009 } else {
1010 *output = AUDIO_IO_HANDLE_NONE;
1011 }
1012 }
1013 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffiec005e562018-11-06 15:04:49 +01001014 *output = getOutputForDevices(outputDevices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001015 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001016 if (*output == AUDIO_IO_HANDLE_NONE) {
1017 return INVALID_OPERATION;
1018 }
Paul McLeanaa981192015-03-21 09:55:15 -07001019
François Gaffiec005e562018-11-06 15:04:49 +01001020 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001021
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001022 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1023
1024 return NO_ERROR;
1025}
1026
1027status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1028 audio_io_handle_t *output,
1029 audio_session_t session,
1030 audio_stream_type_t *stream,
1031 uid_t uid,
1032 const audio_config_t *config,
1033 audio_output_flags_t *flags,
1034 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001035 audio_port_handle_t *portId,
1036 std::vector<audio_io_handle_t> *secondaryOutputs)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001037{
1038 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1039 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1040 return INVALID_OPERATION;
1041 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001042 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001043 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001044 bool isRequestedDeviceForExclusiveUse = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001045 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputDescs;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001046 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001047 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
1048 &secondaryOutputDescs);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001049 if (status != NO_ERROR) {
1050 return status;
1051 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001052 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
1053 for (auto& secondaryDesc : secondaryOutputDescs) {
1054 secondaryOutputs->push_back(secondaryDesc->mIoHandle);
1055 weakSecondaryOutputDescs.push_back(secondaryDesc);
1056 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001057
Eric Laurent8fc147b2018-07-22 19:13:55 -07001058 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1059 .format = config->format,
1060 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001061 *portId = AudioPort::getNextUniqueId();
1062
Eric Laurent8fc147b2018-07-22 19:13:55 -07001063 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001064 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +01001065 requestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001066 mEngine->getProductStrategyForAttributes(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001067 *flags, isRequestedDeviceForExclusiveUse,
1068 std::move(weakSecondaryOutputDescs));
Eric Laurent8fc147b2018-07-22 19:13:55 -07001069 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001070 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001071
François Gaffiec005e562018-11-06 15:04:49 +01001072 ALOGV("%s() returns output %d selectedDeviceId %d for port ID %d", __func__,
1073 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001074
Eric Laurente83b55d2014-11-14 10:06:21 -08001075 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001076}
1077
François Gaffie11d30102018-11-02 16:09:09 +01001078audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1079 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001080 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001081 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001082 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001083 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001084{
Andy Hungc88b0642018-04-27 15:42:35 -07001085 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001086 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001087
Eric Laurente552edb2014-03-10 17:42:56 -07001088 // open a direct output if required by specified parameters
1089 //force direct flag if offload flag is set: offloading implies a direct output stream
1090 // and all common behaviors are driven by checking only the direct flag
1091 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001092 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1093 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001094 }
Nadav Bar766fb022018-01-07 12:18:03 +02001095 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1096 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001097 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001098 // only allow deep buffering for music stream type
1099 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001100 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001101 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001102 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001103 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1104 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001105 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001106 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001107 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001108 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001109 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001110 audio_is_linear_pcm(config->format) &&
1111 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001112 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001113 AUDIO_OUTPUT_FLAG_DIRECT);
1114 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001115 }
Eric Laurente552edb2014-03-10 17:42:56 -07001116
Nadav Bar766fb022018-01-07 12:18:03 +02001117
Eric Laurentb732cf52014-09-24 19:08:21 -07001118 sp<IOProfile> profile;
1119
1120 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001121 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001122 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001123 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1124 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001125 goto non_direct_output;
1126 }
1127
Andy Hung2ddee192015-12-18 17:34:44 -08001128 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1129 // This prevents creating an offloaded track and tearing it down immediately after start
1130 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001131 // FIXME: We should check the audio session here but we do not have it in this context.
1132 // This may prevent offloading in rare situations where effects are left active by apps
1133 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001134
Nadav Bar766fb022018-01-07 12:18:03 +02001135 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001136 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001137 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001138 config->sample_rate,
1139 config->format,
1140 config->channel_mask,
1141 (audio_output_flags_t)*flags,
1142 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001143 }
1144
Eric Laurent1c333e22014-05-20 10:48:17 -07001145 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001146 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1147 for (size_t i = 0; i < mOutputs.size(); i++) {
1148 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1149 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1150 // reuse direct output if currently open by the same client
1151 // and configured with same parameters
1152 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001153 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001154 (config->channel_mask == desc->mChannelMask) &&
1155 (session == desc->mDirectClientSession)) {
1156 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001157 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001158 mOutputs.keyAt(i), session);
1159 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001160 }
1161 }
1162 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001163
1164 if (!profile->canOpenNewIo()) {
1165 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001166 }
Eric Laurent861a6282015-05-18 15:40:16 -07001167
Eric Laurent3974e3b2017-12-07 17:58:43 -08001168 sp<SwAudioOutputDescriptor> outputDesc =
1169 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001170
François Gaffie11d30102018-11-02 16:09:09 +01001171 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001172
Dean Wheatley3023b382018-08-09 07:42:40 +10001173 // MSD patch may be using the only output stream that can service this request. Release
1174 // MSD patch to prioritize this request over any active output on MSD.
1175 AudioPatchCollection msdPatches = getMsdPatches();
1176 for (size_t i = 0; i < msdPatches.size(); i++) {
1177 const auto& patch = msdPatches[i];
1178 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1179 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1180 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001181 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001182 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1183 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1184 releaseAudioPatch(patch->mHandle, mUidCached);
1185 break;
1186 }
1187 }
1188 }
1189
François Gaffie11d30102018-11-02 16:09:09 +01001190 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001191
1192 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001193 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001194 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001195 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001196 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001197 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1198 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001199 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1200 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001201 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001202 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001203 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001204 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001205 if (audio_is_linear_pcm(config->format) &&
1206 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001207 goto non_direct_output;
1208 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001209 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001210 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001211 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001212 outputDesc->mDirectClientSession = session;
1213
Eric Laurente552edb2014-03-10 17:42:56 -07001214 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001215 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001216 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001217 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001218 return output;
1219 }
1220
Eric Laurentb732cf52014-09-24 19:08:21 -07001221non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001222
1223 // A request for HW A/V sync cannot fallback to a mixed output because time
1224 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001225 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001226 return AUDIO_IO_HANDLE_NONE;
1227 }
1228
Eric Laurente552edb2014-03-10 17:42:56 -07001229 // ignoring channel mask due to downmix capability in mixer
1230
1231 // open a non direct output
1232
1233 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001234 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001235 // get which output is suitable for the specified stream. The actual
1236 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001237 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001238
Eric Laurent8838a382014-09-08 16:44:28 -07001239 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001240 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001241 output = selectOutput(outputs, *flags, config->format,
1242 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001243 }
François Gaffie11d30102018-11-02 16:09:09 +01001244 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001245 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001246 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001247
Eric Laurente552edb2014-03-10 17:42:56 -07001248 return output;
1249}
1250
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001251sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001252 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1253 mAvailableInputDevices);
1254 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1255}
1256
1257DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1258 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1259 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001260}
1261
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001262const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1263 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001264 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1265 if (msdModule != 0) {
1266 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1267 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1268 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1269 const struct audio_port_config *source = &patch->mPatch.sources[j];
1270 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1271 source->ext.device.hw_module == msdModule->getHandle()) {
1272 msdPatches.addAudioPatch(patch->mHandle, patch);
1273 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001274 }
1275 }
1276 }
1277 return msdPatches;
1278}
1279
François Gaffie11d30102018-11-02 16:09:09 +01001280status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001281 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1282{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001283 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001284 if (msdModule == nullptr) {
1285 ALOGE("%s() unable to get MSD module", __func__);
1286 return NO_INIT;
1287 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001288 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001289 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001290 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001291 return NO_INIT;
1292 }
1293 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1294 if (inputProfiles.isEmpty()) {
1295 ALOGE("%s() no input profiles for MSD module", __func__);
1296 return NO_INIT;
1297 }
1298 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1299 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001300 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001301 return NO_INIT;
1302 }
1303 AudioProfileVector msdProfiles;
1304 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1305 for (const auto &inProfile : inputProfiles) {
1306 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1307 msdProfiles.appendVector(inProfile->getAudioProfiles());
1308 }
1309 }
1310 AudioProfileVector deviceProfiles;
1311 for (const auto &outProfile : outputProfiles) {
1312 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1313 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1314 }
1315 }
1316 struct audio_config_base bestSinkConfig;
1317 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1318 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1319 &bestSinkConfig);
1320 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001321 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1322 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001323 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001324 }
1325 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1326 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1327 sinkConfig->format = bestSinkConfig.format;
1328 // For encoded streams force direct flag to prevent downstream mixing.
1329 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1330 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1331 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1332 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1333 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1334 sourceConfig->format = bestSinkConfig.format;
1335 // Copy input stream directly without any processing (e.g. resampling).
1336 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1337 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1338 if (hwAvSync) {
1339 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1340 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1341 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1342 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1343 }
1344 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1345 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1346 sinkConfig->config_mask |= config_mask;
1347 sourceConfig->config_mask |= config_mask;
1348 return NO_ERROR;
1349}
1350
François Gaffie11d30102018-11-02 16:09:09 +01001351PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352{
1353 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001354 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001355 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1356 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1357 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1358 // For now, we just forcefully try with HwAvSync first.
1359 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1360 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1361 getBestMsdAudioProfileFor(
1362 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1363 if (res == NO_ERROR) {
1364 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1365 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1366 }
1367 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1368 " supporting PCM format conversion.", __func__);
1369 return patchBuilder;
1370}
1371
François Gaffie11d30102018-11-02 16:09:09 +01001372status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1373 sp<DeviceDescriptor> device = outputDevice;
1374 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001375 // Use media strategy for unspecified output device. This should only
1376 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1377 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001378 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1379 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001380 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1381 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001382 }
François Gaffie11d30102018-11-02 16:09:09 +01001383 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1384 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001385 const struct audio_patch* patch = patchBuilder.patch();
1386 const AudioPatchCollection msdPatches = getMsdPatches();
1387 if (!msdPatches.isEmpty()) {
1388 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1389 "The current MSD prototype only supports one output patch");
1390 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1391 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1392 return NO_ERROR;
1393 }
1394 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1395 }
1396 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1397 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1398 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1399 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001400 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1401 device->toString().c_str(), patch->sources[0].format,
1402 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001403 return status;
1404}
1405
Eric Laurente0720872014-03-11 09:30:41 -07001406audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001407 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001408 audio_format_t format,
1409 audio_channel_mask_t channelMask,
1410 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001411{
1412 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001413 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001414 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001415 // 1: the output supporting haptic playback when requesting haptic playback
1416 // 2: the output with the highest number of requested policy flags
1417 // 3: the output with the bit depth the closest to the requested one
1418 // 4: the primary output
1419 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001420
1421 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001422 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001423 }
1424 if (outputs.size() == 1) {
1425 return outputs[0];
1426 }
1427
1428 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001429 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1430 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001431 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1432 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1433 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001434 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1435 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001436
Eric Laurente78b6762018-12-19 16:29:01 -08001437 // Flags which must be present on both the request and the selected output
1438 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1439 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1440
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001441 for (audio_io_handle_t output : outputs) {
1442 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001443 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001444 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1445 continue;
1446 }
jiabin40573322018-11-08 12:08:02 -08001447 // If haptic channel is specified, use the haptic output if present.
1448 // When using haptic output, same audio format and sample rate are required.
1449 if (hapticChannelCount > 0) {
1450 // If haptic channel is specified, use the first output that
1451 // support haptic playback.
1452 if (audio_channel_count_from_out_mask(
1453 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1454 && format == outputDesc->mFormat
1455 && samplingRate == outputDesc->mSamplingRate) {
1456 return output;
1457 }
1458 } else {
1459 // When haptic channel is not specified, skip haptic output.
1460 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1461 continue;
1462 }
1463 }
Eric Laurente78b6762018-12-19 16:29:01 -08001464 if ((kMandatedFlags & flags) !=
1465 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1466 continue;
1467 }
jiabin40573322018-11-08 12:08:02 -08001468
Eric Laurent8838a382014-09-08 16:44:28 -07001469 // if a valid format is specified, skip output if not compatible
1470 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001471 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001472 continue;
1473 }
Eric Laurente6930022016-02-11 10:20:40 -08001474 if (AudioPort::isBetterFormatMatch(
1475 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001476 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001477 bestFormat = outputDesc->mFormat;
1478 }
Eric Laurent8838a382014-09-08 16:44:28 -07001479 }
1480
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001481 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001482 if (commonFlags >= maxCommonFlags) {
1483 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001484 if (format != AUDIO_FORMAT_INVALID
1485 && AudioPort::isBetterFormatMatch(
1486 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001487 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001488 bestFormatForFlags = outputDesc->mFormat;
1489 }
1490 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001491 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001492 maxCommonFlags = commonFlags;
1493 bestFormatForFlags = outputDesc->mFormat;
1494 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001495 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001496 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001497 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001498 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001499 }
1500 }
1501 }
1502
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001503 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001504 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001505 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001506 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001507 return outputForFormat;
1508 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001509 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001510 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001511 }
1512
1513 return outputs[0];
1514}
1515
Eric Laurent8fc147b2018-07-22 19:13:55 -07001516status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001517{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001518 ALOGV("%s portId %d", __FUNCTION__, portId);
1519
1520 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1521 if (outputDesc == 0) {
1522 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001523 return BAD_VALUE;
1524 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001525 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001526
Eric Laurent8fc147b2018-07-22 19:13:55 -07001527 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001528 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001529
Eric Laurent733ce942017-12-07 12:18:25 -08001530 status_t status = outputDesc->start();
1531 if (status != NO_ERROR) {
1532 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001533 }
1534
Eric Laurent97ac8712018-07-27 18:59:02 -07001535 uint32_t delayMs;
1536 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001537
1538 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001539 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001540 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001541 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001542 if (delayMs != 0) {
1543 usleep(delayMs * 1000);
1544 }
1545
1546 return status;
1547}
1548
Eric Laurent97ac8712018-07-27 18:59:02 -07001549status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1550 const sp<TrackClientDescriptor>& client,
1551 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001552{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001553 // cannot start playback of STREAM_TTS if any other output is being used
1554 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001555
1556 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001557 audio_stream_type_t stream = client->stream();
François Gaffiec005e562018-11-06 15:04:49 +01001558 auto clientStrategy = client->strategy();
1559 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001560 if (stream == AUDIO_STREAM_TTS) {
1561 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001562 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001563 return INVALID_OPERATION;
1564 } else {
1565 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1566 }
1567 } else {
1568 // some playback other than beacon starts
1569 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1570 }
1571
Eric Laurent77305a62016-07-25 16:39:22 -07001572 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001573 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001574 bool force = !outputDesc->isActive() &&
1575 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001576
François Gaffie11d30102018-11-02 16:09:09 +01001577 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001578 AudioMix *policyMix = NULL;
1579 const char *address = NULL;
1580 if (outputDesc->mPolicyMix != NULL) {
1581 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001582 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001583 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001584 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001585 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001586 } else {
1587 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001588 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001589 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1590 AUDIO_FORMAT_DEFAULT);
1591 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1592 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001593 }
1594
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001595 // requiresMuteCheck is false when we can bypass mute strategy.
1596 // It covers a common case when there is no materially active audio
1597 // and muting would result in unnecessary delay and dropped audio.
1598 const uint32_t outputLatencyMs = outputDesc->latency();
1599 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1600
Eric Laurente552edb2014-03-10 17:42:56 -07001601 // increment usage count for this stream on the requested output:
1602 // NOTE that the usage count is the same for duplicated output and hardware output which is
1603 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001604 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001605
1606 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001607 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1608 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001609 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001610 }
1611 }
Eric Laurente552edb2014-03-10 17:42:56 -07001612
François Gaffiec005e562018-11-06 15:04:49 +01001613 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001614 selectOutputForMusicEffects();
1615 }
1616
François Gaffie11d30102018-11-02 16:09:09 +01001617 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001618 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001619 if (devices.isEmpty()) {
1620 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001621 }
François Gaffiec005e562018-11-06 15:04:49 +01001622 bool shouldWait =
1623 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1624 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1625 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001626 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001627 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001628 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001629 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001630 // An output has a shared device if
1631 // - managed by the same hw module
1632 // - supports the currently selected device
1633 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001634 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001635
Eric Laurent77305a62016-07-25 16:39:22 -07001636 // force a device change if any other output is:
1637 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001638 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001639 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001640 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001641 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001642 // change the device currently selected by the other output.
1643 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001644 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001645 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001646 force = true;
1647 }
1648 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001649 // a notification so that audio focus effect can propagate, or that a mute/unmute
1650 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001651 const uint32_t latencyMs = desc->latency();
1652 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1653
1654 if (shouldWait && isActive && (waitMs < latencyMs)) {
1655 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001656 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001657
1658 // Require mute check if another output is on a shared device
1659 // and currently active to have proper drain and avoid pops.
1660 // Note restoring AudioTracks onto this output needs to invoke
1661 // a volume ramp if there is no mute.
1662 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001663 }
1664 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001665
1666 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001667 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001668
Eric Laurente552edb2014-03-10 17:42:56 -07001669 // apply volume rules for current stream and device if necessary
1670 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001671 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001672 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001673 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001674
1675 // update the outputs if starting an output with a stream that can affect notification
1676 // routing
1677 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001678
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001679 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001680 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001681 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1682 }
Eric Laurentdc462862016-07-19 12:29:53 -07001683
1684 if (waitMs > muteWaitMs) {
1685 *delayMs = waitMs - muteWaitMs;
1686 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001687
1688 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1689 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1690 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1691 // change occurs after the MixerThread starts and causes a stream volume
1692 // glitch.
1693 //
1694 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001695 }
Eric Laurentdc462862016-07-19 12:29:53 -07001696
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001697 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1698 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001699 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001700 }
1701
Eric Laurent97ac8712018-07-27 18:59:02 -07001702 // Automatically enable the remote submix input when output is started on a re routing mix
1703 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001704 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001705 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1706 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1707 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1708 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001709 "remote-submix",
1710 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001711 }
1712
Eric Laurente552edb2014-03-10 17:42:56 -07001713 return NO_ERROR;
1714}
1715
Eric Laurent8fc147b2018-07-22 19:13:55 -07001716status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001717{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001718 ALOGV("%s portId %d", __FUNCTION__, portId);
1719
1720 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1721 if (outputDesc == 0) {
1722 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001723 return BAD_VALUE;
1724 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001725 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001726
Eric Laurent97ac8712018-07-27 18:59:02 -07001727 ALOGV("stopOutput() output %d, stream %d, session %d",
1728 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001729
Eric Laurent97ac8712018-07-27 18:59:02 -07001730 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001731
Eric Laurent733ce942017-12-07 12:18:25 -08001732 if (status == NO_ERROR ) {
1733 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001734 }
1735 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001736}
1737
Eric Laurent97ac8712018-07-27 18:59:02 -07001738status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1739 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001740{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001741 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001742 audio_stream_type_t stream = client->stream();
1743
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001744 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1745
Eric Laurent592dd7b2018-08-05 18:58:48 -07001746 if (outputDesc->streamActiveCount(stream) > 0) {
1747 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001748 // Automatically disable the remote submix input when output is stopped on a
1749 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001750 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001751 outputDesc->mPolicyMix != NULL &&
1752 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1753 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1754 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1755 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001756 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001757 }
1758 }
1759 bool forceDeviceUpdate = false;
1760 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001761 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001762 forceDeviceUpdate = true;
1763 }
1764
Eric Laurente552edb2014-03-10 17:42:56 -07001765 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001766 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001767
Eric Laurente552edb2014-03-10 17:42:56 -07001768 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001769 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001770 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001771 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001772 // delay the device switch by twice the latency because stopOutput() is executed when
1773 // the track stop() command is received and at that time the audio track buffer can
1774 // still contain data that needs to be drained. The latency only covers the audio HAL
1775 // and kernel buffers. Also the latency does not always include additional delay in the
1776 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001777 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001778
1779 // force restoring the device selection on other active outputs if it differs from the
1780 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001781 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001782 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001783 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001784 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001785 desc->isActive() &&
1786 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001787 (newDevices != desc->devices())) {
1788 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1789 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001790
François Gaffie11d30102018-11-02 16:09:09 +01001791 setOutputDevices(desc, newDevices2, force, delayMs);
1792
Eric Laurent57de36c2016-09-28 16:59:11 -07001793 // re-apply device specific volume if not done by setOutputDevice()
1794 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001795 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001796 }
Eric Laurente552edb2014-03-10 17:42:56 -07001797 }
1798 }
1799 // update the outputs if stopping one with a stream that can affect notification routing
1800 handleNotificationRoutingForStream(stream);
1801 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001802
1803 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1804 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001805 setStrategyMute(streamToStrategy(AUDIO_STREAM_RING), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001806 }
1807
François Gaffiec005e562018-11-06 15:04:49 +01001808 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001809 selectOutputForMusicEffects();
1810 }
Eric Laurente552edb2014-03-10 17:42:56 -07001811 return NO_ERROR;
1812 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001813 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001814 return INVALID_OPERATION;
1815 }
1816}
1817
Eric Laurent8fc147b2018-07-22 19:13:55 -07001818void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001819{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001820 ALOGV("%s portId %d", __FUNCTION__, portId);
1821
1822 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1823 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001824 // If an output descriptor is closed due to a device routing change,
1825 // then there are race conditions with releaseOutput from tracks
1826 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1827 // destroyed shortly thereafter.
1828 //
1829 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001830 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001831 return;
1832 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001833
1834 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001835
Eric Laurent8fc147b2018-07-22 19:13:55 -07001836 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1837 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001838 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001839 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001840 return;
1841 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001842 if (--outputDesc->mDirectOpenCount == 0) {
1843 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001844 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001845 }
1846 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001847 // stopOutput() needs to be successfully called before releaseOutput()
1848 // otherwise there may be inaccurate stream reference counts.
1849 // This is checked in outputDesc->removeClient below.
1850 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001851}
1852
Eric Laurentcaf7f482014-11-25 17:50:47 -08001853status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1854 audio_io_handle_t *input,
1855 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001856 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001857 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001858 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001859 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001860 input_type_t *inputType,
1861 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001862{
François Gaffiec005e562018-11-06 15:04:49 +01001863 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1864 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1865 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001866
Eric Laurentad2e7b92017-09-14 20:06:42 -07001867 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001868 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001869 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001870 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001871 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001872 sp<AudioInputDescriptor> inputDesc;
1873 sp<RecordClientDescriptor> clientDesc;
1874 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001875 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001876
1877 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1878 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1879 return INVALID_OPERATION;
1880 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001881
Francois Gaffie716e1432019-01-14 16:58:59 +01001882 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1883 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001884 }
1885
Paul McLean466dc8e2015-04-17 13:15:36 -06001886 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001887 sp<DeviceDescriptor> explicitRoutingDevice =
1888 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001889
Eric Laurentad2e7b92017-09-14 20:06:42 -07001890 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1891 // possible
1892 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1893 *input != AUDIO_IO_HANDLE_NONE) {
1894 ssize_t index = mInputs.indexOfKey(*input);
1895 if (index < 0) {
1896 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1897 status = BAD_VALUE;
1898 goto error;
1899 }
1900 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001901 RecordClientVector clients = inputDesc->getClientsForSession(session);
1902 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001903 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1904 status = BAD_VALUE;
1905 goto error;
1906 }
1907 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1908 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001909 // corresponds to a new client and is only permitted from the same UID.
1910 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001911 if (clients.size() > 1) {
1912 for (const auto& client : clients) {
1913 // The client map is ordered by key values (portId) and portIds are allocated
1914 // incrementaly. So the first client in this list is the one opened by audio flinger
1915 // when the mmap stream is created and should be ignored as it does not correspond
1916 // to an actual client
1917 if (client == *clients.cbegin()) {
1918 continue;
1919 }
1920 if (uid != client->uid() && !client->isSilenced()) {
1921 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1922 uid, client->portId(), client->uid());
1923 status = INVALID_OPERATION;
1924 goto error;
1925 }
Eric Laurent331679c2018-04-16 17:03:16 -07001926 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001927 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001928 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001929 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001930
Eric Laurent8f42ea12018-08-08 09:08:25 -07001931 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001932 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001933 }
1934
1935 *input = AUDIO_IO_HANDLE_NONE;
1936 *inputType = API_INPUT_INVALID;
1937
Francois Gaffie716e1432019-01-14 16:58:59 +01001938 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001939
Francois Gaffie716e1432019-01-14 16:58:59 +01001940 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1941 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1942 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001943 if (status != NO_ERROR) {
1944 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001945 }
1946 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001947 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001948 String8(attr->tags + strlen("addr=")),
1949 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001950 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001951 if (explicitRoutingDevice != nullptr) {
1952 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001953 } else {
François Gaffiec005e562018-11-06 15:04:49 +01001954 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001955 }
François Gaffie11d30102018-11-02 16:09:09 +01001956 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001957 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001958 status = BAD_VALUE;
1959 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001960 }
François Gaffie11d30102018-11-02 16:09:09 +01001961 if (policyMix != nullptr) {
1962 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1963 // there is an external policy, but this input is attached to a mix of recorders,
1964 // meaning it receives audio injected into the framework, so the recorder doesn't
1965 // know about it and is therefore considered "legacy"
1966 *inputType = API_INPUT_LEGACY;
1967 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001968 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001969 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001970 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001971 } else {
1972 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001973 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001974
Eric Laurent599c7582015-12-07 18:05:55 -08001975 }
1976
François Gaffiec005e562018-11-06 15:04:49 +01001977 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08001978 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001979 status = INVALID_OPERATION;
1980 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001981 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001982
Eric Laurent8f42ea12018-08-08 09:08:25 -07001983exit:
1984
François Gaffiec005e562018-11-06 15:04:49 +01001985 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1986 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001987
Francois Gaffie716e1432019-01-14 16:58:59 +01001988 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001989 mSoundTriggerSessions.indexOfKey(session) > 0;
1990 *portId = AudioPort::getNextUniqueId();
1991
François Gaffie11d30102018-11-02 16:09:09 +01001992 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001993 requestedDeviceId, attributes.source, flags,
1994 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001995 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001996 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001997
1998 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1999 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002000
Eric Laurent599c7582015-12-07 18:05:55 -08002001 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002002
2003error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002004 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002005}
2006
2007
François Gaffie11d30102018-11-02 16:09:09 +01002008audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002009 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002010 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002011 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002012 audio_input_flags_t flags,
2013 AudioMix *policyMix)
2014{
2015 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002016 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002017 bool isSoundTrigger = false;
2018
François Gaffiec005e562018-11-06 15:04:49 +01002019 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002020 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2021 if (index >= 0) {
2022 input = mSoundTriggerSessions.valueFor(session);
2023 isSoundTrigger = true;
2024 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2025 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2026 } else {
2027 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002028 }
François Gaffiec005e562018-11-06 15:04:49 +01002029 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002030 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002031 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002032 }
2033
Andy Hungf129b032015-04-07 13:45:50 -07002034 // find a compatible input profile (not necessarily identical in parameters)
2035 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002036 // sampling rate and flags may be updated by getInputProfile
2037 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2038 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002039 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002040 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002041 audio_input_flags_t profileFlags = flags;
2042 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002043 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002044 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002045 profileFlags);
2046 if (profile != 0) {
2047 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002048 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2049 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002050 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2051 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2052 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002053 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2054 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2055 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002056 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002057 }
Eric Laurente552edb2014-03-10 17:42:56 -07002058 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002059 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002060 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002061 if (samplingRate == 0) {
2062 samplingRate = profileSamplingRate;
2063 }
Eric Laurente552edb2014-03-10 17:42:56 -07002064
Eric Laurent322b4d22015-04-03 15:57:54 -07002065 if (profile->getModuleHandle() == 0) {
2066 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002067 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002068 }
2069
Eric Laurent3974e3b2017-12-07 17:58:43 -08002070 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002071 for (size_t i = 0; i < mInputs.size(); ) {
2072 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2073 if (desc->mProfile != profile) {
2074 continue;
2075 }
2076 // if sound trigger, reuse input if used by other sound trigger on same session
2077 // else
2078 // reuse input if active client app is not in IDLE state
2079 //
2080 RecordClientVector clients = desc->clientsList();
2081 bool doClose = false;
2082 for (const auto& client : clients) {
2083 if (isSoundTrigger != client->isSoundTrigger()) {
2084 continue;
2085 }
2086 if (client->isSoundTrigger()) {
2087 if (session == client->session()) {
2088 return desc->mIoHandle;
2089 }
2090 continue;
2091 }
2092 if (client->active() && client->appState() != APP_STATE_IDLE) {
2093 return desc->mIoHandle;
2094 }
2095 doClose = true;
2096 }
2097 if (doClose) {
2098 closeInput(desc->mIoHandle);
2099 } else {
2100 i++;
2101 }
2102 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002103 }
2104
Eric Laurentfe231122017-11-17 17:48:06 -08002105 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002106
Eric Laurentfe231122017-11-17 17:48:06 -08002107 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2108 lConfig.sample_rate = profileSamplingRate;
2109 lConfig.channel_mask = profileChannelMask;
2110 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002111
François Gaffie11d30102018-11-02 16:09:09 +01002112 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002113
2114 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002115 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002116 (profileSamplingRate != lConfig.sample_rate) ||
2117 !audio_formats_match(profileFormat, lConfig.format) ||
2118 (profileChannelMask != lConfig.channel_mask)) {
2119 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002120 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002121 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002122 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002123 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002124 }
Eric Laurent599c7582015-12-07 18:05:55 -08002125 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002126 }
2127
Eric Laurentc722f302014-12-10 11:21:49 -08002128 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002129
Eric Laurent599c7582015-12-07 18:05:55 -08002130 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002131 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002132
Eric Laurent599c7582015-12-07 18:05:55 -08002133 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002134}
2135
Eric Laurent4eb58f12018-12-07 16:41:02 -08002136status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002137{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002138 ALOGV("%s portId %d", __FUNCTION__, portId);
2139
2140 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2141 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002142 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002143 return BAD_VALUE;
2144 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002145 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002146 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 if (client->active()) {
2148 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2149 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002150 }
2151
Eric Laurent8f42ea12018-08-08 09:08:25 -07002152 audio_session_t session = client->session();
2153
Eric Laurent4eb58f12018-12-07 16:41:02 -08002154 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002155
Eric Laurent4eb58f12018-12-07 16:41:02 -08002156 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002157
Eric Laurent4eb58f12018-12-07 16:41:02 -08002158 status_t status = inputDesc->start();
2159 if (status != NO_ERROR) {
2160 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002161 }
Eric Laurente552edb2014-03-10 17:42:56 -07002162
Eric Laurent4eb58f12018-12-07 16:41:02 -08002163 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002164 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002166
Eric Laurent8f42ea12018-08-08 09:08:25 -07002167 // indicate active capture to sound trigger service if starting capture from a mic on
2168 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002169 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002170 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002171
Eric Laurent8f42ea12018-08-08 09:08:25 -07002172 if (inputDesc->activeCount() == 1) {
2173 // if input maps to a dynamic policy with an activity listener, notify of state change
2174 if ((inputDesc->mPolicyMix != NULL)
2175 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2176 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2177 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002178 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002179
François Gaffie11d30102018-11-02 16:09:09 +01002180 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2181 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002182 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2183 SoundTrigger::setCaptureState(true);
2184 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002185
Eric Laurent8f42ea12018-08-08 09:08:25 -07002186 // automatically enable the remote submix output when input is started if not
2187 // used by a policy mix of type MIX_TYPE_RECORDERS
2188 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002189 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002190 String8 address = String8("");
2191 if (inputDesc->mPolicyMix == NULL) {
2192 address = String8("0");
2193 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2194 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002195 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002196 if (address != "") {
2197 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2198 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002199 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002200 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002201 }
Eric Laurente552edb2014-03-10 17:42:56 -07002202 }
2203
Eric Laurent8f42ea12018-08-08 09:08:25 -07002204 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002205
Eric Laurente552edb2014-03-10 17:42:56 -07002206 return NO_ERROR;
2207}
2208
Eric Laurent8fc147b2018-07-22 19:13:55 -07002209status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002210{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002211 ALOGV("%s portId %d", __FUNCTION__, portId);
2212
2213 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2214 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002216 return BAD_VALUE;
2217 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002218 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002219 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002220 if (!client->active()) {
2221 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002222 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002223 }
2224
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002226
Eric Laurent8f42ea12018-08-08 09:08:25 -07002227 inputDesc->stop();
2228 if (inputDesc->isActive()) {
2229 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2230 } else {
2231 // if input maps to a dynamic policy with an activity listener, notify of state change
2232 if ((inputDesc->mPolicyMix != NULL)
2233 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2234 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2235 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002236 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002237
2238 // automatically disable the remote submix output when input is stopped if not
2239 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002240 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002241 String8 address = String8("");
2242 if (inputDesc->mPolicyMix == NULL) {
2243 address = String8("0");
2244 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2245 address = inputDesc->mPolicyMix->mDeviceAddress;
2246 }
2247 if (address != "") {
2248 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2249 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002250 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002251 }
2252 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002253 resetInputDevice(input);
2254
2255 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2256 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002257 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2258 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002259 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2260 SoundTrigger::setCaptureState(false);
2261 }
2262 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002263 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002264 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002265}
2266
Eric Laurent8fc147b2018-07-22 19:13:55 -07002267void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002268{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002269 ALOGV("%s portId %d", __FUNCTION__, portId);
2270
2271 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2272 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002273 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002274 return;
2275 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002276 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002277 audio_io_handle_t input = inputDesc->mIoHandle;
2278
Eric Laurent8f42ea12018-08-08 09:08:25 -07002279 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002280
Andy Hung39efb7a2018-09-26 15:39:28 -07002281 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002282
Andy Hung39efb7a2018-09-26 15:39:28 -07002283 if (inputDesc->getClientCount() > 0) {
2284 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002285 return;
2286 }
2287
Eric Laurent05b90f82014-08-27 15:32:29 -07002288 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002289 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002290 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002291}
2292
Eric Laurent8f42ea12018-08-08 09:08:25 -07002293void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002294{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002295 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002296
2297 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002298 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002299 }
2300}
2301
Eric Laurent8f42ea12018-08-08 09:08:25 -07002302void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2303{
2304 stopInput(portId);
2305 releaseInput(portId);
2306}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002307
Eric Laurentd4692962014-05-05 18:13:44 -07002308void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002309 bool patchRemoved = false;
2310
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002311 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002312 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002313 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002314 if (patch_index >= 0) {
2315 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002316 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002317 mAudioPatches.removeItemsAt(patch_index);
2318 patchRemoved = true;
2319 }
Eric Laurentfe231122017-11-17 17:48:06 -08002320 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002321 }
2322 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002323 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002324 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002325
2326 if (patchRemoved) {
2327 mpClientInterface->onAudioPatchListUpdate();
2328 }
Eric Laurentd4692962014-05-05 18:13:44 -07002329}
2330
Eric Laurente0720872014-03-11 09:30:41 -07002331void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002332 int indexMin,
2333 int indexMax)
2334{
2335 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002336 if (indexMin < 0 || indexMax < 0) {
2337 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2338 return;
2339 }
François Gaffied1ab2bd2015-12-02 18:20:06 +01002340 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002341
2342 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002343 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2344 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002345 continue;
2346 }
2347 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002348 }
Eric Laurente552edb2014-03-10 17:42:56 -07002349}
2350
Eric Laurente0720872014-03-11 09:30:41 -07002351status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002352 int index,
2353 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002354{
2355
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002356 // VOICE_CALL and BLUETOOTH_SCO stream have minVolumeIndex > 0 but
2357 // can be muted directly by an app that has MODIFY_PHONE_STATE permission.
Nadav Bar7c605f62017-12-25 00:01:52 +02002358 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002359 !((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
2360 index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002361 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002362 return BAD_VALUE;
2363 }
2364 if (!audio_is_output_device(device)) {
2365 return BAD_VALUE;
2366 }
2367
2368 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002369 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002370
Eric Laurent1fd372e2016-04-06 14:23:53 -07002371 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002372 stream, device, index);
2373
Eric Laurent28d09f02016-03-08 10:43:05 -08002374 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002375 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2376 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002377 continue;
2378 }
2379 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2380 }
Eric Laurente552edb2014-03-10 17:42:56 -07002381
Eric Laurent1fd372e2016-04-06 14:23:53 -07002382 // update volume on all outputs and streams matching the following:
2383 // - The requested stream (or a stream matching for volume control) is active on the output
François Gaffiec005e562018-11-06 15:04:49 +01002384 // - The device (or devices) selected by the engine for this stream includes
Eric Laurent1fd372e2016-04-06 14:23:53 -07002385 // the requested device
2386 // - For non default requested device, currently selected device on the output is either the
François Gaffiec005e562018-11-06 15:04:49 +01002387 // requested device or one of the devices selected by the engine for this stream
Eric Laurent5a2b6292016-04-14 18:05:57 -07002388 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2389 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002390 status_t status = NO_ERROR;
2391 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002392 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002393 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002394 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002395 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002396 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002397 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002398 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002399 continue;
2400 }
François Gaffiec005e562018-11-06 15:04:49 +01002401 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(
2402 mEngine->getOutputDevicesForStream((audio_stream_type_t)curStream,
2403 false /*fromCache*/).types());
Eric Laurente76f29c2016-09-14 17:17:53 -07002404 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2405 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002406 continue;
2407 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002408 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002409 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002410 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002411 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002412 } else {
2413 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002414 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002415 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002416 // rescale index before applying to curStream as ranges may be different for
2417 // stream and curStream
2418 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002419 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002420 //FIXME: workaround for truncated touch sounds
2421 // delayed volume change for system stream to be removed when the problem is
2422 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002423 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002424 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002425 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002426 if (volStatus != NO_ERROR) {
2427 status = volStatus;
2428 }
2429 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002430 }
Eric Laurente552edb2014-03-10 17:42:56 -07002431 }
2432 return status;
2433}
2434
Eric Laurente0720872014-03-11 09:30:41 -07002435status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002436 int *index,
2437 audio_devices_t device)
2438{
2439 if (index == NULL) {
2440 return BAD_VALUE;
2441 }
2442 if (!audio_is_output_device(device)) {
2443 return BAD_VALUE;
2444 }
François Gaffiec005e562018-11-06 15:04:49 +01002445 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2446 // stream by the engine.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002447 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
François Gaffiec005e562018-11-06 15:04:49 +01002448 device = mEngine->getOutputDevicesForStream(stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002449 }
François Gaffiedfd74092015-03-19 12:10:59 +01002450 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002451
François Gaffied1ab2bd2015-12-02 18:20:06 +01002452 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002453 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2454 return NO_ERROR;
2455}
2456
Eric Laurent36829f92017-04-07 19:04:42 -07002457audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002458{
2459 // select one output among several suitable for global effects.
2460 // The priority is as follows:
2461 // 1: An offloaded output. If the effect ends up not being offloadable,
2462 // AudioFlinger will invalidate the track and the offloaded output
2463 // will be closed causing the effect to be moved to a PCM output.
2464 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002465 // 3: The primary output
2466 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002467
François Gaffiec005e562018-11-06 15:04:49 +01002468 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2469 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002470 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002471
Eric Laurent36829f92017-04-07 19:04:42 -07002472 if (outputs.size() == 0) {
2473 return AUDIO_IO_HANDLE_NONE;
2474 }
Eric Laurente552edb2014-03-10 17:42:56 -07002475
Eric Laurent36829f92017-04-07 19:04:42 -07002476 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2477 bool activeOnly = true;
2478
2479 while (output == AUDIO_IO_HANDLE_NONE) {
2480 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2481 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2482 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2483
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002484 for (audio_io_handle_t output : outputs) {
2485 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002486 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2487 continue;
2488 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002489 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2490 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002491 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002492 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002493 }
2494 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002495 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002496 }
2497 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002498 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002499 }
2500 }
2501 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2502 output = outputOffloaded;
2503 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2504 output = outputDeepBuffer;
2505 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2506 output = outputPrimary;
2507 } else {
2508 output = outputs[0];
2509 }
2510 activeOnly = false;
2511 }
2512
2513 if (output != mMusicEffectOutput) {
2514 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2515 mMusicEffectOutput = output;
2516 }
2517
2518 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002519 return output;
2520}
2521
Eric Laurent36829f92017-04-07 19:04:42 -07002522audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2523{
2524 return selectOutputForMusicEffects();
2525}
2526
Eric Laurente0720872014-03-11 09:30:41 -07002527status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002528 audio_io_handle_t io,
2529 uint32_t strategy,
2530 int session,
2531 int id)
2532{
2533 ssize_t index = mOutputs.indexOfKey(io);
2534 if (index < 0) {
2535 index = mInputs.indexOfKey(io);
2536 if (index < 0) {
2537 ALOGW("registerEffect() unknown io %d", io);
2538 return INVALID_OPERATION;
2539 }
2540 }
François Gaffiec005e562018-11-06 15:04:49 +01002541 return mEffects.registerEffect(desc, io, session, id,
2542 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2543 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002544}
2545
Eric Laurentc241b0d2018-11-28 09:08:49 -08002546status_t AudioPolicyManager::unregisterEffect(int id)
2547{
2548 if (mEffects.getEffect(id) == nullptr) {
2549 return INVALID_OPERATION;
2550 }
2551
2552 if (mEffects.isEffectEnabled(id)) {
2553 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2554 setEffectEnabled(id, false);
2555 }
2556 return mEffects.unregisterEffect(id);
2557}
2558
2559status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2560{
2561 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2562 if (effect == nullptr) {
2563 return INVALID_OPERATION;
2564 }
2565
2566 status_t status = mEffects.setEffectEnabled(id, enabled);
2567 if (status == NO_ERROR) {
2568 mInputs.trackEffectEnabled(effect, enabled);
2569 }
2570 return status;
2571}
2572
Eric Laurentc75307b2015-03-17 15:29:32 -07002573bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2574{
Eric Laurent28d09f02016-03-08 10:43:05 -08002575 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002576 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2577 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002578 continue;
2579 }
2580 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2581 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002582 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002583}
2584
2585bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2586{
2587 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2588}
2589
Eric Laurente0720872014-03-11 09:30:41 -07002590bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002591{
2592 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002593 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002594 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002595 return true;
2596 }
2597 }
2598 return false;
2599}
2600
Eric Laurent275e8e92014-11-30 15:14:47 -08002601// Register a list of custom mixes with their attributes and format.
2602// When a mix is registered, corresponding input and output profiles are
2603// added to the remote submix hw module. The profile contains only the
2604// parameters (sampling rate, format...) specified by the mix.
2605// The corresponding input remote submix device is also connected.
2606//
2607// When a remote submix device is connected, the address is checked to select the
2608// appropriate profile and the corresponding input or output stream is opened.
2609//
2610// When capture starts, getInputForAttr() will:
2611// - 1 look for a mix matching the address passed in attribtutes tags if any
2612// - 2 if none found, getDeviceForInputSource() will:
2613// - 2.1 look for a mix matching the attributes source
2614// - 2.2 if none found, default to device selection by policy rules
2615// At this time, the corresponding output remote submix device is also connected
2616// and active playback use cases can be transferred to this mix if needed when reconnecting
2617// after AudioTracks are invalidated
2618//
2619// When playback starts, getOutputForAttr() will:
2620// - 1 look for a mix matching the address passed in attribtutes tags if any
2621// - 2 if none found, look for a mix matching the attributes usage
2622// - 3 if none found, default to device and output selection by policy rules.
2623
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002624status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002625{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002626 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2627 status_t res = NO_ERROR;
2628
2629 sp<HwModule> rSubmixModule;
2630 // examine each mix's route type
2631 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002632 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002633 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2634 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2635 ALOGE("Unsupported Policy Mix %zu of %zu: "
2636 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2637 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002638 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002639 break;
2640 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002641 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2642 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002643 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002644 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2645 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002646 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002647 rSubmixModule = mHwModules.getModuleFromName(
2648 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2649 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002650 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002651 i);
2652 res = INVALID_OPERATION;
2653 break;
2654 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002655 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002656
Eric Laurent97ac8712018-07-27 18:59:02 -07002657 String8 address = mix.mDeviceAddress;
2658 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2659 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2660 } else {
2661 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2662 }
François Gaffie036e1e92015-03-19 10:16:24 +01002663
Eric Laurent97ac8712018-07-27 18:59:02 -07002664 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002665 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002666 res = INVALID_OPERATION;
2667 break;
2668 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002669 audio_config_t outputConfig = mix.mFormat;
2670 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002671 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2672 // stereo and let audio flinger do the channel conversion if needed.
2673 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2674 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2675 rSubmixModule->addOutputProfile(address, &outputConfig,
2676 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2677 rSubmixModule->addInputProfile(address, &inputConfig,
2678 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002679
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002681 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2682 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002683 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002684 } else {
2685 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2686 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002687 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002688 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002689 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2690 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002691 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002692 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002693 i, mixes.size(), type, address.string());
2694
2695 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2696 mix.mDeviceType, mix.mDeviceAddress,
2697 String8(), AUDIO_FORMAT_DEFAULT);
2698 if (device == nullptr) {
2699 res = INVALID_OPERATION;
2700 break;
2701 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002702
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002703 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002704 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2705 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002706
2707 if (desc->supportedDevices().contains(device)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002708 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002709 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2710 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002711 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002712 } else {
2713 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002714 }
2715 break;
2716 }
2717 }
2718
2719 if (res != NO_ERROR) {
2720 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002721 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002722 res = INVALID_OPERATION;
2723 break;
2724 } else if (!foundOutput) {
2725 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002726 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002727 res = INVALID_OPERATION;
2728 break;
2729 }
Eric Laurentc722f302014-12-10 11:21:49 -08002730 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002731 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002732 if (res != NO_ERROR) {
2733 unregisterPolicyMixes(mixes);
2734 }
2735 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002736}
2737
2738status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2739{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002740 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002741 status_t res = NO_ERROR;
2742 sp<HwModule> rSubmixModule;
2743 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002744 for (const auto& mix : mixes) {
2745 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002746
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002747 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002748 rSubmixModule = mHwModules.getModuleFromName(
2749 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2750 if (rSubmixModule == 0) {
2751 res = INVALID_OPERATION;
2752 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002753 }
2754 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002755
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002756 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002757
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002758 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2759 res = INVALID_OPERATION;
2760 continue;
2761 }
2762
2763 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2764 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2765 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2766 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002767 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002768 }
2769 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2770 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2771 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2772 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002773 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002774 }
2775 rSubmixModule->removeOutputProfile(address);
2776 rSubmixModule->removeInputProfile(address);
2777
Kevin Rocard153f92d2018-12-18 18:33:28 -08002778 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002779 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002780 res = INVALID_OPERATION;
2781 continue;
2782 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002783 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002784 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002785 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002786}
2787
Mikhail Naganov100f0122018-11-29 11:22:16 -08002788void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2789{
2790 size_t i = 0;
2791 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2792 for (const auto& fmt : mManualSurroundFormats) {
2793 if (i++ != 0) dst->append(", ");
2794 std::string sfmt;
2795 FormatConverter::toString(fmt, sfmt);
2796 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2797 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2798 }
2799}
2800
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002801status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2802 const Vector<AudioDeviceTypeAddr>& devices) {
2803 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2804 // uid/device affinity is only for output devices
2805 for (size_t i = 0; i < devices.size(); i++) {
2806 if (!audio_is_output_device(devices[i].mType)) {
2807 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2808 devices[i].mType);
2809 return BAD_VALUE;
2810 }
2811 }
2812 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2813 if (res == NO_ERROR) {
2814 // reevaluate outputs for all given devices
2815 for (size_t i = 0; i < devices.size(); i++) {
2816 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002817 devices[i].mType, devices[i].mAddress, String8(),
2818 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002819 SortedVector<audio_io_handle_t> outputs;
2820 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002821 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002822 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2823 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2824 return INVALID_OPERATION;
2825 }
2826 }
2827 }
2828 return res;
2829}
2830
2831status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2832 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2833 Vector<AudioDeviceTypeAddr> devices;
2834 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2835 if (res == NO_ERROR) {
2836 // reevaluate outputs for all found devices
2837 for (size_t i = 0; i < devices.size(); i++) {
2838 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002839 devices[i].mType, devices[i].mAddress, String8(),
2840 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002841 SortedVector<audio_io_handle_t> outputs;
2842 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002843 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002844 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2845 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2846 return INVALID_OPERATION;
2847 }
2848 }
2849 }
2850
2851 return res;
2852}
2853
Andy Hungc29d82b2018-10-05 12:23:17 -07002854void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002855{
Andy Hungc29d82b2018-10-05 12:23:17 -07002856 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2857 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002858 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002859 std::string stateLiteral;
2860 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002861 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002862 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2863 "communications", "media", "record", "dock", "system",
2864 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2865 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2866 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002867 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2868 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2869 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2870 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2871 dst->append(" (MANUAL: ");
2872 dumpManualSurroundFormats(dst);
2873 dst->append(")");
2874 }
2875 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002876 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002877 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2878 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2879 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2880 mAvailableOutputDevices.dump(dst, String8("Available output"));
2881 mAvailableInputDevices.dump(dst, String8("Available input"));
2882 mHwModulesAll.dump(dst);
2883 mOutputs.dump(dst);
2884 mInputs.dump(dst);
2885 mVolumeCurves->dump(dst);
2886 mEffects.dump(dst);
2887 mAudioPatches.dump(dst);
2888 mPolicyMixes.dump(dst);
2889 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01002890
2891 dst->appendFormat("\nPolicy Engine dump:\n");
2892 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002893}
2894
2895status_t AudioPolicyManager::dump(int fd)
2896{
2897 String8 result;
2898 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002899 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002900 return NO_ERROR;
2901}
2902
2903// This function checks for the parameters which can be offloaded.
2904// This can be enhanced depending on the capability of the DSP and policy
2905// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002906bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002907{
2908 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002909 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002910 offloadInfo.sample_rate, offloadInfo.channel_mask,
2911 offloadInfo.format,
2912 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2913 offloadInfo.has_video);
2914
Andy Hung2ddee192015-12-18 17:34:44 -08002915 if (mMasterMono) {
2916 return false; // no offloading if mono is set.
2917 }
2918
Eric Laurente552edb2014-03-10 17:42:56 -07002919 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002920 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2921 ALOGV("offload disabled by audio.offload.disable");
2922 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002923 }
2924
2925 // Check if stream type is music, then only allow offload as of now.
2926 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2927 {
2928 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2929 return false;
2930 }
2931
2932 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002933 const bool allowOffloadWithVideo =
2934 property_get_bool("audio.offload.video", false /* default_value */);
2935 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002936 ALOGV("isOffloadSupported: has_video == true, returning false");
2937 return false;
2938 }
2939
2940 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002941 const int min_duration_secs = property_get_int32(
2942 "audio.offload.min.duration.secs", -1 /* default_value */);
2943 if (min_duration_secs >= 0) {
2944 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2945 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2946 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002947 return false;
2948 }
2949 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2950 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2951 return false;
2952 }
2953
2954 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2955 // creating an offloaded track and tearing it down immediately after start when audioflinger
2956 // detects there is an active non offloadable effect.
2957 // FIXME: We should check the audio session here but we do not have it in this context.
2958 // This may prevent offloading in rare situations where effects are left active by apps
2959 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002960 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002961 return false;
2962 }
2963
2964 // See if there is a profile to support this.
2965 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002966 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002967 offloadInfo.sample_rate,
2968 offloadInfo.format,
2969 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002970 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2971 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002972 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2973 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002974}
2975
Michael Chana94fbb22018-04-24 14:31:19 +10002976bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2977 const audio_attributes_t& attributes) {
2978 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01002979 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002980 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002981 config.sample_rate,
2982 config.format,
2983 config.channel_mask,
2984 output_flags,
2985 true /* directOnly */);
2986 ALOGV("%s() profile %sfound with name: %s, "
2987 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2988 __FUNCTION__, profile != 0 ? "" : "NOT ",
2989 (profile != 0 ? profile->getTagName().string() : "null"),
2990 config.sample_rate, config.format, config.channel_mask, output_flags);
2991 return (profile != 0);
2992}
2993
Eric Laurent6a94d692014-05-20 11:18:06 -07002994status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2995 audio_port_type_t type,
2996 unsigned int *num_ports,
2997 struct audio_port *ports,
2998 unsigned int *generation)
2999{
3000 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3001 generation == NULL) {
3002 return BAD_VALUE;
3003 }
3004 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3005 if (ports == NULL) {
3006 *num_ports = 0;
3007 }
3008
3009 size_t portsWritten = 0;
3010 size_t portsMax = *num_ports;
3011 *num_ports = 0;
3012 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003013 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3014 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003015 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003016 for (const auto& dev : mAvailableOutputDevices) {
3017 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003018 continue;
3019 }
3020 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003021 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003022 }
3023 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003024 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003025 }
3026 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003027 for (const auto& dev : mAvailableInputDevices) {
3028 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003029 continue;
3030 }
3031 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003032 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003033 }
3034 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003035 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003036 }
3037 }
3038 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3039 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3040 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3041 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3042 }
3043 *num_ports += mInputs.size();
3044 }
3045 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003046 size_t numOutputs = 0;
3047 for (size_t i = 0; i < mOutputs.size(); i++) {
3048 if (!mOutputs[i]->isDuplicated()) {
3049 numOutputs++;
3050 if (portsWritten < portsMax) {
3051 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3052 }
3053 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003054 }
Eric Laurent84c70242014-06-23 08:46:27 -07003055 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003056 }
3057 }
3058 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003059 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003060 return NO_ERROR;
3061}
3062
Eric Laurent99fcae42018-05-17 16:59:18 -07003063status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003064{
Eric Laurent99fcae42018-05-17 16:59:18 -07003065 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3066 return BAD_VALUE;
3067 }
3068 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3069 if (dev != 0) {
3070 dev->toAudioPort(port);
3071 return NO_ERROR;
3072 }
3073 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3074 if (dev != 0) {
3075 dev->toAudioPort(port);
3076 return NO_ERROR;
3077 }
3078 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3079 if (out != 0) {
3080 out->toAudioPort(port);
3081 return NO_ERROR;
3082 }
3083 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3084 if (in != 0) {
3085 in->toAudioPort(port);
3086 return NO_ERROR;
3087 }
3088 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003089}
3090
Eric Laurent6a94d692014-05-20 11:18:06 -07003091status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3092 audio_patch_handle_t *handle,
3093 uid_t uid)
3094{
3095 ALOGV("createAudioPatch()");
3096
3097 if (handle == NULL || patch == NULL) {
3098 return BAD_VALUE;
3099 }
3100 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3101
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003102 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003103 return BAD_VALUE;
3104 }
3105 // only one source per audio patch supported for now
3106 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003107 return INVALID_OPERATION;
3108 }
Eric Laurent874c42872014-08-08 15:13:39 -07003109
3110 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003111 return INVALID_OPERATION;
3112 }
Eric Laurent874c42872014-08-08 15:13:39 -07003113 for (size_t i = 0; i < patch->num_sinks; i++) {
3114 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3115 return INVALID_OPERATION;
3116 }
3117 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003118
3119 sp<AudioPatch> patchDesc;
3120 ssize_t index = mAudioPatches.indexOfKey(*handle);
3121
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3123 patch->sources[0].role,
3124 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003125#if LOG_NDEBUG == 0
3126 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003127 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003128 patch->sinks[i].role,
3129 patch->sinks[i].type);
3130 }
3131#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003132
3133 if (index >= 0) {
3134 patchDesc = mAudioPatches.valueAt(index);
3135 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3136 mUidCached, patchDesc->mUid, uid);
3137 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3138 return INVALID_OPERATION;
3139 }
3140 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003141 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003142 }
3143
3144 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003145 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003146 if (outputDesc == NULL) {
3147 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3148 return BAD_VALUE;
3149 }
Eric Laurent84c70242014-06-23 08:46:27 -07003150 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3151 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003152 if (patchDesc != 0) {
3153 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3154 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3155 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3156 return BAD_VALUE;
3157 }
3158 }
Eric Laurent874c42872014-08-08 15:13:39 -07003159 DeviceVector devices;
3160 for (size_t i = 0; i < patch->num_sinks; i++) {
3161 // Only support mix to devices connection
3162 // TODO add support for mix to mix connection
3163 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3164 ALOGV("createAudioPatch() source mix but sink is not a device");
3165 return INVALID_OPERATION;
3166 }
3167 sp<DeviceDescriptor> devDesc =
3168 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3169 if (devDesc == 0) {
3170 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3171 return BAD_VALUE;
3172 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003173
François Gaffie11d30102018-11-02 16:09:09 +01003174 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003175 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003176 NULL, // updatedSamplingRate
3177 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003178 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003179 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003180 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003181 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003182 ALOGV("createAudioPatch() profile not supported for device %08x",
3183 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003184 return INVALID_OPERATION;
3185 }
3186 devices.add(devDesc);
3187 }
3188 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003189 return INVALID_OPERATION;
3190 }
Eric Laurent874c42872014-08-08 15:13:39 -07003191
Eric Laurent6a94d692014-05-20 11:18:06 -07003192 // TODO: reconfigure output format and channels here
3193 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003194 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003195 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 index = mAudioPatches.indexOfKey(*handle);
3197 if (index >= 0) {
3198 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3199 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3200 }
3201 patchDesc = mAudioPatches.valueAt(index);
3202 patchDesc->mUid = uid;
3203 ALOGV("createAudioPatch() success");
3204 } else {
3205 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3206 return INVALID_OPERATION;
3207 }
3208 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3209 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3210 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003211 // only one sink supported when connecting an input device to a mix
3212 if (patch->num_sinks > 1) {
3213 return INVALID_OPERATION;
3214 }
François Gaffie53615e22015-03-19 09:24:12 +01003215 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003216 if (inputDesc == NULL) {
3217 return BAD_VALUE;
3218 }
3219 if (patchDesc != 0) {
3220 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3221 return BAD_VALUE;
3222 }
3223 }
François Gaffie11d30102018-11-02 16:09:09 +01003224 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003225 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003226 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003227 return BAD_VALUE;
3228 }
3229
François Gaffie11d30102018-11-02 16:09:09 +01003230 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003231 patch->sinks[0].sample_rate,
3232 NULL, /*updatedSampleRate*/
3233 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003234 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003235 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003236 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003237 // FIXME for the parameter type,
3238 // and the NONE
3239 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003240 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003241 return INVALID_OPERATION;
3242 }
3243 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003244 ALOGV("%s() setting device %s on output %d", __func__,
3245 device->toString().c_str(), inputDesc->mIoHandle);
3246 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003247 index = mAudioPatches.indexOfKey(*handle);
3248 if (index >= 0) {
3249 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3250 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3251 }
3252 patchDesc = mAudioPatches.valueAt(index);
3253 patchDesc->mUid = uid;
3254 ALOGV("createAudioPatch() success");
3255 } else {
3256 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3257 return INVALID_OPERATION;
3258 }
3259 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3260 // device to device connection
3261 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003262 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003263 return BAD_VALUE;
3264 }
3265 }
François Gaffie11d30102018-11-02 16:09:09 +01003266 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003267 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003268 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003269 return BAD_VALUE;
3270 }
Eric Laurent874c42872014-08-08 15:13:39 -07003271
Eric Laurent6a94d692014-05-20 11:18:06 -07003272 //update source and sink with our own data as the data passed in the patch may
3273 // be incomplete.
3274 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003275 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003276
Eric Laurent874c42872014-08-08 15:13:39 -07003277 for (size_t i = 0; i < patch->num_sinks; i++) {
3278 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3279 ALOGV("createAudioPatch() source device but one sink is not a device");
3280 return INVALID_OPERATION;
3281 }
3282
François Gaffie11d30102018-11-02 16:09:09 +01003283 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003284 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003285 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003286 return BAD_VALUE;
3287 }
François Gaffie11d30102018-11-02 16:09:09 +01003288 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003289
Eric Laurent3bcf8592015-04-03 12:13:24 -07003290 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003291 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003292 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003293 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003294 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3295 (srcDevice->getModuleVersionMajor() < 3) ||
3296 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003297 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003298 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003299 return INVALID_OPERATION;
3300 }
Eric Laurent874c42872014-08-08 15:13:39 -07003301 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003302 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003303 // if the sink device is reachable via an opened output stream, request to go via
3304 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003305 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003306 if (output != AUDIO_IO_HANDLE_NONE) {
3307 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3308 if (outputDesc->isDuplicated()) {
3309 return INVALID_OPERATION;
3310 }
3311 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003312 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003313 newPatch.num_sources = 2;
3314 }
Eric Laurent83b88082014-06-20 18:31:16 -07003315 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003316 }
3317 // TODO: check from routing capabilities in config file and other conflicting patches
3318
Mikhail Naganovdc769682018-05-04 15:34:08 -07003319 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3320 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003321 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3322 status);
3323 return INVALID_OPERATION;
3324 }
3325 } else {
3326 return BAD_VALUE;
3327 }
3328 } else {
3329 return BAD_VALUE;
3330 }
3331 return NO_ERROR;
3332}
3333
3334status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3335 uid_t uid)
3336{
3337 ALOGV("releaseAudioPatch() patch %d", handle);
3338
3339 ssize_t index = mAudioPatches.indexOfKey(handle);
3340
3341 if (index < 0) {
3342 return BAD_VALUE;
3343 }
3344 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3345 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3346 mUidCached, patchDesc->mUid, uid);
3347 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3348 return INVALID_OPERATION;
3349 }
3350
3351 struct audio_patch *patch = &patchDesc->mPatch;
3352 patchDesc->mUid = mUidCached;
3353 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003354 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003355 if (outputDesc == NULL) {
3356 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3357 return BAD_VALUE;
3358 }
3359
François Gaffie11d30102018-11-02 16:09:09 +01003360 setOutputDevices(outputDesc,
3361 getNewOutputDevices(outputDesc, true /*fromCache*/),
3362 true,
3363 0,
3364 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003365 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3366 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003367 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003368 if (inputDesc == NULL) {
3369 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3370 return BAD_VALUE;
3371 }
3372 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003373 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003374 true,
3375 NULL);
3376 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003377 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3378 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3379 status, patchDesc->mAfPatchHandle);
3380 removeAudioPatch(patchDesc->mHandle);
3381 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003382 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003383 } else {
3384 return BAD_VALUE;
3385 }
3386 } else {
3387 return BAD_VALUE;
3388 }
3389 return NO_ERROR;
3390}
3391
3392status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3393 struct audio_patch *patches,
3394 unsigned int *generation)
3395{
François Gaffie53615e22015-03-19 09:24:12 +01003396 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003397 return BAD_VALUE;
3398 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003399 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003400 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003401}
3402
Eric Laurente1715a42014-05-20 11:30:42 -07003403status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003404{
Eric Laurente1715a42014-05-20 11:30:42 -07003405 ALOGV("setAudioPortConfig()");
3406
3407 if (config == NULL) {
3408 return BAD_VALUE;
3409 }
3410 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3411 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003412 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3413 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003414 }
3415
Eric Laurenta121f902014-06-03 13:32:54 -07003416 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003417 if (config->type == AUDIO_PORT_TYPE_MIX) {
3418 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003419 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003420 if (outputDesc == NULL) {
3421 return BAD_VALUE;
3422 }
Eric Laurent84c70242014-06-23 08:46:27 -07003423 ALOG_ASSERT(!outputDesc->isDuplicated(),
3424 "setAudioPortConfig() called on duplicated output %d",
3425 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003426 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003427 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003428 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003429 if (inputDesc == NULL) {
3430 return BAD_VALUE;
3431 }
Eric Laurenta121f902014-06-03 13:32:54 -07003432 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003433 } else {
3434 return BAD_VALUE;
3435 }
3436 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3437 sp<DeviceDescriptor> deviceDesc;
3438 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3439 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3440 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3441 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3442 } else {
3443 return BAD_VALUE;
3444 }
3445 if (deviceDesc == NULL) {
3446 return BAD_VALUE;
3447 }
Eric Laurenta121f902014-06-03 13:32:54 -07003448 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003449 } else {
3450 return BAD_VALUE;
3451 }
3452
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003453 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003454 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3455 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003456 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003457 audioPortConfig->toAudioPortConfig(&newConfig, config);
3458 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003459 }
Eric Laurenta121f902014-06-03 13:32:54 -07003460 if (status != NO_ERROR) {
3461 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003462 }
Eric Laurente1715a42014-05-20 11:30:42 -07003463
3464 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003465}
3466
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003467void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3468{
Eric Laurentd60560a2015-04-10 11:31:20 -07003469 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003470 clearAudioPatches(uid);
3471 clearSessionRoutes(uid);
3472}
3473
Eric Laurent6a94d692014-05-20 11:18:06 -07003474void AudioPolicyManager::clearAudioPatches(uid_t uid)
3475{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003476 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003477 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3478 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003479 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003480 }
3481 }
3482}
3483
François Gaffiec005e562018-11-06 15:04:49 +01003484void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003485{
François Gaffiec005e562018-11-06 15:04:49 +01003486 // Take the first attributes following the product strategy as it is used to retrieve the routed
3487 // device. All attributes wihin a strategy follows the same "routing strategy"
3488 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
3489 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01003490 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003491 for (size_t j = 0; j < mOutputs.size(); j++) {
3492 if (mOutputs.keyAt(j) == ouptutToSkip) {
3493 continue;
3494 }
3495 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01003496 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003497 continue;
3498 }
3499 // If the default device for this strategy is on another output mix,
3500 // invalidate all tracks in this strategy to force re connection.
3501 // Otherwise select new device on the output mix.
3502 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01003503 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
3504 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003505 }
3506 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003507 setOutputDevices(
3508 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003509 }
3510 }
3511}
3512
3513void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3514{
3515 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01003516 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003517 for (size_t i = 0; i < mOutputs.size(); i++) {
3518 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003519 for (const auto& client : outputDesc->getClientIterable()) {
3520 if (client->hasPreferredDevice() && client->uid() == uid) {
3521 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01003522 auto clientStrategy = client->strategy();
3523 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
3524 end(affectedStrategies)) {
3525 continue;
3526 }
3527 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003528 }
3529 }
3530 }
3531 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003532 for (const auto& strategy : affectedStrategies) {
3533 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003534 }
3535
3536 // remove input routes associated with this uid
3537 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003538 for (size_t i = 0; i < mInputs.size(); i++) {
3539 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003540 for (const auto& client : inputDesc->getClientIterable()) {
3541 if (client->hasPreferredDevice() && client->uid() == uid) {
3542 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3543 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003544 }
3545 }
3546 }
3547 // reroute inputs if necessary
3548 SortedVector<audio_io_handle_t> inputsToClose;
3549 for (size_t i = 0; i < mInputs.size(); i++) {
3550 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003551 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003552 inputsToClose.add(inputDesc->mIoHandle);
3553 }
3554 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003555 for (const auto& input : inputsToClose) {
3556 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003557 }
3558}
3559
Eric Laurentd60560a2015-04-10 11:31:20 -07003560void AudioPolicyManager::clearAudioSources(uid_t uid)
3561{
3562 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003563 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3564 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003565 stopAudioSource(mAudioSources.keyAt(i));
3566 }
3567 }
3568}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003569
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003570status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3571 audio_io_handle_t *ioHandle,
3572 audio_devices_t *device)
3573{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003574 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3575 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003576 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01003577 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003578
François Gaffiedf372692015-03-19 10:43:27 +01003579 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003580}
3581
Eric Laurentd60560a2015-04-10 11:31:20 -07003582status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003583 const audio_attributes_t *attributes,
3584 audio_port_handle_t *portId,
3585 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003586{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003587 ALOGV("%s", __FUNCTION__);
3588 *portId = AUDIO_PORT_HANDLE_NONE;
3589
3590 if (source == NULL || attributes == NULL || portId == NULL) {
3591 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3592 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003593 return BAD_VALUE;
3594 }
3595
Eric Laurentd60560a2015-04-10 11:31:20 -07003596 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3597 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003598 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3599 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003600 return INVALID_OPERATION;
3601 }
3602
François Gaffie11d30102018-11-02 16:09:09 +01003603 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003604 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003605 String8(source->ext.device.address),
3606 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003607 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003608 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003609 return BAD_VALUE;
3610 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003611
3612 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003613
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003614 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003615 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003616
3617 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003618 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
François Gaffiec005e562018-11-06 15:04:49 +01003619 mEngine->getStreamTypeForAttributes(*attributes),
3620 mEngine->getProductStrategyForAttributes(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003621
3622 status_t status = connectAudioSource(sourceDesc);
3623 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003624 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003625 }
3626 return status;
3627}
3628
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003629status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003630{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003631 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003632
3633 // make sure we only have one patch per source.
3634 disconnectAudioSource(sourceDesc);
3635
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003636 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003637 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003638 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003639
François Gaffiec005e562018-11-06 15:04:49 +01003640 DeviceVector sinkDevices =
3641 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
3642 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01003643 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3644 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3645 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003646
3647 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003648
François Gaffie11d30102018-11-02 16:09:09 +01003649 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3650 srcDevice->getModuleVersionMajor() >= 3 &&
3651 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3652 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003653 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003654 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003655 // create patch between src device and output device
3656 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003657 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003658 audio_attributes_t resultAttr;
3659 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3660 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3661 config.sample_rate = sourceDesc->config().sample_rate;
3662 config.channel_mask = sourceDesc->config().channel_mask;
3663 config.format = sourceDesc->config().format;
3664 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3665 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffief579db52018-11-13 11:25:16 +01003666 bool isRequestedDeviceForExclusiveUse = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08003667 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputs;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003668 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
François Gaffief579db52018-11-13 11:25:16 +01003669 &attributes, &stream, sourceDesc->uid(), &config, &flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -08003670 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3671 &secondaryOutputs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003672 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003673 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003674 return INVALID_OPERATION;
3675 }
3676 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3677 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003678 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003679 return INVALID_OPERATION;
3680 }
Eric Laurent733ce942017-12-07 12:18:25 -08003681 status_t status = outputDesc->start();
3682 if (status != NO_ERROR) {
3683 return status;
3684 }
3685
Eric Laurentd60560a2015-04-10 11:31:20 -07003686 // create a special patch with no sink and two sources:
3687 // - the second source indicates to PatchPanel through which output mix this patch should
3688 // be connected as well as the stream type for volume control
3689 // - the sink is defined by whatever output device is currently selected for the output
3690 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003691 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003692 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003693 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003694 &afPatchHandle,
3695 0);
3696 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3697 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003698 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003699 if (status != NO_ERROR) {
3700 ALOGW("%s patch panel could not connect device patch, error %d",
3701 __FUNCTION__, status);
3702 return INVALID_OPERATION;
3703 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003704
3705 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3706 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3707 return INVALID_OPERATION;
3708 }
3709 outputDesc->addClient(sourceDesc);
3710
Eric Laurentd60560a2015-04-10 11:31:20 -07003711 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003712 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003713
3714 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003715 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003716 return status;
3717 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003718 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003719 if (delayMs != 0) {
3720 usleep(delayMs * 1000);
3721 }
3722 }
3723
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003724 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3725 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003726
3727 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003728}
3729
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003730status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003731{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003732 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3733 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003734 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003735 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003736 return BAD_VALUE;
3737 }
3738 status_t status = disconnectAudioSource(sourceDesc);
3739
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003740 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003741 return status;
3742}
3743
Andy Hung2ddee192015-12-18 17:34:44 -08003744status_t AudioPolicyManager::setMasterMono(bool mono)
3745{
3746 if (mMasterMono == mono) {
3747 return NO_ERROR;
3748 }
3749 mMasterMono = mono;
3750 // if enabling mono we close all offloaded devices, which will invalidate the
3751 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3752 // for recreating the new AudioTrack as non-offloaded PCM.
3753 //
3754 // If disabling mono, we leave all tracks as is: we don't know which clients
3755 // and tracks are able to be recreated as offloaded. The next "song" should
3756 // play back offloaded.
3757 if (mMasterMono) {
3758 Vector<audio_io_handle_t> offloaded;
3759 for (size_t i = 0; i < mOutputs.size(); ++i) {
3760 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3761 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3762 offloaded.push(desc->mIoHandle);
3763 }
3764 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003765 for (const auto& handle : offloaded) {
3766 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003767 }
3768 }
3769 // update master mono for all remaining outputs
3770 for (size_t i = 0; i < mOutputs.size(); ++i) {
3771 updateMono(mOutputs.keyAt(i));
3772 }
3773 return NO_ERROR;
3774}
3775
3776status_t AudioPolicyManager::getMasterMono(bool *mono)
3777{
3778 *mono = mMasterMono;
3779 return NO_ERROR;
3780}
3781
Eric Laurentac9cef52017-06-09 15:46:26 -07003782float AudioPolicyManager::getStreamVolumeDB(
3783 audio_stream_type_t stream, int index, audio_devices_t device)
3784{
3785 return computeVolume(stream, index, device);
3786}
3787
jiabin81772902018-04-02 17:52:27 -07003788status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3789 audio_format_t *surroundFormats,
3790 bool *surroundFormatsEnabled,
3791 bool reported)
3792{
3793 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3794 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3795 return BAD_VALUE;
3796 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003797 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3798 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003799
3800 size_t formatsWritten = 0;
3801 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003802 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003803 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003804 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003805 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003806 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3807 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3808 FormatVector supportedFormats =
3809 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3810 for (size_t j = 0; j < supportedFormats.size(); j++) {
3811 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3812 formats.insert(supportedFormats[j]);
3813 } else {
3814 for (const auto& pair : mConfig.getSurroundFormats()) {
3815 if (pair.second.count(supportedFormats[j]) != 0) {
3816 formats.insert(pair.first);
3817 break;
3818 }
3819 }
3820 }
3821 }
jiabin81772902018-04-02 17:52:27 -07003822 }
3823 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003824 for (const auto& pair : mConfig.getSurroundFormats()) {
3825 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003826 }
3827 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003828 *numSurroundFormats = formats.size();
3829 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3830 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003831 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003832 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003833 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003834 bool formatEnabled = true;
3835 switch (forceUse) {
3836 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3837 formatEnabled = mManualSurroundFormats.count(format) != 0;
3838 break;
3839 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3840 formatEnabled = false;
3841 break;
3842 default: // AUTO or ALWAYS => true
3843 break;
jiabin81772902018-04-02 17:52:27 -07003844 }
3845 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3846 }
jiabin81772902018-04-02 17:52:27 -07003847 }
3848 return NO_ERROR;
3849}
3850
3851status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3852{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003853 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003854 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3855 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003856 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003857 return BAD_VALUE;
3858 }
3859
Mikhail Naganov100f0122018-11-29 11:22:16 -08003860 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3861 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003862 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003863 return INVALID_OPERATION;
3864 }
3865
Mikhail Naganov100f0122018-11-29 11:22:16 -08003866 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003867 return NO_ERROR;
3868 }
3869
Mikhail Naganov100f0122018-11-29 11:22:16 -08003870 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003871 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003872 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003873 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003874 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003875 }
3876 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003877 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003878 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003879 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003880 }
3881 }
3882
3883 sp<SwAudioOutputDescriptor> outputDesc;
3884 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003885 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003886 AUDIO_DEVICE_OUT_HDMI);
3887 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3888 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003889 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003890 String8 name = hdmiOutputDevices[i]->getName();
3891 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3892 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
3897 continue;
3898 }
3899 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3900 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3901 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003902 name.c_str(),
3903 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003904 profileUpdated |= (status == NO_ERROR);
3905 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003906 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003907 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003908 AUDIO_DEVICE_IN_HDMI);
3909 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3910 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003911 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003912 String8 name = hdmiInputDevices[i]->getName();
3913 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3914 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3915 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003916 name.c_str(),
3917 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003918 if (status != NO_ERROR) {
3919 continue;
3920 }
3921 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3922 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3923 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003924 name.c_str(),
3925 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003926 profileUpdated |= (status == NO_ERROR);
3927 }
3928
jiabin81772902018-04-02 17:52:27 -07003929 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003930 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003931 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003932 }
3933
3934 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3935}
3936
Eric Laurentf32108e2018-10-04 17:22:04 -07003937void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003938{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003939 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003940
Eric Laurenta9f86652018-11-28 17:23:11 -08003941 for (size_t i = 0; i < mInputs.size(); i++) {
3942 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3943 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003944 for (const auto& client : clients) {
3945 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003946 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003947 }
3948 }
3949 }
3950}
3951
jiabin6012f912018-11-02 17:06:30 -07003952bool AudioPolicyManager::isHapticPlaybackSupported()
3953{
3954 for (const auto& hwModule : mHwModules) {
3955 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3956 for (const auto &outProfile : outputProfiles) {
3957 struct audio_port audioPort;
3958 outProfile->toAudioPort(&audioPort);
3959 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3960 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3961 return true;
3962 }
3963 }
3964 }
3965 }
3966 return false;
3967}
3968
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003969status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003970{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003971 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003972
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003973 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003974 if (patchDesc == 0) {
3975 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003976 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003977 return BAD_VALUE;
3978 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003979 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003980
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003981 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003982 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003983 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003984 if (status == NO_ERROR) {
3985 swOutputDesc->stop();
3986 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003987 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3988 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003989 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003990 if (hwOutputDesc != 0) {
3991 // release patch between src device and output device
3992 // close Hwoutput and remove from mHwOutputs
3993 } else {
3994 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3995 }
3996 }
3997 return NO_ERROR;
3998}
3999
François Gaffiec005e562018-11-06 15:04:49 +01004000sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4001 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004002{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004003 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004004 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004005 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004006 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004007 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4008 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004009 source = sourceDesc;
4010 break;
4011 }
4012 }
4013 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004014}
4015
Eric Laurente552edb2014-03-10 17:42:56 -07004016// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004017// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004018// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004019uint32_t AudioPolicyManager::nextAudioPortGeneration()
4020{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004021 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004022}
4023
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004024// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
4025static const char *kConfigLocationList[] =
4026 {"/odm/etc", "/vendor/etc", "/system/etc"};
4027static const int kConfigLocationListSize =
4028 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
4029
4030static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4031 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004032 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004033 status_t ret;
4034
Petri Gyntherf497f292018-04-17 18:46:10 -07004035 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
4036 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4037 // A2DP offload supported but disabled: try to use special XML file
4038 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4039 }
4040 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4041
4042 for (const char* fileName : fileNames) {
4043 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004044 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4045 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004046 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004047 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004048 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004049 return ret;
4050 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004051 }
4052 }
4053 return ret;
4054}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004055
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004056AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4057 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004058 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004059 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004060 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004061 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004062 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004063 mVolumeCurves(new VolumeCurvesCollection()),
4064 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004065 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004066 mAudioPortGeneration(1),
4067 mBeaconMuteRefCount(0),
4068 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004069 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004070 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004071 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004072 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004073{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004074}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004075
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004076AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4077 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4078{
4079 loadConfig();
4080 initialize();
4081}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004082
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004083// This check is to catch any legacy platform updating to Q without having
4084// switched to XML since its deprecation on O.
4085// TODO: after Q release, remove this check and flag as XML is now the only
4086// option and all legacy platform should have transitioned to XML.
4087#ifndef USE_XML_AUDIO_POLICY_CONF
4088#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004089#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004090
4091void AudioPolicyManager::loadConfig() {
4092 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004093 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004094 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004095 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004096}
4097
4098status_t AudioPolicyManager::initialize() {
4099 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004100
4101 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004102 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4103 if (!engineInstance) {
4104 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004105 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004106 }
4107 // Retrieve the Policy Manager Interface
4108 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4109 if (mEngine == NULL) {
4110 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004111 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004112 }
4113 mEngine->setObserver(this);
4114 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004115 if (status != NO_ERROR) {
4116 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4117 return status;
4118 }
François Gaffie2110e042015-03-24 08:41:51 +01004119
Eric Laurent3a4311c2014-03-17 12:00:47 -07004120 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004121 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004122 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004123 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004124 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4125 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004126 continue;
4127 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004128 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004129 // open all output streams needed to access attached devices
4130 // except for direct output streams that are only opened when they are actually
4131 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004132 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004133 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004134 if (!outProfile->canOpenNewIo()) {
4135 ALOGE("Invalid Output profile max open count %u for profile %s",
4136 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4137 continue;
4138 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004139 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004140 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 continue;
4142 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004143 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004144 mTtsOutputAvailable = true;
4145 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004147 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004148 continue;
4149 }
François Gaffie11d30102018-11-02 16:09:09 +01004150 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4151 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4152 sp<DeviceDescriptor> supportedDevice = 0;
4153 if (supportedDevices.contains(mDefaultOutputDevice)) {
4154 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004155 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004156 // choose first device present in profile's SupportedDevices also part of
4157 // mAvailableOutputDevices.
4158 if (availProfileDevices.isEmpty()) {
4159 continue;
4160 }
4161 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004162 }
François Gaffie11d30102018-11-02 16:09:09 +01004163 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004164 continue;
4165 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004166 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4167 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004168 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004169 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4170 AUDIO_STREAM_DEFAULT,
4171 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004172 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004173 ALOGW("Cannot open output stream for devices %s on hw module %s",
4174 supportedDevice->toString().c_str(), hwModule->getName());
4175 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004176 }
François Gaffie11d30102018-11-02 16:09:09 +01004177 for (const auto &device : availProfileDevices) {
4178 // give a valid ID to an attached device once confirmed it is reachable
4179 if (!device->isAttached()) {
4180 device->attach(hwModule);
4181 }
4182 }
4183 if (mPrimaryOutput == 0 &&
4184 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4185 mPrimaryOutput = outputDesc;
4186 }
4187 addOutput(output, outputDesc);
4188 setOutputDevices(outputDesc,
4189 DeviceVector(supportedDevice),
4190 true,
4191 0,
4192 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004193 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004194 // open input streams needed to access attached devices to validate
4195 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004196 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004197 if (!inProfile->canOpenNewIo()) {
4198 ALOGE("Invalid Input profile max open count %u for profile %s",
4199 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4200 continue;
4201 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004202 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004203 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004204 continue;
4205 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004206 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004207 // available input devices
4208 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4209 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4210 if (availProfileDevices.isEmpty()) {
4211 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004212 continue;
4213 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004214 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004215 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004216
Eric Laurentd78f1532014-09-16 16:38:20 -07004217 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004218 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004219 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004220 AUDIO_SOURCE_MIC,
4221 AUDIO_INPUT_FLAG_NONE,
4222 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004223 if (status != NO_ERROR) {
4224 ALOGW("Cannot open input stream for device %s on hw module %s",
4225 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004226 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004227 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004228 }
François Gaffie11d30102018-11-02 16:09:09 +01004229 for (const auto &device : availProfileDevices) {
4230 // give a valid ID to an attached device once confirmed it is reachable
4231 if (!device->isAttached()) {
4232 device->attach(hwModule);
4233 device->importAudioPort(inProfile, true);
4234 }
4235 }
4236 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004237 }
4238 }
4239 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004240 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004241 for (size_t i = 0; i < devices.size();) {
4242 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004243 if (!device->isAttached()) {
4244 ALOGW("device %s is unreachable", device->toString().c_str());
4245 devices.remove(device);
4246 continue;
4247 }
4248 // Device is now validated and can be appended to the available devices of the engine
4249 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004250 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004251 }
François Gaffie11d30102018-11-02 16:09:09 +01004252 };
4253 checkAndSetAvailable(mAvailableOutputDevices);
4254 checkAndSetAvailable(mAvailableInputDevices);
4255
Eric Laurent3a4311c2014-03-17 12:00:47 -07004256 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004257 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4258 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4259 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004260 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004261 }
jiabin9ff780e2018-03-19 18:19:52 -07004262 // If microphones address is empty, set it according to device type
4263 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004264 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004265 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004266 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004267 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004268 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004269 }
4270 }
4271 }
Eric Laurente552edb2014-03-10 17:42:56 -07004272
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004273 if (mPrimaryOutput == 0) {
4274 ALOGE("Failed to open primary output");
4275 status = NO_INIT;
4276 }
Eric Laurente552edb2014-03-10 17:42:56 -07004277
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004278 // Silence ALOGV statements
4279 property_set("log.tag." LOG_TAG, "D");
4280
Eric Laurente552edb2014-03-10 17:42:56 -07004281 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004282 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004283}
4284
Eric Laurente0720872014-03-11 09:30:41 -07004285AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004286{
Eric Laurente552edb2014-03-10 17:42:56 -07004287 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004288 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004289 }
4290 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004291 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004292 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004293 mAvailableOutputDevices.clear();
4294 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004295 mOutputs.clear();
4296 mInputs.clear();
4297 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004298 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004299 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004300}
4301
Eric Laurente0720872014-03-11 09:30:41 -07004302status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004303{
Eric Laurent87ffa392015-05-22 10:32:38 -07004304 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004305}
4306
Eric Laurente552edb2014-03-10 17:42:56 -07004307// ---
4308
Eric Laurent98e38192018-02-15 18:31:53 -08004309void AudioPolicyManager::addOutput(audio_io_handle_t output,
4310 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004311{
Eric Laurent1c333e22014-05-20 10:48:17 -07004312 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004313 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004314 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004315 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004316 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004317}
4318
François Gaffie53615e22015-03-19 09:24:12 +01004319void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4320{
4321 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004322 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004323}
4324
Eric Laurent98e38192018-02-15 18:31:53 -08004325void AudioPolicyManager::addInput(audio_io_handle_t input,
4326 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004327{
Eric Laurent1c333e22014-05-20 10:48:17 -07004328 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004329 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004330}
Eric Laurente552edb2014-03-10 17:42:56 -07004331
François Gaffie11d30102018-11-02 16:09:09 +01004332status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004333 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004334 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004335{
François Gaffie11d30102018-11-02 16:09:09 +01004336 audio_devices_t deviceType = device->type();
4337 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004338 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004339
François Gaffie11d30102018-11-02 16:09:09 +01004340 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004341 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004342 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004343 }
Eric Laurente552edb2014-03-10 17:42:56 -07004344
Eric Laurent3b73df72014-03-11 09:06:29 -07004345 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004346 // first list already open outputs that can be routed to this device
4347 for (size_t i = 0; i < mOutputs.size(); i++) {
4348 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004349 if (!desc->isDuplicated() && desc->supportsDevice(device)
4350 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004351 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4352 mOutputs.keyAt(i), device->toString().c_str());
4353 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004354 }
4355 }
4356 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004357 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004358 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004359 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4360 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004361 if (profile->supportsDevice(device)) {
4362 profiles.add(profile);
4363 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4364 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004365 }
4366 }
4367 }
4368
Eric Laurent7b279bb2015-12-14 10:18:23 -08004369 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004370
Eric Laurente552edb2014-03-10 17:42:56 -07004371 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004372 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004373 return BAD_VALUE;
4374 }
4375
4376 // open outputs for matching profiles if needed. Direct outputs are also opened to
4377 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4378 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004379 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004380
4381 // nothing to do if one output is already opened for this profile
4382 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004383 for (j = 0; j < outputs.size(); j++) {
4384 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004385 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004386 // matching profile: save the sample rates, format and channel masks supported
4387 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004388 if (audio_device_is_digital(deviceType)) {
4389 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004390 }
Eric Laurente552edb2014-03-10 17:42:56 -07004391 break;
4392 }
4393 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004394 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004395 continue;
4396 }
4397
Eric Laurent3974e3b2017-12-07 17:58:43 -08004398 if (!profile->canOpenNewIo()) {
4399 ALOGW("Max Output number %u already opened for this profile %s",
4400 profile->maxOpenCount, profile->getTagName().c_str());
4401 continue;
4402 }
4403
Eric Laurent83efe1c2017-07-09 16:51:08 -07004404 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004405 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004406 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004407 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004408 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004409 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004410
Eric Laurentfe231122017-11-17 17:48:06 -08004411 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004412 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004413 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004414 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004415 mpClientInterface->setParameters(output, String8(param));
4416 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004417 }
François Gaffie11d30102018-11-02 16:09:09 +01004418 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004419 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004420 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004421 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004422 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004423 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004424 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004425 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004426 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4427 profile->pickAudioProfile(
4428 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004429 config.offload_info.sample_rate = config.sample_rate;
4430 config.offload_info.channel_mask = config.channel_mask;
4431 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004432
François Gaffie11d30102018-11-02 16:09:09 +01004433 status_t status = desc->open(&config, DeviceVector(device),
4434 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004435 AUDIO_OUTPUT_FLAG_NONE, &output);
4436 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004437 output = AUDIO_IO_HANDLE_NONE;
4438 }
Eric Laurentd4692962014-05-05 18:13:44 -07004439 }
4440
Eric Laurentcf2c0212014-07-25 16:20:43 -07004441 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004442 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004443 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004444 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004445 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4446 policyMix->setOutput(desc);
4447 desc->mPolicyMix = policyMix->getMix();
4448 } else {
4449 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004450 address.string());
4451 }
François Gaffie036e1e92015-03-19 10:16:24 +01004452
Eric Laurent87ffa392015-05-22 10:32:38 -07004453 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4454 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004455 // no duplicated output for direct outputs and
4456 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004457 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004458
Eric Laurentd4692962014-05-05 18:13:44 -07004459 //TODO: configure audio effect output stage here
4460
4461 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004462 sp<SwAudioOutputDescriptor> dupOutputDesc =
4463 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4464 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4465 &duplicatedOutput);
4466 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004467 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004468 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004469 } else {
4470 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004471 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004472 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004473 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004474 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004475 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004476 }
Eric Laurente552edb2014-03-10 17:42:56 -07004477 }
4478 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004479 } else {
4480 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004481 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004482 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004483 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004484 profiles.removeAt(profile_index);
4485 profile_index--;
4486 } else {
4487 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004488 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004489 if (audio_device_is_digital(deviceType)) {
4490 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004491 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004492
François Gaffie11d30102018-11-02 16:09:09 +01004493 if (device_distinguishes_on_address(deviceType)) {
4494 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4495 device->toString().c_str());
4496 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4497 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004498 }
Eric Laurente552edb2014-03-10 17:42:56 -07004499 ALOGV("checkOutputsForDevice(): adding output %d", output);
4500 }
4501 }
4502
4503 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004504 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004505 return BAD_VALUE;
4506 }
Eric Laurentd4692962014-05-05 18:13:44 -07004507 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004508 // check if one opened output is not needed any more after disconnecting one device
4509 for (size_t i = 0; i < mOutputs.size(); i++) {
4510 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004511 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004512 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004513 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4514 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004515 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004516 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004517 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4518 mOutputs.keyAt(i));
4519 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004520 }
Eric Laurente552edb2014-03-10 17:42:56 -07004521 }
4522 }
Eric Laurentd4692962014-05-05 18:13:44 -07004523 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004524 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004525 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4526 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004527 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004528 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004529 "clearing direct output profile %zu on module %s",
4530 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004531 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004532 }
4533 }
4534 }
4535 }
4536 return NO_ERROR;
4537}
4538
François Gaffie11d30102018-11-02 16:09:09 +01004539status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004540 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004541 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004542{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004543 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004544
François Gaffie11d30102018-11-02 16:09:09 +01004545 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004546 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004547 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004548 }
4549
Eric Laurentd4692962014-05-05 18:13:44 -07004550 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4551 // first list already open inputs that can be routed to this device
4552 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4553 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004554 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004555 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4556 inputs.add(mInputs.keyAt(input_index));
4557 }
4558 }
4559
4560 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004561 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004562 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004563 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004564 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004565 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004566 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004567
François Gaffie11d30102018-11-02 16:09:09 +01004568 if (profile->supportsDevice(device)) {
4569 profiles.add(profile);
4570 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4571 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004572 }
4573 }
4574 }
4575
4576 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004577 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004578 return BAD_VALUE;
4579 }
4580
4581 // open inputs for matching profiles if needed. Direct inputs are also opened to
4582 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4583 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4584
Eric Laurent1c333e22014-05-20 10:48:17 -07004585 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004586
Eric Laurentd4692962014-05-05 18:13:44 -07004587 // nothing to do if one input is already opened for this profile
4588 size_t input_index;
4589 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4590 desc = mInputs.valueAt(input_index);
4591 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004592 if (audio_device_is_digital(device->type())) {
4593 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004594 }
Eric Laurentd4692962014-05-05 18:13:44 -07004595 break;
4596 }
4597 }
4598 if (input_index != mInputs.size()) {
4599 continue;
4600 }
4601
Eric Laurent3974e3b2017-12-07 17:58:43 -08004602 if (!profile->canOpenNewIo()) {
4603 ALOGW("Max Input number %u already opened for this profile %s",
4604 profile->maxOpenCount, profile->getTagName().c_str());
4605 continue;
4606 }
4607
Eric Laurentfe231122017-11-17 17:48:06 -08004608 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004609 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004610 status_t status = desc->open(nullptr,
4611 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004612 AUDIO_SOURCE_MIC,
4613 AUDIO_INPUT_FLAG_NONE,
4614 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004615
Eric Laurentcf2c0212014-07-25 16:20:43 -07004616 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004617 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004618 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004619 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004620 mpClientInterface->setParameters(input, String8(param));
4621 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004622 }
François Gaffie11d30102018-11-02 16:09:09 +01004623 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004624 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004625 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004626 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004627 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004628 }
4629
4630 if (input != 0) {
4631 addInput(input, desc);
4632 }
4633 } // endif input != 0
4634
Eric Laurentcf2c0212014-07-25 16:20:43 -07004635 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004636 ALOGW("%s could not open input for device %s", __func__,
4637 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004638 profiles.removeAt(profile_index);
4639 profile_index--;
4640 } else {
4641 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004642 if (audio_device_is_digital(device->type())) {
4643 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004644 }
Eric Laurentd4692962014-05-05 18:13:44 -07004645 ALOGV("checkInputsForDevice(): adding input %d", input);
4646 }
4647 } // end scan profiles
4648
4649 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004650 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004651 return BAD_VALUE;
4652 }
4653 } else {
4654 // Disconnect
4655 // check if one opened input is not needed any more after disconnecting one device
4656 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4657 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004658 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004659 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4660 mInputs.keyAt(input_index));
4661 inputs.add(mInputs.keyAt(input_index));
4662 }
4663 }
4664 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004665 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004666 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004667 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004668 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004669 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004670 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004671 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4672 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004673 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004674 }
4675 }
4676 }
4677 } // end disconnect
4678
4679 return NO_ERROR;
4680}
4681
4682
Eric Laurente0720872014-03-11 09:30:41 -07004683void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004684{
4685 ALOGV("closeOutput(%d)", output);
4686
Eric Laurentc75307b2015-03-17 15:29:32 -07004687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004688 if (outputDesc == NULL) {
4689 ALOGW("closeOutput() unknown output %d", output);
4690 return;
4691 }
François Gaffie036e1e92015-03-19 10:16:24 +01004692 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004693
Eric Laurente552edb2014-03-10 17:42:56 -07004694 // look for duplicated outputs connected to the output being removed.
4695 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004696 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004697 if (dupOutputDesc->isDuplicated() &&
4698 (dupOutputDesc->mOutput1 == outputDesc ||
4699 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004700 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004701 if (dupOutputDesc->mOutput1 == outputDesc) {
4702 outputDesc2 = dupOutputDesc->mOutput2;
4703 } else {
4704 outputDesc2 = dupOutputDesc->mOutput1;
4705 }
4706 // As all active tracks on duplicated output will be deleted,
4707 // and as they were also referenced on the other output, the reference
4708 // count for their stream type must be adjusted accordingly on
4709 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004710 const bool wasActive = outputDesc2->isActive();
4711 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4712 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004713 }
Eric Laurent733ce942017-12-07 12:18:25 -08004714 // stop() will be a no op if the output is still active but is needed in case all
4715 // active streams refcounts where cleared above
4716 if (wasActive) {
4717 outputDesc2->stop();
4718 }
Eric Laurente552edb2014-03-10 17:42:56 -07004719 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4720 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4721
4722 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004723 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004724 }
4725 }
4726
Eric Laurent05b90f82014-08-27 15:32:29 -07004727 nextAudioPortGeneration();
4728
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004729 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004730 if (index >= 0) {
4731 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004732 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004733 mAudioPatches.removeItemsAt(index);
4734 mpClientInterface->onAudioPatchListUpdate();
4735 }
4736
Eric Laurentfe231122017-11-17 17:48:06 -08004737 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004738
François Gaffie53615e22015-03-19 09:24:12 +01004739 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004740 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004741
4742 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4743 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004744 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004745 bool directOutputOpen = false;
4746 for (size_t i = 0; i < mOutputs.size(); i++) {
4747 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4748 directOutputOpen = true;
4749 break;
4750 }
4751 }
4752 if (!directOutputOpen) {
4753 ALOGV("no direct outputs open, reset MSD patch");
4754 setMsdPatch();
4755 }
4756 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004757}
4758
4759void AudioPolicyManager::closeInput(audio_io_handle_t input)
4760{
4761 ALOGV("closeInput(%d)", input);
4762
4763 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4764 if (inputDesc == NULL) {
4765 ALOGW("closeInput() unknown input %d", input);
4766 return;
4767 }
4768
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004770
François Gaffie11d30102018-11-02 16:09:09 +01004771 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004772 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004773 if (index >= 0) {
4774 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004775 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004776 mAudioPatches.removeItemsAt(index);
4777 mpClientInterface->onAudioPatchListUpdate();
4778 }
4779
Eric Laurentfe231122017-11-17 17:48:06 -08004780 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004781 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004782
François Gaffie11d30102018-11-02 16:09:09 +01004783 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4784 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004785 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4786 SoundTrigger::setCaptureState(false);
4787 }
Eric Laurente552edb2014-03-10 17:42:56 -07004788}
4789
François Gaffie11d30102018-11-02 16:09:09 +01004790SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4791 const DeviceVector &devices,
4792 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004793{
4794 SortedVector<audio_io_handle_t> outputs;
4795
François Gaffie11d30102018-11-02 16:09:09 +01004796 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004797 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004798 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004799 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004800 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004801 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4802 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004803 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004804 outputs.add(openOutputs.keyAt(i));
4805 }
4806 }
4807 return outputs;
4808}
4809
Mikhail Naganov37977152018-07-11 15:54:44 -07004810void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4811{
4812 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4813 // output is suspended before any tracks are moved to it
4814 checkA2dpSuspend();
4815 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08004816 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004817 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004818 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004819 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004820 setMsdPatch();
4821 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004822}
4823
François Gaffiec005e562018-11-06 15:04:49 +01004824bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
4825 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07004826{
François Gaffiec005e562018-11-06 15:04:49 +01004827 return mEngine->getProductStrategyForAttributes(lAttr) ==
4828 mEngine->getProductStrategyForAttributes(rAttr);
4829}
4830
4831void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
4832{
4833 auto psId = mEngine->getProductStrategyForAttributes(attr);
4834
4835 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
4836 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01004837 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4838 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004839
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004840 // also take into account external policy-related changes: add all outputs which are
4841 // associated with policies in the "before" and "after" output vectors
François Gaffiec005e562018-11-06 15:04:49 +01004842 ALOGVV("%s(): policy related outputs", __func__);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004843 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004844 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004845 if (desc != 0 && desc->mPolicyMix != NULL) {
4846 srcOutputs.add(desc->mIoHandle);
4847 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4848 }
4849 }
4850 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004851 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004852 if (desc != 0 && desc->mPolicyMix != NULL) {
4853 dstOutputs.add(desc->mIoHandle);
4854 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4855 }
4856 }
4857
François Gaffiec005e562018-11-06 15:04:49 +01004858 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004859 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4860 // audio from invalidated tracks will be rendered when unmuting
4861 uint32_t maxLatency = 0;
4862 for (audio_io_handle_t srcOut : srcOutputs) {
4863 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4864 if (desc != 0 && maxLatency < desc->latency()) {
4865 maxLatency = desc->latency();
4866 }
4867 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004868 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01004869 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004870 std::to_string(srcOutputs[0]).c_str(),
4871 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004872 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004873 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004874 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
François Gaffiec005e562018-11-06 15:04:49 +01004875 if (desc != 0 && desc->isStrategyActive(psId)) {
4876 setStrategyMute(psId, true, desc);
4877 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01004878 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004879 }
François Gaffiec005e562018-11-06 15:04:49 +01004880 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07004881 if (source != 0){
4882 connectAudioSource(source);
4883 }
Eric Laurente552edb2014-03-10 17:42:56 -07004884 }
4885
François Gaffiec005e562018-11-06 15:04:49 +01004886 // Move effects associated to this stream from previous output to new output
4887 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07004888 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004889 }
François Gaffiec005e562018-11-06 15:04:49 +01004890 // Move tracks associated to this stream (and linked) from previous output to new output
4891 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
4892 mpClientInterface->invalidateStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004893 }
4894 }
4895}
4896
Eric Laurente0720872014-03-11 09:30:41 -07004897void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004898{
François Gaffiec005e562018-11-06 15:04:49 +01004899 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
4900 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
4901 checkOutputForAttributes(attributes);
4902 }
Eric Laurente552edb2014-03-10 17:42:56 -07004903}
4904
Kevin Rocard153f92d2018-12-18 18:33:28 -08004905void AudioPolicyManager::checkSecondaryOutputs() {
4906 std::set<audio_stream_type_t> streamsToInvalidate;
4907 for (size_t i = 0; i < mOutputs.size(); i++) {
4908 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
4909 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
4910 // FIXME code duplicated from getOutputForAttrInt
4911 sp<SwAudioOutputDescriptor> desc;
4912 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
4913 mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(), desc,
4914 &secondaryDescs);
4915 if (!std::equal(client->getSecondaryOutputs().begin(),
4916 client->getSecondaryOutputs().end(),
4917 secondaryDescs.begin(), secondaryDescs.end())) {
4918 streamsToInvalidate.insert(client->stream());
4919 }
4920 }
4921 }
4922 for (audio_stream_type_t stream : streamsToInvalidate) {
4923 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
4924 mpClientInterface->invalidateStream(stream);
4925 }
4926}
4927
Eric Laurente0720872014-03-11 09:30:41 -07004928void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004929{
François Gaffie53615e22015-03-19 09:24:12 +01004930 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004931 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004932 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004933 return;
4934 }
4935
Eric Laurent3a4311c2014-03-17 12:00:47 -07004936 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004937 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4938 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4939 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004940
4941 // if suspended, restore A2DP output if:
4942 // ((SCO device is NOT connected) ||
4943 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4944 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004945 //
Eric Laurentf732e072016-08-03 19:30:28 -07004946 // if not suspended, suspend A2DP output if:
4947 // (SCO device is connected) &&
4948 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4949 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004950 //
4951 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004952 if (!isScoConnected ||
4953 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4954 AUDIO_POLICY_FORCE_BT_SCO) &&
4955 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4956 AUDIO_POLICY_FORCE_BT_SCO) &&
4957 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004958 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004959
4960 mpClientInterface->restoreOutput(a2dpOutput);
4961 mA2dpSuspended = false;
4962 }
4963 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004964 if (isScoConnected &&
4965 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4966 AUDIO_POLICY_FORCE_BT_SCO) ||
4967 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4968 AUDIO_POLICY_FORCE_BT_SCO) ||
4969 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004970 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004971
4972 mpClientInterface->suspendOutput(a2dpOutput);
4973 mA2dpSuspended = true;
4974 }
4975 }
4976}
4977
François Gaffie11d30102018-11-02 16:09:09 +01004978DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4979 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004980{
François Gaffie11d30102018-11-02 16:09:09 +01004981 DeviceVector devices;
4982
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004983 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 if (index >= 0) {
4985 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4986 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004987 ALOGV("%s device %s forced by patch %d", __func__,
4988 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4989 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 }
4991 }
4992
Eric Laurent97ac8712018-07-27 18:59:02 -07004993 // Honor explicit routing requests only if no client using default routing is active on this
4994 // input: a specific app can not force routing for other apps by setting a preferred device.
4995 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004996 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01004997 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004998 if (device != nullptr) {
4999 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005000 }
5001
François Gaffiea807ef92018-11-05 10:44:33 +01005002 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5003 // of setForceUse / Default Bus device here
5004 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5005 if (device != nullptr) {
5006 return DeviceVector(device);
5007 }
5008
François Gaffiec005e562018-11-06 15:04:49 +01005009 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5010 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5011 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005012
François Gaffiec005e562018-11-06 15:04:49 +01005013 if ((hasVoiceStream(streams) &&
5014 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) ||
5015 (hasStream(streams, AUDIO_STREAM_ALARM) &&
5016 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5017 outputDesc->isStrategyActive(productStrategy)) {
5018 // Retrieval of devices for voice DL is done on primary output profile, cannot
5019 // check the route (would force modifying configuration file for this profile)
5020 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5021 break;
5022 }
Eric Laurente552edb2014-03-10 17:42:56 -07005023 }
François Gaffiec005e562018-11-06 15:04:49 +01005024 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005025 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005026}
5027
François Gaffie11d30102018-11-02 16:09:09 +01005028sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5029 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005030{
François Gaffie11d30102018-11-02 16:09:09 +01005031 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005032
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005033 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 if (index >= 0) {
5035 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5036 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005037 ALOGV("getNewInputDevice() device %s forced by patch %d",
5038 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5039 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 }
5041 }
5042
Eric Laurent97ac8712018-07-27 18:59:02 -07005043 // Honor explicit routing requests only if no client using default routing is active on this
5044 // input: a specific app can not force routing for other apps by setting a preferred device.
5045 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005046 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5047 if (device != nullptr) {
5048 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005049 }
5050
Eric Laurentdc95a252018-04-12 12:46:56 -07005051 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005052 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005053 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5054 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5055 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005056 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005057 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005058 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005059 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005060
Eric Laurente552edb2014-03-10 17:42:56 -07005061 return device;
5062}
5063
Eric Laurent794fde22016-03-11 09:50:45 -08005064bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5065 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005066 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005067}
5068
Eric Laurente0720872014-03-11 09:30:41 -07005069audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005070 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005071 // getOutputDevicesForStream's behavior for invalid streams.
5072 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5073 // device for music stream), but we want to return the empty set.
5074 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 return AUDIO_DEVICE_NONE;
5076 }
François Gaffie11d30102018-11-02 16:09:09 +01005077 DeviceVector activeDevices;
5078 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01005079 for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
5080 curStream = (audio_stream_type_t) (curStream + 1)) {
5081 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005082 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005083 }
François Gaffiec005e562018-11-06 15:04:49 +01005084 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005085 devices.merge(curDevices);
5086 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005087 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005088 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005089 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005090 }
5091 }
Eric Laurente552edb2014-03-10 17:42:56 -07005092 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005093
Eric Laurentb0688d62018-08-14 15:49:18 -07005094 // Favor devices selected on active streams if any to report correct device in case of
5095 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005096 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005097 devices = activeDevices;
5098 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005099 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5100 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005101 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5102 if (!speakerSafeDevices.isEmpty()) {
5103 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5104 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005105 }
François Gaffie11d30102018-11-02 16:09:09 +01005106 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005107}
5108
Eric Laurente0720872014-03-11 09:30:41 -07005109void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005110 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005111 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005112 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005113 updateDevicesAndOutputs();
5114 break;
5115 default:
5116 break;
5117 }
5118}
5119
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005120uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005121
5122 // skip beacon mute management if a dedicated TTS output is available
5123 if (mTtsOutputAvailable) {
5124 return 0;
5125 }
5126
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005127 switch(event) {
5128 case STARTING_OUTPUT:
5129 mBeaconMuteRefCount++;
5130 break;
5131 case STOPPING_OUTPUT:
5132 if (mBeaconMuteRefCount > 0) {
5133 mBeaconMuteRefCount--;
5134 }
5135 break;
5136 case STARTING_BEACON:
5137 mBeaconPlayingRefCount++;
5138 break;
5139 case STOPPING_BEACON:
5140 if (mBeaconPlayingRefCount > 0) {
5141 mBeaconPlayingRefCount--;
5142 }
5143 break;
5144 }
5145
5146 if (mBeaconMuteRefCount > 0) {
5147 // any playback causes beacon to be muted
5148 return setBeaconMute(true);
5149 } else {
5150 // no other playback: unmute when beacon starts playing, mute when it stops
5151 return setBeaconMute(mBeaconPlayingRefCount == 0);
5152 }
5153}
5154
5155uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5156 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5157 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5158 // keep track of muted state to avoid repeating mute/unmute operations
5159 if (mBeaconMuted != mute) {
5160 // mute/unmute AUDIO_STREAM_TTS on all outputs
5161 ALOGV("\t muting %d", mute);
5162 uint32_t maxLatency = 0;
5163 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005164 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005165 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005166 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005167 0 /*delay*/, AUDIO_DEVICE_NONE);
5168 const uint32_t latency = desc->latency() * 2;
5169 if (latency > maxLatency) {
5170 maxLatency = latency;
5171 }
5172 }
5173 mBeaconMuted = mute;
5174 return maxLatency;
5175 }
5176 return 0;
5177}
5178
Eric Laurente0720872014-03-11 09:30:41 -07005179void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005180{
François Gaffiec005e562018-11-06 15:04:49 +01005181 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005182 mPreviousOutputs = mOutputs;
5183}
5184
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005185uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005186 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005187 uint32_t delayMs)
5188{
5189 // mute/unmute strategies using an incompatible device combination
5190 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5191 // if unmuting, unmute only after the specified delay
5192 if (outputDesc->isDuplicated()) {
5193 return 0;
5194 }
5195
5196 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005197 DeviceVector devices = outputDesc->devices();
5198 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005199
François Gaffiec005e562018-11-06 15:04:49 +01005200 auto productStrategies = mEngine->getOrderedProductStrategies();
5201 for (const auto &productStrategy : productStrategies) {
5202 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5203 DeviceVector curDevices =
5204 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5205 curDevices = curDevices.filter(outputDesc->supportedDevices());
5206 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005207 bool doMute = false;
5208
François Gaffiec005e562018-11-06 15:04:49 +01005209 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005210 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005211 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5212 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005213 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005214 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005215 }
Eric Laurent99401132014-05-07 19:48:15 -07005216 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005217 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005218 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005219 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005220 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005221 continue;
5222 }
François Gaffiec005e562018-11-06 15:04:49 +01005223 ALOGVV("%s() %s (curDevice %s)", __func__,
5224 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5225 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5226 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005227 if (mute) {
5228 // FIXME: should not need to double latency if volume could be applied
5229 // immediately by the audioflinger mixer. We must account for the delay
5230 // between now and the next time the audioflinger thread for this output
5231 // will process a buffer (which corresponds to one buffer size,
5232 // usually 1/2 or 1/4 of the latency).
5233 if (muteWaitMs < desc->latency() * 2) {
5234 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005235 }
5236 }
5237 }
5238 }
5239 }
5240 }
5241
Eric Laurent99401132014-05-07 19:48:15 -07005242 // temporary mute output if device selection changes to avoid volume bursts due to
5243 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005244 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005245 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5246 // temporary mute duration is conservatively set to 4 times the reported latency
5247 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5248 if (muteWaitMs < tempMuteWaitMs) {
5249 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005250 }
Eric Laurentdc462862016-07-19 12:29:53 -07005251
François Gaffiec005e562018-11-06 15:04:49 +01005252 for (const auto &productStrategy : productStrategies) {
5253 if (outputDesc->isStrategyActive(productStrategy)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005254 // make sure that we do not start the temporary mute period too early in case of
5255 // delayed device change
François Gaffiec005e562018-11-06 15:04:49 +01005256 setStrategyMute(productStrategy, true, outputDesc, delayMs);
5257 setStrategyMute(productStrategy, false, outputDesc, delayMs + tempMuteDurationMs,
5258 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005259 }
5260 }
5261 }
5262
Eric Laurente552edb2014-03-10 17:42:56 -07005263 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5264 if (muteWaitMs > delayMs) {
5265 muteWaitMs -= delayMs;
5266 usleep(muteWaitMs * 1000);
5267 return muteWaitMs;
5268 }
5269 return 0;
5270}
5271
François Gaffie11d30102018-11-02 16:09:09 +01005272uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5273 const DeviceVector &devices,
5274 bool force,
5275 int delayMs,
5276 audio_patch_handle_t *patchHandle,
5277 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005278{
François Gaffie11d30102018-11-02 16:09:09 +01005279 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005280 uint32_t muteWaitMs;
5281
5282 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005283 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5284 nullptr /* patchHandle */, requiresMuteCheck);
5285 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5286 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005287 return muteWaitMs;
5288 }
Eric Laurente552edb2014-03-10 17:42:56 -07005289
5290 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005291 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005292
François Gaffie11d30102018-11-02 16:09:09 +01005293 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5294 // output profile
5295 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5296 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5297 return 0;
5298 }
Eric Laurente552edb2014-03-10 17:42:56 -07005299
François Gaffie11d30102018-11-02 16:09:09 +01005300 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005301
François Gaffie11d30102018-11-02 16:09:09 +01005302 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5303
5304 if (!filteredDevices.isEmpty()) {
5305 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005306 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005307
5308 // if the outputs are not materially active, there is no need to mute.
5309 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005310 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005311 } else {
5312 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5313 muteWaitMs = 0;
5314 }
Eric Laurente552edb2014-03-10 17:42:56 -07005315
5316 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005317 // the requested device is AUDIO_DEVICE_NONE
5318 // OR the requested device is the same as current device
5319 // AND force is not specified
5320 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005321 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005322 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005323 !force && outputDesc->getPatchHandle() != 0) {
5324 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5325 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005326 return muteWaitMs;
5327 }
5328
François Gaffie11d30102018-11-02 16:09:09 +01005329 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005330
Eric Laurente552edb2014-03-10 17:42:56 -07005331 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005332 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005333 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005334 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005335 PatchBuilder patchBuilder;
5336 patchBuilder.addSource(outputDesc);
5337 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5338 for (const auto &filteredDevice : filteredDevices) {
5339 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005340 }
5341
François Gaffie11d30102018-11-02 16:09:09 +01005342 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005343 }
Eric Laurente552edb2014-03-10 17:42:56 -07005344
5345 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005346 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005347
5348 return muteWaitMs;
5349}
5350
Eric Laurentc75307b2015-03-17 15:29:32 -07005351status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005352 int delayMs,
5353 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005354{
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 ssize_t index;
5356 if (patchHandle) {
5357 index = mAudioPatches.indexOfKey(*patchHandle);
5358 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005359 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005360 }
5361 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005362 return INVALID_OPERATION;
5363 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5365 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005366 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005367 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 removeAudioPatch(patchDesc->mHandle);
5369 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005370 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005371 return status;
5372}
5373
5374status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005375 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 bool force,
5377 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005378{
5379 status_t status = NO_ERROR;
5380
Eric Laurent1f2f2232014-06-02 12:01:23 -07005381 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005382 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5383 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005384
François Gaffie11d30102018-11-02 16:09:09 +01005385 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005386 PatchBuilder patchBuilder;
5387 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005388 // AUDIO_SOURCE_HOTWORD is for internal use only:
5389 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005390 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5391 auto result = usecase;
5392 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5393 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5394 }
5395 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005396 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005397 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005398 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005399 }
5400 }
5401 return status;
5402}
5403
Eric Laurent6a94d692014-05-20 11:18:06 -07005404status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5405 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005406{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005407 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 ssize_t index;
5409 if (patchHandle) {
5410 index = mAudioPatches.indexOfKey(*patchHandle);
5411 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005412 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 }
5414 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005415 return INVALID_OPERATION;
5416 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005417 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5418 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005419 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005420 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 removeAudioPatch(patchDesc->mHandle);
5422 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005423 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005424 return status;
5425}
5426
François Gaffie11d30102018-11-02 16:09:09 +01005427sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005428 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005429 audio_format_t& format,
5430 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005431 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005432{
5433 // Choose an input profile based on the requested capture parameters: select the first available
5434 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005435 //
5436 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5437 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005438
Glenn Kasten730b9262018-03-29 15:01:26 -07005439 sp<IOProfile> firstInexact;
5440 uint32_t updatedSamplingRate = 0;
5441 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5442 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005443 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005444 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005445 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005446 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005447 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005448 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005449 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005450 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005451 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005452 &channelMask /*updatedChannelMask*/,
5453 // FIXME ugly cast
5454 (audio_output_flags_t) flags,
5455 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005456 return profile;
5457 }
François Gaffie11d30102018-11-02 16:09:09 +01005458 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005459 samplingRate,
5460 &updatedSamplingRate,
5461 format,
5462 &updatedFormat,
5463 channelMask,
5464 &updatedChannelMask,
5465 // FIXME ugly cast
5466 (audio_output_flags_t) flags,
5467 false /*exactMatchRequiredForInputFlags*/)) {
5468 firstInexact = profile;
5469 }
5470
Eric Laurente552edb2014-03-10 17:42:56 -07005471 }
5472 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005473 if (firstInexact != nullptr) {
5474 samplingRate = updatedSamplingRate;
5475 format = updatedFormat;
5476 channelMask = updatedChannelMask;
5477 return firstInexact;
5478 }
Eric Laurente552edb2014-03-10 17:42:56 -07005479 return NULL;
5480}
5481
Eric Laurente0720872014-03-11 09:30:41 -07005482float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005483 int index,
5484 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005485{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005486 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005487
5488 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5489 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5490 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5491 // the ringtone volume
5492 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5493 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5494 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5495 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5496 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5497 }
5498
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005499 // in-call: always cap volume by voice volume + some low headroom
5500 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005501 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005502 switch (stream) {
5503 case AUDIO_STREAM_SYSTEM:
5504 case AUDIO_STREAM_RING:
5505 case AUDIO_STREAM_MUSIC:
5506 case AUDIO_STREAM_ALARM:
5507 case AUDIO_STREAM_NOTIFICATION:
5508 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5509 case AUDIO_STREAM_DTMF:
5510 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005511 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005512 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005513 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005514 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005515 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005516 if (volumeDB > maxVoiceVolDb) {
5517 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5518 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5519 volumeDB = maxVoiceVolDb;
5520 }
5521 } break;
5522 default:
5523 break;
5524 }
5525 }
5526
Eric Laurente552edb2014-03-10 17:42:56 -07005527 // if a headset is connected, apply the following rules to ring tones and notifications
5528 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005529 // - always attenuate notifications volume by 6dB
5530 // - attenuate ring tones volume by 6dB unless music is not playing and
5531 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005532 // - if music is playing, always limit the volume to current music volume,
5533 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurente552edb2014-03-10 17:42:56 -07005534 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5535 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5536 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005537 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005538 AUDIO_DEVICE_OUT_USB_HEADSET |
5539 AUDIO_DEVICE_OUT_HEARING_AID)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005540 ((stream == AUDIO_STREAM_ALARM || stream == AUDIO_STREAM_RING)
5541 || (stream == AUDIO_STREAM_NOTIFICATION)
Eric Laurent3b73df72014-03-11 09:06:29 -07005542 || (stream == AUDIO_STREAM_SYSTEM)
François Gaffiec005e562018-11-06 15:04:49 +01005543 || ((stream == AUDIO_STREAM_ENFORCED_AUDIBLE) &&
5544 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
5545 AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005546 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005547 // when the phone is ringing we must consider that music could have been paused just before
5548 // by the music application and behave as if music was active if the last music track was
5549 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005550 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005551 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005552 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
François Gaffiec005e562018-11-06 15:04:49 +01005553 audio_devices_t musicDevice =
5554 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
5555 nullptr, true /*fromCache*/).types();
Eric Laurentffbc80f2015-03-18 18:30:19 -07005556 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005557 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5558 musicDevice),
5559 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005560 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5561 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005562 if (volumeDB > minVolDB) {
5563 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005564 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005566 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5567 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5568 // on A2DP, also ensure notification volume is not too low compared to media when
5569 // intended to be played
5570 if ((volumeDB > -96.0f) &&
5571 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5572 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5573 stream, device,
5574 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5575 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5576 }
5577 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005578 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffiec005e562018-11-06 15:04:49 +01005579 (stream != AUDIO_STREAM_ALARM && stream != AUDIO_STREAM_RING)) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005580 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005581 }
5582 }
5583
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005584 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005585}
5586
Eric Laurent3839bc02018-07-10 18:33:34 -07005587int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5588 audio_stream_type_t srcStream,
5589 audio_stream_type_t dstStream)
5590{
5591 if (srcStream == dstStream) {
5592 return srcIndex;
5593 }
5594 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5595 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5596 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5597 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5598
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005599 // preserve mute request or correct range
5600 if (srcIndex < minSrc) {
5601 if (srcIndex == 0) {
5602 return 0;
5603 }
5604 srcIndex = minSrc;
5605 } else if (srcIndex > maxSrc) {
5606 srcIndex = maxSrc;
5607 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005608 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5609}
5610
Eric Laurente0720872014-03-11 09:30:41 -07005611status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005612 int index,
5613 const sp<AudioOutputDescriptor>& outputDesc,
5614 audio_devices_t device,
5615 int delayMs,
5616 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005617{
Eric Laurente552edb2014-03-10 17:42:56 -07005618 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005619 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005620 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005621 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005622 return NO_ERROR;
5623 }
François Gaffie2110e042015-03-24 08:41:51 +01005624 audio_policy_forced_cfg_t forceUseForComm =
5625 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005626 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005627 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5628 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005629 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005630 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005631 return INVALID_OPERATION;
5632 }
5633
Eric Laurentc75307b2015-03-17 15:29:32 -07005634 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005635 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005636 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005637
Eric Laurentffbc80f2015-03-18 18:30:19 -07005638 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005639 if (outputDesc->isFixedVolume(device) ||
5640 // Force VoIP volume to max for bluetooth SCO
5641 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5642 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005643 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005644 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005645
Eric Laurentffbc80f2015-03-18 18:30:19 -07005646 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005647
Eric Laurent3b73df72014-03-11 09:06:29 -07005648 if (stream == AUDIO_STREAM_VOICE_CALL ||
5649 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005650 float voiceVolume;
5651 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005652 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005653 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005654 } else {
5655 voiceVolume = 1.0;
5656 }
5657
Eric Laurent18fba842016-03-31 14:41:26 -07005658 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005659 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5660 mLastVoiceVolume = voiceVolume;
5661 }
5662 }
5663
5664 return NO_ERROR;
5665}
5666
Eric Laurentc75307b2015-03-17 15:29:32 -07005667void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5668 audio_devices_t device,
5669 int delayMs,
5670 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005671{
Eric Laurentc75307b2015-03-17 15:29:32 -07005672 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005673
Eric Laurent794fde22016-03-11 09:50:45 -08005674 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005675 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005676 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005677 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005678 device,
5679 delayMs,
5680 force);
5681 }
5682}
5683
François Gaffiec005e562018-11-06 15:04:49 +01005684void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
5685 bool on,
5686 const sp<AudioOutputDescriptor>& outputDesc,
5687 int delayMs,
5688 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005689{
François Gaffiec005e562018-11-06 15:04:49 +01005690 for (auto stream: mEngine->getStreamTypesForProductStrategy(strategy)) {
5691 ALOGVV("%s() stream %d, mute %d, output ID %d", __FUNCTION__, stream, on,
5692 outputDesc->getId());
5693 setStreamMute(stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005694 }
5695}
5696
Eric Laurente0720872014-03-11 09:30:41 -07005697void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005698 bool on,
5699 const sp<AudioOutputDescriptor>& outputDesc,
5700 int delayMs,
5701 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005702{
Eric Laurente552edb2014-03-10 17:42:56 -07005703 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005704 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005705 }
5706
Eric Laurentc75307b2015-03-17 15:29:32 -07005707 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5708 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005709
5710 if (on) {
5711 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005712 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005713 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005714 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005715 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005716 }
5717 }
5718 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5719 outputDesc->mMuteCount[stream]++;
5720 } else {
5721 if (outputDesc->mMuteCount[stream] == 0) {
5722 ALOGV("setStreamMute() unmuting non muted stream!");
5723 return;
5724 }
5725 if (--outputDesc->mMuteCount[stream] == 0) {
5726 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005727 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005728 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005729 device,
5730 delayMs);
5731 }
5732 }
5733}
5734
François Gaffie53615e22015-03-19 09:24:12 +01005735bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5736{
François Gaffiec005e562018-11-06 15:04:49 +01005737 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08005738 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5739 return true;
5740 }
5741
5742 // has known usage?
5743 switch (paa->usage) {
5744 case AUDIO_USAGE_UNKNOWN:
5745 case AUDIO_USAGE_MEDIA:
5746 case AUDIO_USAGE_VOICE_COMMUNICATION:
5747 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5748 case AUDIO_USAGE_ALARM:
5749 case AUDIO_USAGE_NOTIFICATION:
5750 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5751 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5752 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5753 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5754 case AUDIO_USAGE_NOTIFICATION_EVENT:
5755 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5756 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5757 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5758 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005759 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005760 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005761 break;
5762 default:
5763 return false;
5764 }
5765 return true;
5766}
5767
François Gaffie2110e042015-03-24 08:41:51 +01005768audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5769{
5770 return mEngine->getForceUse(usage);
5771}
5772
5773bool AudioPolicyManager::isInCall()
5774{
5775 return isStateInCall(mEngine->getPhoneState());
5776}
5777
5778bool AudioPolicyManager::isStateInCall(int state)
5779{
5780 return is_state_in_call(state);
5781}
5782
Eric Laurentd60560a2015-04-10 11:31:20 -07005783void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5784{
5785 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005786 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5787 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5788 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5789 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005790 }
5791 }
5792
5793 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5795 bool release = false;
5796 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5797 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5798 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5799 source->ext.device.type == deviceDesc->type()) {
5800 release = true;
5801 }
5802 }
5803 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5804 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5805 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5806 sink->ext.device.type == deviceDesc->type()) {
5807 release = true;
5808 }
5809 }
5810 if (release) {
5811 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5812 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5813 }
5814 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005815
5816 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005817}
5818
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005819void AudioPolicyManager::modifySurroundFormats(
5820 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005821 std::unordered_set<audio_format_t> enforcedSurround(
5822 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005823 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5824 for (const auto& pair : mConfig.getSurroundFormats()) {
5825 allSurround.insert(pair.first);
5826 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5827 }
Phil Burk09bc4612016-02-24 15:58:15 -08005828
5829 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5830 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005831 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005832 // This is the resulting set of formats depending on the surround mode:
5833 // 'all surround' = allSurround
5834 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5835 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5836 // 'manual surround' = mManualSurroundFormats
5837 // AUTO: formats v 'enforced surround'
5838 // ALWAYS: formats v 'all surround' v 'enforced surround'
5839 // NEVER: formats ^ 'non-surround'
5840 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005841
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005842 std::unordered_set<audio_format_t> formatSet;
5843 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5844 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005845 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005846 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005847 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005848 formatSet.insert(*formatIter);
5849 }
5850 }
5851 } else {
5852 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5853 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005854 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005855
jiabin81772902018-04-02 17:52:27 -07005856 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005857 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005858 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5859 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5860 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005861 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005862 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5863 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5864 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005865 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005866 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005867 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005868 for (const auto& format : formatSet) {
5869 formatsPtr->push(format);
5870 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005871}
5872
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005873void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005874 ChannelsVector &channelMasks = *channelMasksPtr;
5875 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5876 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5877
5878 // If NEVER, then remove support for channelMasks > stereo.
5879 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5880 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5881 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5882 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5883 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5884 channelMasks.removeAt(maskIndex);
5885 } else {
5886 maskIndex++;
5887 }
5888 }
jiabin81772902018-04-02 17:52:27 -07005889 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5890 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5891 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005892 bool supports5dot1 = false;
5893 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005894 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005895 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5896 supports5dot1 = true;
5897 break;
5898 }
5899 }
5900 // If not then add 5.1 support.
5901 if (!supports5dot1) {
5902 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005903 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005904 }
Phil Burk09bc4612016-02-24 15:58:15 -08005905 }
5906}
5907
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005908void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005909 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005910 AudioProfileVector &profiles)
5911{
5912 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005913 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005914
François Gaffie112b0af2015-11-19 16:13:25 +01005915 // Format MUST be checked first to update the list of AudioProfile
5916 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005917 reply = mpClientInterface->getParameters(
5918 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005919 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005920 AudioParameter repliedParameters(reply);
5921 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005922 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005923 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5924 return;
5925 }
Phil Burk09bc4612016-02-24 15:58:15 -08005926 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005927 if (device == AUDIO_DEVICE_OUT_HDMI
5928 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005929 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005930 }
Phil Burk09bc4612016-02-24 15:58:15 -08005931 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005932 }
François Gaffie112b0af2015-11-19 16:13:25 +01005933
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005934 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005935 ChannelsVector channelMasks;
5936 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005937 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005938 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005939
5940 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005941 reply = mpClientInterface->getParameters(
5942 ioHandle,
5943 requestedParameters.toString() + ";" +
5944 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005945 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005946 AudioParameter repliedParameters(reply);
5947 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005948 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005949 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005950 }
5951 }
5952 if (profiles.hasDynamicChannelsFor(format)) {
5953 reply = mpClientInterface->getParameters(ioHandle,
5954 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005955 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005956 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005957 AudioParameter repliedParameters(reply);
5958 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005959 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005960 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005961 if (device == AUDIO_DEVICE_OUT_HDMI
5962 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005963 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005964 }
François Gaffie112b0af2015-11-19 16:13:25 +01005965 }
5966 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005967 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005968 }
5969}
Eric Laurentd60560a2015-04-10 11:31:20 -07005970
Mikhail Naganovdc769682018-05-04 15:34:08 -07005971status_t AudioPolicyManager::installPatch(const char *caller,
5972 audio_patch_handle_t *patchHandle,
5973 AudioIODescriptorInterface *ioDescriptor,
5974 const struct audio_patch *patch,
5975 int delayMs)
5976{
5977 ssize_t index = mAudioPatches.indexOfKey(
5978 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5979 *patchHandle : ioDescriptor->getPatchHandle());
5980 sp<AudioPatch> patchDesc;
5981 status_t status = installPatch(
5982 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5983 if (status == NO_ERROR) {
5984 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5985 }
5986 return status;
5987}
5988
5989status_t AudioPolicyManager::installPatch(const char *caller,
5990 ssize_t index,
5991 audio_patch_handle_t *patchHandle,
5992 const struct audio_patch *patch,
5993 int delayMs,
5994 uid_t uid,
5995 sp<AudioPatch> *patchDescPtr)
5996{
5997 sp<AudioPatch> patchDesc;
5998 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5999 if (index >= 0) {
6000 patchDesc = mAudioPatches.valueAt(index);
6001 afPatchHandle = patchDesc->mAfPatchHandle;
6002 }
6003
6004 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6005 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6006 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6007 if (status == NO_ERROR) {
6008 if (index < 0) {
6009 patchDesc = new AudioPatch(patch, uid);
6010 addAudioPatch(patchDesc->mHandle, patchDesc);
6011 } else {
6012 patchDesc->mPatch = *patch;
6013 }
6014 patchDesc->mAfPatchHandle = afPatchHandle;
6015 if (patchHandle) {
6016 *patchHandle = patchDesc->mHandle;
6017 }
6018 nextAudioPortGeneration();
6019 mpClientInterface->onAudioPatchListUpdate();
6020 }
6021 if (patchDescPtr) *patchDescPtr = patchDesc;
6022 return status;
6023}
6024
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006025} // namespace android