blob: f343bec8338a62c2dc75da774fa2f655435d619d [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"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070034
François Gaffie2110e042015-03-24 08:41:51 +010035#include <AudioPolicyManagerInterface.h>
36#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070039#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080040#include <media/AudioPolicyHelper.h>
Mikhail Naganovdc769682018-05-04 15:34:08 -070041#include <media/PatchBuilder.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Eric Laurente552edb2014-03-10 17:42:56 -070085// ----------------------------------------------------------------------------
86// AudioPolicyInterface implementation
87// ----------------------------------------------------------------------------
88
Eric Laurente0720872014-03-11 09:30:41 -070089status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080090 audio_policy_dev_state_t state,
91 const char *device_address,
92 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070093{
jiabina7b43792018-02-15 16:04:46 -080094 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
95 nextAudioPortGeneration();
96 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080097}
98
François Gaffie44481e72016-04-20 07:49:57 +020099void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
100 audio_policy_dev_state_t state,
101 const String8 &device_address)
102{
103 AudioParameter param(device_address);
104 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700105 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200106 param.addInt(key, device);
107 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
108}
109
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800111 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800112 const char *device_address,
113 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114{
Paul McLeane743a472015-01-28 11:07:31 -0800115 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800116 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700117
118 // connect/disconnect only 1 device at a time
119 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
120
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<DeviceDescriptor> devDesc =
122 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800123
Eric Laurente552edb2014-03-10 17:42:56 -0700124 // handle output devices
125 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700126 SortedVector <audio_io_handle_t> outputs;
127
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
129
Eric Laurente552edb2014-03-10 17:42:56 -0700130 // save a copy of the opened output descriptors before any output is opened or closed
131 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
132 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700133 switch (state)
134 {
135 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800136 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700137 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700138 ALOGW("setDeviceConnectionState() device already connected: %x", device);
139 return INVALID_OPERATION;
140 }
141 ALOGV("setDeviceConnectionState() connecting device %x", device);
142
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 index = mAvailableOutputDevices.add(devDesc);
145 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100146 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700147 if (module == 0) {
148 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
149 device);
150 mAvailableOutputDevices.remove(devDesc);
151 return INVALID_OPERATION;
152 }
Paul McLeane743a472015-01-28 11:07:31 -0800153 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 } else {
155 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...)
160 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200164
165 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
166 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700167 return INVALID_OPERATION;
168 }
François Gaffie2110e042015-03-24 08:41:51 +0100169 // Propagate device availability to Engine
170 mEngine->setDeviceConnectionState(devDesc, state);
171
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700172 // outputs should never be empty here
173 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
174 "checkOutputsForDevice() returned no outputs but status OK");
175 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
176 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) {
Eric Laurente552edb2014-03-10 17:42:56 -0700182 ALOGW("setDeviceConnectionState() device not connected: %x", device);
183 return INVALID_OPERATION;
184 }
185
Paul McLean5c477aa2014-08-20 16:47:57 -0700186 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200189 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
Eric Laurenta1d525f2015-01-29 13:36:45 -0800194 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100195
196 // Propagate device availability to Engine
197 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700198 } break;
199
200 default:
201 ALOGE("setDeviceConnectionState() invalid state: %x", state);
202 return BAD_VALUE;
203 }
204
Mikhail Naganov37977152018-07-11 15:54:44 -0700205 checkForDeviceAndOutputChanges([&]() {
206 // outputs must be closed after checkOutputForAllStrategies() is executed
207 if (!outputs.isEmpty()) {
208 for (audio_io_handle_t output : outputs) {
209 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
210 // close unused outputs after device disconnection or direct outputs that have been
211 // opened by checkOutputsForDevice() to query dynamic parameters
212 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
213 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
214 (desc->mDirectOpenCount == 0))) {
215 closeOutput(output);
216 }
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700218 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
219 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 return false;
222 });
Eric Laurente552edb2014-03-10 17:42:56 -0700223
Eric Laurent87ffa392015-05-22 10:32:38 -0700224 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700225 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
226 updateCallRouting(newDevice);
227 }
Eric Laurente552edb2014-03-10 17:42:56 -0700228 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
230 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
231 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // do not force device change on duplicated output because if device is 0, it will
233 // also force a device 0 for the two outputs it is duplicated to which may override
234 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700235 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100236 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700237 // always force when disconnecting (a non-duplicated device)
238 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700239 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700240 }
Eric Laurente552edb2014-03-10 17:42:56 -0700241 }
242
Eric Laurentd60560a2015-04-10 11:31:20 -0700243 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
244 cleanUpForDevice(devDesc);
245 }
246
Eric Laurent72aa32f2014-05-30 18:51:48 -0700247 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700248 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700249 } // end if is output device
250
Eric Laurente552edb2014-03-10 17:42:56 -0700251 // handle input devices
252 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700253 SortedVector <audio_io_handle_t> inputs;
254
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700256 switch (state)
257 {
258 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700259 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700260 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700261 ALOGW("setDeviceConnectionState() device already connected: %d", device);
262 return INVALID_OPERATION;
263 }
François Gaffie53615e22015-03-19 09:24:12 +0100264 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700265 if (module == NULL) {
266 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
267 device);
268 return INVALID_OPERATION;
269 }
François Gaffie44481e72016-04-20 07:49:57 +0200270
271 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
272 // parameters on newly connected devices (instead of opening the inputs...)
273 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
274
Paul McLean9080a4c2015-06-18 08:24:02 -0700275 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200276 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
277 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700278 return INVALID_OPERATION;
279 }
280
Eric Laurent3a4311c2014-03-17 12:00:47 -0700281 index = mAvailableInputDevices.add(devDesc);
282 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800283 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700284 } else {
285 return NO_MEMORY;
286 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800287
François Gaffie2110e042015-03-24 08:41:51 +0100288 // Propagate device availability to Engine
289 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700291
292 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700293 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700294 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700295 ALOGW("setDeviceConnectionState() device not connected: %d", device);
296 return INVALID_OPERATION;
297 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
299 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
300
301 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200302 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700303
Paul McLean9080a4c2015-06-18 08:24:02 -0700304 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700305 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700306
François Gaffie2110e042015-03-24 08:41:51 +0100307 // Propagate device availability to Engine
308 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700309 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700310
311 default:
312 ALOGE("setDeviceConnectionState() invalid state: %x", state);
313 return BAD_VALUE;
314 }
315
Eric Laurentd4692962014-05-05 18:13:44 -0700316 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700317 // As the input device list can impact the output device selection, update
318 // getDeviceForStrategy() cache
319 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700320
Eric Laurent87ffa392015-05-22 10:32:38 -0700321 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
323 updateCallRouting(newDevice);
324 }
325
Eric Laurentd60560a2015-04-10 11:31:20 -0700326 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
327 cleanUpForDevice(devDesc);
328 }
329
Eric Laurentb52c1522014-05-20 11:27:36 -0700330 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700331 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700332 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700333
334 ALOGW("setDeviceConnectionState() invalid device: %x", device);
335 return BAD_VALUE;
336}
337
Eric Laurente0720872014-03-11 09:30:41 -0700338audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100339 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700340{
Eric Laurent634b7142016-04-20 13:48:02 -0700341 sp<DeviceDescriptor> devDesc =
342 mHwModules.getDeviceDescriptor(device, device_address, "",
343 (strlen(device_address) != 0)/*matchAddress*/);
344
345 if (devDesc == 0) {
346 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
347 device, device_address);
348 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
349 }
François Gaffie53615e22015-03-19 09:24:12 +0100350
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 DeviceVector *deviceVector;
352
Eric Laurente552edb2014-03-10 17:42:56 -0700353 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 deviceVector = &mAvailableInputDevices;
357 } else {
358 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
359 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 }
Eric Laurent634b7142016-04-20 13:48:02 -0700361
362 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
363 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800364}
365
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800366status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
367 const char *device_address,
368 const char *device_name)
369{
370 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700371 String8 reply;
372 AudioParameter param;
373 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374
375 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
376 device, device_address, device_name);
377
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800378 // connect/disconnect only 1 device at a time
379 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
380
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381 // Check if the device is currently connected
382 sp<DeviceDescriptor> devDesc =
383 mHwModules.getDeviceDescriptor(device, device_address, device_name);
384 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
385 if (index < 0) {
386 // Nothing to do: device is not connected
387 return NO_ERROR;
388 }
389
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700390 // For offloaded A2DP, Hw modules may have the capability to
391 // configure codecs. Check if any of the loaded hw modules
392 // supports this.
393 // If supported, send a set parameter to configure A2DP codecs
394 // and return. No need to toggle device state.
395 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
396 reply = mpClientInterface->getParameters(
397 AUDIO_IO_HANDLE_NONE,
398 String8(AudioParameter::keyReconfigA2dpSupported));
399 AudioParameter repliedParameters(reply);
400 repliedParameters.getInt(
401 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
402 if (isReconfigA2dpSupported) {
403 const String8 key(AudioParameter::keyReconfigA2dp);
404 param.add(key, String8("true"));
405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406 return NO_ERROR;
407 }
408 }
409
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800410 // Toggle the device state: UNAVAILABLE -> AVAILABLE
411 // This will force reading again the device configuration
412 status = setDeviceConnectionState(device,
413 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
414 device_address, device_name);
415 if (status != NO_ERROR) {
416 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
417 status);
418 return status;
419 }
420
421 status = setDeviceConnectionState(device,
422 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
423 device_address, device_name);
424 if (status != NO_ERROR) {
425 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
426 status);
427 return status;
428 }
429
430 return NO_ERROR;
431}
432
Eric Laurentdc462862016-07-19 12:29:53 -0700433uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434{
435 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700436 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437
Andy Hunga76c7de2016-12-13 19:14:31 -0800438 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700439 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700440 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800441 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
443
444 // release existing RX patch if any
445 if (mCallRxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
447 mCallRxPatch.clear();
448 }
449 // release TX patch if any
450 if (mCallTxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
452 mCallTxPatch.clear();
453 }
454
455 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
456 // via setOutputDevice() on primary output.
457 // Otherwise, create two audio patches for TX and RX path.
458 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700459 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 // If the TX device is also on the primary HW module, setOutputDevice() will take care
461 // of it due to legacy implementation. If not, create a patch.
462 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
463 == AUDIO_DEVICE_NONE) {
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 createTxPatch = true;
469 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700470 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
472 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 return muteWaitMs;
475}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700476
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
478 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700479 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 sp<DeviceDescriptor> txSourceDeviceDesc;
482 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700483 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
484 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800485 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700486 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
487 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 }
489
490 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
491 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
492 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
493 // request to reuse existing output stream if one is already opened to reach the target device
494 if (output != AUDIO_IO_HANDLE_NONE) {
495 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
496 ALOG_ASSERT(!outputDesc->isDuplicated(),
497 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800499 }
500
501 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700502 // terminate active capture if on the same HW module as the call TX source device
503 // FIXME: would be better to refine to only inputs whose profile connects to the
504 // call TX device but this information is not in the audio patch and logic here must be
505 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800506 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800507 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8fc147b2018-07-22 19:13:55 -0700508 closeSessions(activeDesc, true /*activeOnly*/);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700509 }
510 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700511 }
Eric Laurentdc462862016-07-19 12:29:53 -0700512
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800513 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700514 status_t status = mpClientInterface->createAudioPatch(
515 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800516 ALOGW_IF(status != NO_ERROR,
517 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
518 sp<AudioPatch> audioPatch;
519 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700520 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800521 audioPatch->mAfPatchHandle = afPatchHandle;
522 audioPatch->mUid = mUidCached;
523 }
524 return audioPatch;
525}
526
Mikhail Naganovdc769682018-05-04 15:34:08 -0700527sp<DeviceDescriptor> AudioPolicyManager::findDevice(
528 const DeviceVector& devices, audio_devices_t device) {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700529 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800530 ALOG_ASSERT(!deviceList.isEmpty(),
531 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700532 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700533}
534
Eric Laurente0720872014-03-11 09:30:41 -0700535void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700536{
537 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100538 // store previous phone state for management of sonification strategy below
539 int oldState = mEngine->getPhoneState();
540
541 if (mEngine->setPhoneState(state) != NO_ERROR) {
542 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700543 return;
544 }
François Gaffie2110e042015-03-24 08:41:51 +0100545 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700546 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700547 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700548 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800549 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700550 }
551
François Gaffie2110e042015-03-24 08:41:51 +0100552 /**
553 * Switching to or from incall state or switching between telephony and VoIP lead to force
554 * routing command.
555 */
556 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
557 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700558
559 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700560 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700561
Eric Laurente552edb2014-03-10 17:42:56 -0700562 int delayMs = 0;
563 if (isStateInCall(state)) {
564 nsecs_t sysTime = systemTime();
565 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700566 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700567 // mute media and sonification strategies and delay device switch by the largest
568 // latency of any output where either strategy is active.
569 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100570 if ((isStrategyActive(desc, STRATEGY_MEDIA,
571 SONIFICATION_HEADSET_MUSIC_DELAY,
572 sysTime) ||
573 isStrategyActive(desc, STRATEGY_SONIFICATION,
574 SONIFICATION_HEADSET_MUSIC_DELAY,
575 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 (delayMs < (int)desc->latency()*2)) {
577 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700578 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 setStrategyMute(STRATEGY_MEDIA, true, desc);
580 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700581 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
583 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700584 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
585 }
586 }
587
Eric Laurent87ffa392015-05-22 10:32:38 -0700588 if (hasPrimaryOutput()) {
589 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
590 // the device returned is not necessarily reachable via this output
591 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
592 // force routing command to audio hardware when ending call
593 // even if no device change is needed
594 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
595 rxDevice = mPrimaryOutput->device();
596 }
Eric Laurente552edb2014-03-10 17:42:56 -0700597
Eric Laurent87ffa392015-05-22 10:32:38 -0700598 if (state == AUDIO_MODE_IN_CALL) {
599 updateCallRouting(rxDevice, delayMs);
600 } else if (oldState == AUDIO_MODE_IN_CALL) {
601 if (mCallRxPatch != 0) {
602 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
603 mCallRxPatch.clear();
604 }
605 if (mCallTxPatch != 0) {
606 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
607 mCallTxPatch.clear();
608 }
609 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
610 } else {
611 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700612 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700613 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700614
615 // reevaluate routing on all outputs in case tracks have been started during the call
616 for (size_t i = 0; i < mOutputs.size(); i++) {
617 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
618 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
619 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800620 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700621 }
622 }
623
Eric Laurente552edb2014-03-10 17:42:56 -0700624 if (isStateInCall(state)) {
625 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700626 // force reevaluating accessibility routing when call starts
627 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700628 }
629
630 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700631 if (state == AUDIO_MODE_RINGTONE &&
632 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700633 mLimitRingtoneVolume = true;
634 } else {
635 mLimitRingtoneVolume = false;
636 }
637}
638
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700639audio_mode_t AudioPolicyManager::getPhoneState() {
640 return mEngine->getPhoneState();
641}
642
Eric Laurente0720872014-03-11 09:30:41 -0700643void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700645{
François Gaffie2110e042015-03-24 08:41:51 +0100646 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700647 if (config == mEngine->getForceUse(usage)) {
648 return;
649 }
Eric Laurente552edb2014-03-10 17:42:56 -0700650
François Gaffie2110e042015-03-24 08:41:51 +0100651 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
652 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
653 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700654 }
François Gaffie2110e042015-03-24 08:41:51 +0100655 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
656 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
657 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700658
659 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700660 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800661
Eric Laurentdc462862016-07-19 12:29:53 -0700662 //FIXME: workaround for truncated touch sounds
663 // to be removed when the problem is handled by system UI
664 uint32_t delayMs = 0;
665 uint32_t waitMs = 0;
666 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
667 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
668 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700669 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700671 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700674 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
675 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
676 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700677 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
678 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700679 }
Eric Laurente552edb2014-03-10 17:42:56 -0700680 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700681 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700682 }
683 }
684
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800685 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700687 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800688 if (activeDesc->mProfile->getSupportedDevices().types() &
689 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
690 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700691 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800692 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700693 }
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
Eric Laurente552edb2014-03-10 17:42:56 -0700695}
696
Eric Laurente0720872014-03-11 09:30:41 -0700697void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700698{
699 ALOGV("setSystemProperty() property %s, value %s", property, value);
700}
701
702// Find a direct output profile compatible with the parameters passed, even if the input flags do
703// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800704sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700705 audio_devices_t device,
706 uint32_t samplingRate,
707 audio_format_t format,
708 audio_channel_mask_t channelMask,
709 audio_output_flags_t flags)
710{
Eric Laurent861a6282015-05-18 15:40:16 -0700711 // only retain flags that will drive the direct output profile selection
712 // if explicitly requested
713 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700714 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
715 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700716 flags =
717 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
718
719 sp<IOProfile> profile;
720
Mikhail Naganovd4120142017-12-06 15:49:22 -0800721 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800722 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700723 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700724 samplingRate, NULL /*updatedSamplingRate*/,
725 format, NULL /*updatedFormat*/,
726 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700727 flags)) {
728 continue;
729 }
730 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100731 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700732 continue;
733 }
734 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100735 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700736 continue;
737 }
738 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100739 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700740 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700741 }
Eric Laurente552edb2014-03-10 17:42:56 -0700742 }
743 }
Eric Laurent861a6282015-05-18 15:40:16 -0700744 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700745}
746
Eric Laurentf4e63452017-11-06 19:31:46 +0000747audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700748{
Eric Laurent3b73df72014-03-11 09:06:29 -0700749 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700750 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800751
752 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
753 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
754 // format, flags, etc. This may result in some discrepancy for functions that utilize
755 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
756 // and AudioSystem::getOutputSamplingRate().
757
Eric Laurentf4e63452017-11-06 19:31:46 +0000758 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
759 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700760
Eric Laurentf4e63452017-11-06 19:31:46 +0000761 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
762 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700763}
764
Eric Laurente83b55d2014-11-14 10:06:21 -0800765status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
766 audio_io_handle_t *output,
767 audio_session_t session,
768 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700769 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800770 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200771 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700772 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800773 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700774{
Eric Laurente83b55d2014-11-14 10:06:21 -0800775 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700776 DeviceVector outputDevices;
777 routing_strategy strategy;
778 audio_devices_t device;
779 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
780
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 if (attr != NULL) {
782 if (!isValidAttributes(attr)) {
783 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
784 attr->usage, attr->content_type, attr->flags,
785 attr->tags);
786 return BAD_VALUE;
787 }
788 attributes = *attr;
789 } else {
790 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
791 ALOGE("getOutputForAttr(): invalid stream type");
792 return BAD_VALUE;
793 }
794 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700795 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800796
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700797 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
798 " session %d selectedDeviceId %d",
799 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700800 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700801
Scott Randolph7b1fd232018-06-18 15:33:03 -0700802 // TODO: check for existing client for this port ID
803 if (*portId == AUDIO_PORT_HANDLE_NONE) {
804 *portId = AudioPort::getNextUniqueId();
805 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700806
Scott Randolph7b1fd232018-06-18 15:33:03 -0700807 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700808 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700809 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800810 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700811 } else {
812 // If no explict route, is there a matching dynamic policy that applies?
813 sp<SwAudioOutputDescriptor> desc;
814 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
815 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
816 if (!audio_has_proportional_frames(config->format)) {
817 return BAD_VALUE;
818 }
819 *stream = streamTypefromAttributesInt(&attributes);
820 *output = desc->mIoHandle;
821 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700822 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700823 }
824
825 // Virtual sources must always be dynamicaly or explicitly routed
826 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
827 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
828 return BAD_VALUE;
829 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700830 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700831
832 // Virtual sources must always be dynamicaly or explicitly routed
833 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
834 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
835 return BAD_VALUE;
836 }
837
838 *stream = streamTypefromAttributesInt(&attributes);
839
840 // TODO: Should this happen only if an explicit route is active?
841 // the previous code structure meant that this would always happen which
842 // would appear to result in adding a null deviceDesc when not using an
843 // explicit route. Is that the intended and necessary behavior?
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700844 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700845
Eric Laurent8fc147b2018-07-22 19:13:55 -0700846 strategy = (routing_strategy) getStrategyForAttr(&attributes);
847 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700848
Eric Laurente83b55d2014-11-14 10:06:21 -0800849 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200850 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700851 }
852
Nadav Barb2f18162018-07-18 13:01:53 +0300853 // Set incall music only if device was explicitly set, and fallback to the device which is
854 // chosen by the engine if not.
855 // FIXME: provide a more generic approach which is not device specific and move this back
856 // to getOutputForDevice.
857 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
858 *stream == AUDIO_STREAM_MUSIC &&
859 audio_is_linear_pcm(config->format) &&
860 isInCall()) {
861 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
862 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
863 } else {
864 device = mEngine->getDeviceForStrategy(strategy);
865 }
866 }
867
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800868 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
869 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200870 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700871
Andy Hungc88b0642018-04-27 15:42:35 -0700872 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800873 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700874 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800875 return INVALID_OPERATION;
876 }
Paul McLeanaa981192015-03-21 09:55:15 -0700877
Eric Laurent8fc147b2018-07-22 19:13:55 -0700878 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700879 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
880 : AUDIO_PORT_HANDLE_NONE;
881
Eric Laurent8fc147b2018-07-22 19:13:55 -0700882exit:
883 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
884 .format = config->format,
885 .channel_mask = config->channel_mask };
886 sp<TrackClientDescriptor> clientDesc =
887 new TrackClientDescriptor(*portId, uid, session,
888 attributes, clientConfig, requestedDeviceId, *stream, *flags);
889 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
890 outputDesc->clients().emplace(*portId, clientDesc);
891
892 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
893 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700894
Eric Laurente83b55d2014-11-14 10:06:21 -0800895 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700896}
897
898audio_io_handle_t AudioPolicyManager::getOutputForDevice(
899 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800900 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700901 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800902 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200903 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904{
Andy Hungc88b0642018-04-27 15:42:35 -0700905 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700906 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700907
Eric Laurente552edb2014-03-10 17:42:56 -0700908 // open a direct output if required by specified parameters
909 //force direct flag if offload flag is set: offloading implies a direct output stream
910 // and all common behaviors are driven by checking only the direct flag
911 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200912 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
913 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700914 }
Nadav Bar766fb022018-01-07 12:18:03 +0200915 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
916 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700917 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800918 // only allow deep buffering for music stream type
919 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200920 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700921 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200922 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700923 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
924 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200925 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800926 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700927 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200928 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700929 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800930 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200931 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700932 AUDIO_OUTPUT_FLAG_DIRECT);
933 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700934 }
Eric Laurente552edb2014-03-10 17:42:56 -0700935
Nadav Bar766fb022018-01-07 12:18:03 +0200936
Eric Laurentb732cf52014-09-24 19:08:21 -0700937 sp<IOProfile> profile;
938
939 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700940 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200941 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800942 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
943 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700944 goto non_direct_output;
945 }
946
Andy Hung2ddee192015-12-18 17:34:44 -0800947 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
948 // This prevents creating an offloaded track and tearing it down immediately after start
949 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700950 // FIXME: We should check the audio session here but we do not have it in this context.
951 // This may prevent offloading in rare situations where effects are left active by apps
952 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700953
Nadav Bar766fb022018-01-07 12:18:03 +0200954 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800955 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700956 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800957 config->sample_rate,
958 config->format,
959 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200960 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962
Eric Laurent1c333e22014-05-20 10:48:17 -0700963 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700964 // exclusive outputs for MMAP and Offload are enforced by different session ids.
965 for (size_t i = 0; i < mOutputs.size(); i++) {
966 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
967 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
968 // reuse direct output if currently open by the same client
969 // and configured with same parameters
970 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700971 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700972 (config->channel_mask == desc->mChannelMask) &&
973 (session == desc->mDirectClientSession)) {
974 desc->mDirectOpenCount++;
975 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
976 mOutputs.keyAt(i), session);
977 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700978 }
979 }
980 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800981
982 if (!profile->canOpenNewIo()) {
983 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
Eric Laurent861a6282015-05-18 15:40:16 -0700985
Eric Laurent3974e3b2017-12-07 17:58:43 -0800986 sp<SwAudioOutputDescriptor> outputDesc =
987 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800988
Mikhail Naganov708e0382018-05-30 09:53:04 -0700989 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800990 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
991 : String8("");
992
Nadav Bar766fb022018-01-07 12:18:03 +0200993 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700994
995 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700996 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800997 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700998 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800999 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1000 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1001 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1002 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1003 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001004 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001005 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001006 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001007 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001008 if (audio_is_linear_pcm(config->format) &&
1009 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001010 goto non_direct_output;
1011 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001012 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001013 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001014 outputDesc->mRefCount[stream] = 0;
1015 outputDesc->mStopTime[stream] = 0;
1016 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001017 outputDesc->mDirectClientSession = session;
1018
Eric Laurente552edb2014-03-10 17:42:56 -07001019 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001020 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001021 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001022 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001023 return output;
1024 }
1025
Eric Laurentb732cf52014-09-24 19:08:21 -07001026non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001027
1028 // A request for HW A/V sync cannot fallback to a mixed output because time
1029 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001030 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001031 return AUDIO_IO_HANDLE_NONE;
1032 }
1033
Eric Laurente552edb2014-03-10 17:42:56 -07001034 // ignoring channel mask due to downmix capability in mixer
1035
1036 // open a non direct output
1037
1038 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001039 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001040 // get which output is suitable for the specified stream. The actual
1041 // routing change will happen when startOutput() will be called
1042 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1043
Eric Laurent8838a382014-09-08 16:44:28 -07001044 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001045 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1046 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001047 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001048 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001049 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001050 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001051
Eric Laurente552edb2014-03-10 17:42:56 -07001052 return output;
1053}
1054
Eric Laurente0720872014-03-11 09:30:41 -07001055audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001056 audio_output_flags_t flags,
1057 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001058{
1059 // select one output among several that provide a path to a particular device or set of
1060 // devices (the list was previously build by getOutputsForDevice()).
1061 // The priority is as follows:
1062 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001063 // 2: the output with the bit depth the closest to the requested one
1064 // 3: the primary output
1065 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001066
1067 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001068 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001069 }
1070 if (outputs.size() == 1) {
1071 return outputs[0];
1072 }
1073
1074 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001075 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1076 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1077 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001078 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1079 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001080
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001081 for (audio_io_handle_t output : outputs) {
1082 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001083 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001084 // if a valid format is specified, skip output if not compatible
1085 if (format != AUDIO_FORMAT_INVALID) {
1086 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001087 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001088 continue;
1089 }
1090 } else if (!audio_is_linear_pcm(format)) {
1091 continue;
1092 }
Eric Laurente6930022016-02-11 10:20:40 -08001093 if (AudioPort::isBetterFormatMatch(
1094 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001095 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001096 bestFormat = outputDesc->mFormat;
1097 }
Eric Laurent8838a382014-09-08 16:44:28 -07001098 }
1099
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001100 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001101 if (commonFlags >= maxCommonFlags) {
1102 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001103 if (format != AUDIO_FORMAT_INVALID
1104 && AudioPort::isBetterFormatMatch(
1105 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001106 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001107 bestFormatForFlags = outputDesc->mFormat;
1108 }
1109 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001110 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001111 maxCommonFlags = commonFlags;
1112 bestFormatForFlags = outputDesc->mFormat;
1113 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001114 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001115 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001116 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001117 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001118 }
1119 }
1120 }
1121
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001122 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001123 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001124 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001125 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001126 return outputForFormat;
1127 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001128 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001129 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001130 }
1131
1132 return outputs[0];
1133}
1134
Eric Laurent8fc147b2018-07-22 19:13:55 -07001135status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001136{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001137 ALOGV("%s portId %d", __FUNCTION__, portId);
1138
1139 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1140 if (outputDesc == 0) {
1141 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001142 return BAD_VALUE;
1143 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001144 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1145 audio_stream_type_t stream = client->stream();
1146 audio_session_t session = client->session();
Eric Laurente552edb2014-03-10 17:42:56 -07001147
Eric Laurent8fc147b2018-07-22 19:13:55 -07001148 ALOGV("startOutput() output %d, stream %d, session %d",
1149 outputDesc->mIoHandle, stream, session);
Eric Laurentc75307b2015-03-17 15:29:32 -07001150
Eric Laurent733ce942017-12-07 12:18:25 -08001151 status_t status = outputDesc->start();
1152 if (status != NO_ERROR) {
1153 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001154 }
1155
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001156 // Routing?
1157 mOutputRoutes.incRouteActivity(session);
1158
Eric Laurentc75307b2015-03-17 15:29:32 -07001159 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001160 AudioMix *policyMix = NULL;
1161 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001162 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001163 policyMix = outputDesc->mPolicyMix;
1164 address = policyMix->mDeviceAddress.string();
1165 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1166 newDevice = policyMix->mDeviceType;
1167 } else {
1168 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1169 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001170 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001171 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001172 if (newDevice != outputDesc->device()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07001173 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001174 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001175 } else {
1176 newDevice = AUDIO_DEVICE_NONE;
1177 }
1178
1179 uint32_t delayMs = 0;
1180
Eric Laurent733ce942017-12-07 12:18:25 -08001181 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001182
1183 if (status != NO_ERROR) {
1184 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001185 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001186 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001187 }
1188 // Automatically enable the remote submix input when output is started on a re routing mix
1189 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001190 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1191 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001192 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1193 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001194 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001195 "remote-submix");
1196 }
1197
1198 if (delayMs != 0) {
1199 usleep(delayMs * 1000);
1200 }
1201
1202 return status;
1203}
1204
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001205status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001206 audio_stream_type_t stream,
1207 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001208 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001209 uint32_t *delayMs)
1210{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001211 // cannot start playback of STREAM_TTS if any other output is being used
1212 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001213
1214 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001215 if (stream == AUDIO_STREAM_TTS) {
1216 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001217 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001218 return INVALID_OPERATION;
1219 } else {
1220 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1221 }
1222 } else {
1223 // some playback other than beacon starts
1224 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1225 }
1226
Eric Laurent77305a62016-07-25 16:39:22 -07001227 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001228 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001229 bool force = !outputDesc->isActive() &&
1230 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001231
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001232 // requiresMuteCheck is false when we can bypass mute strategy.
1233 // It covers a common case when there is no materially active audio
1234 // and muting would result in unnecessary delay and dropped audio.
1235 const uint32_t outputLatencyMs = outputDesc->latency();
1236 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1237
Eric Laurente552edb2014-03-10 17:42:56 -07001238 // increment usage count for this stream on the requested output:
1239 // NOTE that the usage count is the same for duplicated output and hardware output which is
1240 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1241 outputDesc->changeRefCount(stream, 1);
1242
Eric Laurent36829f92017-04-07 19:04:42 -07001243 if (stream == AUDIO_STREAM_MUSIC) {
1244 selectOutputForMusicEffects();
1245 }
1246
Eric Laurent493404d2015-04-21 15:07:36 -07001247 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001248 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001249 if (device == AUDIO_DEVICE_NONE) {
1250 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001251 }
Eric Laurent36829f92017-04-07 19:04:42 -07001252
Eric Laurente552edb2014-03-10 17:42:56 -07001253 routing_strategy strategy = getStrategy(stream);
1254 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001255 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1256 (beaconMuteLatency > 0);
1257 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001258 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001259 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001260 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001261 // An output has a shared device if
1262 // - managed by the same hw module
1263 // - supports the currently selected device
1264 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1265 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1266
Eric Laurent77305a62016-07-25 16:39:22 -07001267 // force a device change if any other output is:
1268 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001269 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001270 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001271 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001272 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001273 // change the device currently selected by the other output.
1274 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001275 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001276 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001277 force = true;
1278 }
1279 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001280 // a notification so that audio focus effect can propagate, or that a mute/unmute
1281 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001282 const uint32_t latencyMs = desc->latency();
1283 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1284
1285 if (shouldWait && isActive && (waitMs < latencyMs)) {
1286 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001287 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001288
1289 // Require mute check if another output is on a shared device
1290 // and currently active to have proper drain and avoid pops.
1291 // Note restoring AudioTracks onto this output needs to invoke
1292 // a volume ramp if there is no mute.
1293 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
1295 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001296
1297 const uint32_t muteWaitMs =
1298 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001299
Eric Laurente552edb2014-03-10 17:42:56 -07001300 // apply volume rules for current stream and device if necessary
1301 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001302 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001303 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001304 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001305
1306 // update the outputs if starting an output with a stream that can affect notification
1307 // routing
1308 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001309
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001310 // force reevaluating accessibility routing when ringtone or alarm starts
1311 if (strategy == STRATEGY_SONIFICATION) {
1312 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1313 }
Eric Laurentdc462862016-07-19 12:29:53 -07001314
1315 if (waitMs > muteWaitMs) {
1316 *delayMs = waitMs - muteWaitMs;
1317 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001318
1319 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1320 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1321 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1322 // change occurs after the MixerThread starts and causes a stream volume
1323 // glitch.
1324 //
1325 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001326 }
Eric Laurentdc462862016-07-19 12:29:53 -07001327
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001328 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1329 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1330 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1331 }
1332
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001333 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1334 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1335 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1336 }
1337
Eric Laurente552edb2014-03-10 17:42:56 -07001338 return NO_ERROR;
1339}
1340
Eric Laurent8fc147b2018-07-22 19:13:55 -07001341status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001342{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001343 ALOGV("%s portId %d", __FUNCTION__, portId);
1344
1345 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1346 if (outputDesc == 0) {
1347 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001348 return BAD_VALUE;
1349 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001350 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1351 audio_stream_type_t stream = client->stream();
1352 audio_session_t session = client->session();
Eric Laurente552edb2014-03-10 17:42:56 -07001353
Eric Laurent8fc147b2018-07-22 19:13:55 -07001354 ALOGV("stopOutput() output %d, stream %d, session %d", outputDesc->mIoHandle, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001355
Eric Laurentc75307b2015-03-17 15:29:32 -07001356 if (outputDesc->mRefCount[stream] == 1) {
1357 // Automatically disable the remote submix input when output is stopped on a
1358 // re routing mix of type MIX_TYPE_RECORDERS
1359 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1360 outputDesc->mPolicyMix != NULL &&
1361 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1362 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1363 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001364 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001365 "remote-submix");
1366 }
1367 }
1368
1369 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001370 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001371 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 int activityCount = mOutputRoutes.decRouteActivity(session);
1373 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1374
1375 if (forceDeviceUpdate) {
1376 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1377 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001378 }
1379
Eric Laurent3974e3b2017-12-07 17:58:43 -08001380 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1381
Eric Laurent733ce942017-12-07 12:18:25 -08001382 if (status == NO_ERROR ) {
1383 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001384 }
1385 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001386}
1387
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001388status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001389 audio_stream_type_t stream,
1390 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001391{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001392 // always handle stream stop, check which stream type is stopping
1393 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1394
Eric Laurente552edb2014-03-10 17:42:56 -07001395 if (outputDesc->mRefCount[stream] > 0) {
1396 // decrement usage count of this stream on the output
1397 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001398
Eric Laurente552edb2014-03-10 17:42:56 -07001399 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001400 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001401 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001402 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001403 // delay the device switch by twice the latency because stopOutput() is executed when
1404 // the track stop() command is received and at that time the audio track buffer can
1405 // still contain data that needs to be drained. The latency only covers the audio HAL
1406 // and kernel buffers. Also the latency does not always include additional delay in the
1407 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001408 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001409
1410 // force restoring the device selection on other active outputs if it differs from the
1411 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001412 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001413 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001414 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001415 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001416 desc->isActive() &&
1417 outputDesc->sharesHwModuleWith(desc) &&
1418 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001419 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1420 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001421
Eric Laurentc75307b2015-03-17 15:29:32 -07001422 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001423 newDevice2,
1424 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001425 delayMs);
1426 // re-apply device specific volume if not done by setOutputDevice()
1427 if (!force) {
1428 applyStreamVolumes(desc, newDevice2, delayMs);
1429 }
Eric Laurente552edb2014-03-10 17:42:56 -07001430 }
1431 }
1432 // update the outputs if stopping one with a stream that can affect notification routing
1433 handleNotificationRoutingForStream(stream);
1434 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001435
1436 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1437 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1438 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1439 }
1440
Eric Laurent36829f92017-04-07 19:04:42 -07001441 if (stream == AUDIO_STREAM_MUSIC) {
1442 selectOutputForMusicEffects();
1443 }
Eric Laurente552edb2014-03-10 17:42:56 -07001444 return NO_ERROR;
1445 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001446 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001447 return INVALID_OPERATION;
1448 }
1449}
1450
Eric Laurent8fc147b2018-07-22 19:13:55 -07001451void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001452{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001453 ALOGV("%s portId %d", __FUNCTION__, portId);
1454
1455 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1456 if (outputDesc == 0) {
1457 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001458 return;
1459 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001460 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1461 audio_session_t session = client->session();
1462
1463 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001464
Paul McLeanaa981192015-03-21 09:55:15 -07001465 // Routing
1466 mOutputRoutes.removeRoute(session);
1467
Eric Laurent8fc147b2018-07-22 19:13:55 -07001468 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1469 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001470 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001471 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001472 return;
1473 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001474 if (--outputDesc->mDirectOpenCount == 0) {
1475 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001476 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001477 }
1478 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001479 outputDesc->clients().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001480}
1481
1482
Eric Laurentcaf7f482014-11-25 17:50:47 -08001483status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1484 audio_io_handle_t *input,
1485 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001486 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001487 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001488 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001489 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001490 input_type_t *inputType,
1491 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001492{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001493 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001494 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001495 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001496
Eric Laurentad2e7b92017-09-14 20:06:42 -07001497 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001498 // handle legacy remote submix case where the address was not always specified
1499 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001500 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001501 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001502 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001503 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001504 sp<AudioInputDescriptor> inputDesc;
1505 sp<RecordClientDescriptor> clientDesc;
1506 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001507
Eric Laurentfe231122017-11-17 17:48:06 -08001508 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1509 inputSource = AUDIO_SOURCE_MIC;
1510 }
1511
Paul McLean466dc8e2015-04-17 13:15:36 -06001512 // Explicit routing?
1513 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001514 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001515 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001516 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001517 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001518
Eric Laurentad2e7b92017-09-14 20:06:42 -07001519 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1520 // possible
1521 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1522 *input != AUDIO_IO_HANDLE_NONE) {
1523 ssize_t index = mInputs.indexOfKey(*input);
1524 if (index < 0) {
1525 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1526 status = BAD_VALUE;
1527 goto error;
1528 }
1529 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1530 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1531 if (audioSession == 0) {
1532 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1533 status = BAD_VALUE;
1534 goto error;
1535 }
1536 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1537 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001538 // corresponds to a new client and is only permitted from the same UID.
1539 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001540 if (audioSession->openCount() == 1) {
1541 audioSession->setUid(uid);
1542 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001543 if (!audioSession->isSilenced()) {
1544 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1545 uid, session, audioSession->uid());
1546 status = INVALID_OPERATION;
1547 goto error;
1548 }
1549 audioSession->setUid(uid);
1550 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001551 }
1552 audioSession->changeOpenCount(1);
1553 *inputType = API_INPUT_LEGACY;
1554 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1555 *portId = AudioPort::getNextUniqueId();
1556 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001557 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001558 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1559 : AUDIO_PORT_HANDLE_NONE;
1560 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1561
Eric Laurent8fc147b2018-07-22 19:13:55 -07001562 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001563 }
1564
1565 *input = AUDIO_IO_HANDLE_NONE;
1566 *inputType = API_INPUT_INVALID;
1567
Eric Laurentad2e7b92017-09-14 20:06:42 -07001568 halInputSource = inputSource;
1569
1570 // TODO: check for existing client for this port ID
1571 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1572 *portId = AudioPort::getNextUniqueId();
1573 }
1574
1575 audio_devices_t device;
1576
Eric Laurentc447ded2015-01-06 08:47:05 -08001577 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001578 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001579 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1580 if (status != NO_ERROR) {
1581 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001582 }
1583 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001584 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1585 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001586 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001587 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001588 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001589 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001590 status = BAD_VALUE;
1591 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001592 }
Eric Laurentc722f302014-12-10 11:21:49 -08001593 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001594 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001595 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1596 // there is an external policy, but this input is attached to a mix of recorders,
1597 // meaning it receives audio injected into the framework, so the recorder doesn't
1598 // know about it and is therefore considered "legacy"
1599 *inputType = API_INPUT_LEGACY;
1600 } else {
1601 // recording a mix of players defined by an external policy, we're rerouting for
1602 // an external policy
1603 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1604 }
Eric Laurentc722f302014-12-10 11:21:49 -08001605 } else if (audio_is_remote_submix_device(device)) {
1606 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001607 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001608 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1609 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001610 } else {
1611 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001612 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001613
Eric Laurent599c7582015-12-07 18:05:55 -08001614 }
1615
1616 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001617 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001618 policyMix);
1619 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001620 status = INVALID_OPERATION;
1621 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001622 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001623
Mikhail Naganov708e0382018-05-30 09:53:04 -07001624 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001625 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1626 : AUDIO_PORT_HANDLE_NONE;
1627
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628exit:
1629 clientDesc = new RecordClientDescriptor(*portId, uid, session,
1630 *attr, *config, requestedDeviceId, inputSource, flags);
1631 inputDesc = mInputs.valueFor(*input);
1632 inputDesc->clients().emplace(*portId, clientDesc);
1633
1634 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1635 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001636
Eric Laurent599c7582015-12-07 18:05:55 -08001637 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001638
1639error:
1640 mInputRoutes.removeRoute(session);
1641 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001642}
1643
1644
1645audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1646 String8 address,
1647 audio_session_t session,
1648 uid_t uid,
1649 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001650 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001651 audio_input_flags_t flags,
1652 AudioMix *policyMix)
1653{
1654 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1655 audio_source_t halInputSource = inputSource;
1656 bool isSoundTrigger = false;
1657
1658 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1659 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1660 if (index >= 0) {
1661 input = mSoundTriggerSessions.valueFor(session);
1662 isSoundTrigger = true;
1663 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1664 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1665 } else {
1666 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001667 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001668 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001669 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001670 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001671 }
1672
Andy Hungf129b032015-04-07 13:45:50 -07001673 // find a compatible input profile (not necessarily identical in parameters)
1674 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001675 // sampling rate and flags may be updated by getInputProfile
1676 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1677 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001678 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001679 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001680 audio_input_flags_t profileFlags = flags;
1681 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001682 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001683 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001684 profileSamplingRate, profileFormat, profileChannelMask,
1685 profileFlags);
1686 if (profile != 0) {
1687 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001688 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1689 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001690 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1691 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1692 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001693 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001694 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1695 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001696 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001697 }
Eric Laurente552edb2014-03-10 17:42:56 -07001698 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001699 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001700 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001701 if (samplingRate == 0) {
1702 samplingRate = profileSamplingRate;
1703 }
Eric Laurente552edb2014-03-10 17:42:56 -07001704
Eric Laurent322b4d22015-04-03 15:57:54 -07001705 if (profile->getModuleHandle() == 0) {
1706 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001707 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001708 }
1709
Eric Laurent599c7582015-12-07 18:05:55 -08001710 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001711 inputSource,
1712 config->format,
1713 samplingRate,
1714 config->channel_mask,
1715 flags,
1716 uid,
Eric Laurenta18dced2018-07-20 15:14:54 -07001717 isSoundTrigger);
Eric Laurent599c7582015-12-07 18:05:55 -08001718
Eric Laurent3974e3b2017-12-07 17:58:43 -08001719 if (!profile->canOpenNewIo()) {
1720 return AUDIO_IO_HANDLE_NONE;
1721 }
1722
Eric Laurentfe231122017-11-17 17:48:06 -08001723 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001724
Eric Laurentfe231122017-11-17 17:48:06 -08001725 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1726 lConfig.sample_rate = profileSamplingRate;
1727 lConfig.channel_mask = profileChannelMask;
1728 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001729
Eric Laurent53b810e2017-12-10 17:25:10 -08001730 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001731 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001732 // the inputs vector must be of size >= 1, but we don't want to crash here
1733 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1734 }
1735
Eric Laurentfe231122017-11-17 17:48:06 -08001736 status_t status = inputDesc->open(&lConfig, device, address,
1737 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001738
1739 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001740 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001741 (profileSamplingRate != lConfig.sample_rate) ||
1742 !audio_formats_match(profileFormat, lConfig.format) ||
1743 (profileChannelMask != lConfig.channel_mask)) {
1744 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001745 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001746 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001747 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001748 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001749 }
Eric Laurent599c7582015-12-07 18:05:55 -08001750 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001751 }
1752
Eric Laurentc722f302014-12-10 11:21:49 -08001753 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001754 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001755
Eric Laurent599c7582015-12-07 18:05:55 -08001756 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001757 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001758
Eric Laurent599c7582015-12-07 18:05:55 -08001759 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001760}
1761
Eric Laurentbb948092017-01-23 18:33:30 -08001762//static
1763bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1764{
1765 return (source == AUDIO_SOURCE_HOTWORD) ||
1766 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1767 (source == AUDIO_SOURCE_FM_TUNER);
1768}
1769
Eric Laurentfb66dd92016-01-28 18:32:03 -08001770bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1771 const sp<AudioSession>& audioSession)
1772{
1773 // Do not allow capture if an active voice call is using a software patch and
1774 // the call TX source device is on the same HW module.
1775 // FIXME: would be better to refine to only inputs whose profile connects to the
1776 // call TX device but this information is not in the audio patch
1777 if (mCallTxPatch != 0 &&
1778 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1779 return false;
1780 }
1781
1782 // starting concurrent capture is enabled if:
1783 // 1) capturing for re-routing
1784 // 2) capturing for HOTWORD source
1785 // 3) capturing for FM TUNER source
1786 // 3) All other active captures are either for re-routing or HOTWORD
1787
1788 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001789 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001790 return true;
1791 }
1792
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001793 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001794 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001795 !is_virtual_input_device(activeInput->mDevice)) {
1796 return false;
1797 }
1798 }
1799
1800 return true;
1801}
1802
Chris Thornton2b864642017-06-27 21:26:07 -07001803// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1804bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1805 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1806 bool soundTriggerSupportsConcurrentCapture = false;
1807 unsigned int numModules = 0;
1808 struct sound_trigger_module_descriptor* nModules = NULL;
1809
1810 status_t status = SoundTrigger::listModules(nModules, &numModules);
1811 if (status == NO_ERROR && numModules != 0) {
1812 nModules = (struct sound_trigger_module_descriptor*) calloc(
1813 numModules, sizeof(struct sound_trigger_module_descriptor));
1814 if (nModules == NULL) {
1815 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1816 // ram the next time this function is called.
1817 ALOGE("Failed to allocate buffer for module descriptors");
1818 return false;
1819 }
1820
1821 status = SoundTrigger::listModules(nModules, &numModules);
1822 if (status == NO_ERROR) {
1823 soundTriggerSupportsConcurrentCapture = true;
1824 for (size_t i = 0; i < numModules; ++i) {
1825 soundTriggerSupportsConcurrentCapture &=
1826 nModules[i].properties.concurrent_capture;
1827 }
1828 }
1829 free(nModules);
1830 }
1831 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1832 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1833 }
1834 return mSoundTriggerSupportsConcurrentCapture;
1835}
1836
Eric Laurentfb66dd92016-01-28 18:32:03 -08001837
Eric Laurent8fc147b2018-07-22 19:13:55 -07001838status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001839 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001840 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001841{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001842 *concurrency = API_INPUT_CONCURRENCY_NONE;
1843
1844 ALOGV("%s portId %d", __FUNCTION__, portId);
1845
1846 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1847 if (inputDesc == 0) {
1848 ALOGW("startInput() no input for client %d", portId);
1849 return BAD_VALUE;
1850 }
1851 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
1852 audio_session_t session = client->session();
1853 audio_io_handle_t input = inputDesc->mIoHandle;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001854
1855 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1856 input, session, silenced, *concurrency);
1857
Eric Laurent599c7582015-12-07 18:05:55 -08001858 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1859 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001860 ALOGW("startInput() unknown session %d on input %d", session, input);
1861 return BAD_VALUE;
1862 }
1863
Eric Laurent74708e72017-04-07 17:13:42 -07001864 if (!is_virtual_input_device(inputDesc->mDevice)) {
1865 if (mCallTxPatch != 0 &&
1866 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1867 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001868 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001869 return INVALID_OPERATION;
1870 }
1871
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001872 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001873
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001874 // If a UID is idle and records silence and another not silenced recording starts
1875 // from another UID (idle or active) we stop the current idle UID recording in
1876 // favor of the new one - "There can be only one" TM
1877 if (!silenced) {
1878 for (const auto& activeDesc : activeInputs) {
1879 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1880 activeDesc->getId() == inputDesc->getId()) {
1881 continue;
1882 }
1883
1884 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1885 true /*activeOnly*/);
1886 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1887 if (activeSession->isSilenced()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07001888 closeSession(activeDesc, activeSession);
1889 ALOGV("startInput() session %d stopping silenced session %d", session, activeSession->session());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001890 activeInputs = mInputs.getActiveInputs();
1891 }
1892 }
1893 }
1894
1895 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001896 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1897 activeDesc->getId() == inputDesc->getId()) {
1898 continue;
1899 }
1900
Eric Laurent74708e72017-04-07 17:13:42 -07001901 audio_source_t activeSource = activeDesc->inputSource(true);
1902 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1903 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1904 if (activeDesc->hasPreemptedSession(session)) {
1905 ALOGW("startInput(%d) failed for HOTWORD: "
1906 "other input %d already started for HOTWORD",
1907 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001908 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001909 return INVALID_OPERATION;
1910 }
1911 } else {
1912 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1913 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001914 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001915 return INVALID_OPERATION;
1916 }
1917 } else {
1918 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1919 ALOGW("startInput(%d) failed: other input %d already started",
1920 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001921 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001922 return INVALID_OPERATION;
1923 }
1924 }
1925 }
1926
Chris Thornton2b864642017-06-27 21:26:07 -07001927 // We only need to check if the sound trigger session supports concurrent capture if the
1928 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1929 // that's running.
1930 const bool allowConcurrentWithSoundTrigger =
1931 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1932
Eric Laurent74708e72017-04-07 17:13:42 -07001933 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001934 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001935 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1936 continue;
1937 }
1938
Eric Laurent74708e72017-04-07 17:13:42 -07001939 audio_source_t activeSource = activeDesc->inputSource(true);
1940 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1941 AudioSessionCollection activeSessions =
1942 activeDesc->getAudioSessions(true /*activeOnly*/);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001943 sp<AudioSession> activeSession = activeSessions[0];
Eric Laurent74708e72017-04-07 17:13:42 -07001944 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001945 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001946 sessions.add(activeSession->session());
Eric Laurent74708e72017-04-07 17:13:42 -07001947 inputDesc->setPreemptedSessions(sessions);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001948 closeSession(inputDesc, activeSession);
Eric Laurent74708e72017-04-07 17:13:42 -07001949 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1950 input, activeDesc->mIoHandle);
1951 }
1952 }
1953 }
Eric Laurente552edb2014-03-10 17:42:56 -07001954
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001955 // Make sure we start with the correct silence state
1956 audioSession->setSilenced(silenced);
1957
Eric Laurent313d1e72016-01-29 09:56:57 -08001958 // increment activity count before calling getNewInputDevice() below as only active sessions
1959 // are considered for device selection
Eric Laurenta18dced2018-07-20 15:14:54 -07001960 inputDesc->changeRefCount(session, 1);
Eric Laurent313d1e72016-01-29 09:56:57 -08001961
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001962 // Routing?
1963 mInputRoutes.incRouteActivity(session);
1964
Eric Laurent2157f5b2018-04-25 18:33:02 -07001965 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001966 // indicate active capture to sound trigger service if starting capture from a mic on
1967 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001968 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001969 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001970
Eric Laurent733ce942017-12-07 12:18:25 -08001971 status_t status = inputDesc->start();
1972 if (status != NO_ERROR) {
1973 mInputRoutes.decRouteActivity(session);
Eric Laurenta18dced2018-07-20 15:14:54 -07001974 inputDesc->changeRefCount(session, -1);
Eric Laurent733ce942017-12-07 12:18:25 -08001975 return status;
1976 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001977
Eric Laurent733ce942017-12-07 12:18:25 -08001978 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001979 // if input maps to a dynamic policy with an activity listener, notify of state change
1980 if ((inputDesc->mPolicyMix != NULL)
1981 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1982 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1983 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001984 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001985
Eric Laurentf7c50102016-09-30 15:19:43 -07001986 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1987 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001988 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001989 SoundTrigger::setCaptureState(true);
1990 }
1991
1992 // automatically enable the remote submix output when input is started if not
1993 // used by a policy mix of type MIX_TYPE_RECORDERS
1994 // For remote submix (a virtual device), we open only one input per capture request.
1995 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1996 String8 address = String8("");
1997 if (inputDesc->mPolicyMix == NULL) {
1998 address = String8("0");
1999 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2000 address = inputDesc->mPolicyMix->mDeviceAddress;
2001 }
2002 if (address != "") {
2003 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2004 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2005 address, "remote-submix");
2006 }
Eric Laurentc722f302014-12-10 11:21:49 -08002007 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002008 }
Eric Laurente552edb2014-03-10 17:42:56 -07002009 }
2010
Eric Laurent599c7582015-12-07 18:05:55 -08002011 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002012
Eric Laurente552edb2014-03-10 17:42:56 -07002013 return NO_ERROR;
2014}
2015
Eric Laurent8fc147b2018-07-22 19:13:55 -07002016status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002017{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002018 ALOGV("%s portId %d", __FUNCTION__, portId);
2019
2020 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2021 if (inputDesc == 0) {
2022 ALOGW("stopInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002023 return BAD_VALUE;
2024 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002025 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2026 audio_session_t session = client->session();
2027 audio_io_handle_t input = inputDesc->mIoHandle;
2028
2029 ALOGV("stopInput() input %d", input);
Eric Laurente552edb2014-03-10 17:42:56 -07002030
Eric Laurent599c7582015-12-07 18:05:55 -08002031 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002032
Eric Laurent599c7582015-12-07 18:05:55 -08002033 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002034 ALOGW("stopInput() input %d already stopped", input);
2035 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002036 }
2037
Eric Laurenta18dced2018-07-20 15:14:54 -07002038 inputDesc->changeRefCount(session, -1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002039
2040 // Routing?
2041 mInputRoutes.decRouteActivity(session);
2042
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002043 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002044 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002045 if (inputDesc->isActive()) {
2046 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2047 } else {
2048 // if input maps to a dynamic policy with an activity listener, notify of state change
2049 if ((inputDesc->mPolicyMix != NULL)
2050 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2051 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2052 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002053 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002054
2055 // automatically disable the remote submix output when input is stopped if not
2056 // used by a policy mix of type MIX_TYPE_RECORDERS
2057 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2058 String8 address = String8("");
2059 if (inputDesc->mPolicyMix == NULL) {
2060 address = String8("0");
2061 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2062 address = inputDesc->mPolicyMix->mDeviceAddress;
2063 }
2064 if (address != "") {
2065 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2066 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2067 address, "remote-submix");
2068 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002069 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002070
Eric Laurentf7c50102016-09-30 15:19:43 -07002071 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002072 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002073
Eric Laurentf7c50102016-09-30 15:19:43 -07002074 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2075 // primary HW module
2076 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2077 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2078 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002079 SoundTrigger::setCaptureState(false);
2080 }
2081 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002082 }
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002084 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002085}
2086
Eric Laurent8fc147b2018-07-22 19:13:55 -07002087void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002088{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002089 ALOGV("%s portId %d", __FUNCTION__, portId);
2090
2091 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2092 if (inputDesc == 0) {
2093 ALOGW("releaseInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002094 return;
2095 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002096 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2097 audio_session_t session = client->session();
2098 audio_io_handle_t input = inputDesc->mIoHandle;
2099
2100 ALOGV("releaseInput() %d", input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002101
2102 // Routing
2103 mInputRoutes.removeRoute(session);
2104
Eric Laurent599c7582015-12-07 18:05:55 -08002105 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002106 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002107 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2108 return;
2109 }
Eric Laurent599c7582015-12-07 18:05:55 -08002110
2111 if (audioSession->openCount() == 0) {
2112 ALOGW("releaseInput() invalid open count %d on session %d",
2113 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002114 return;
2115 }
Eric Laurent599c7582015-12-07 18:05:55 -08002116
2117 if (audioSession->changeOpenCount(-1) == 0) {
2118 inputDesc->removeAudioSession(session);
2119 }
2120
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002121 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002122 ALOGV("releaseInput() exit > 0");
2123 return;
2124 }
2125
Eric Laurent05b90f82014-08-27 15:32:29 -07002126 closeInput(input);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002127 inputDesc->clients().erase(portId);
Eric Laurentb52c1522014-05-20 11:27:36 -07002128 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002129 ALOGV("releaseInput() exit");
2130}
2131
Eric Laurent8fc147b2018-07-22 19:13:55 -07002132void AudioPolicyManager::closeSessions(const sp<AudioInputDescriptor>& input, bool activeOnly)
2133{
2134 AudioSessionCollection sessions = input->getAudioSessions(activeOnly /*activeOnly*/);
2135 for (size_t i = 0; i < sessions.size(); i++) {
2136 closeSession(input, sessions[i]);
2137 }
2138}
2139
2140void AudioPolicyManager::closeSession(const sp<AudioInputDescriptor>& input,
2141 const sp<AudioSession>& session)
2142{
2143 RecordClientVector clients = input->getClientsForSession(session->session());
2144
2145 for (const auto& client : clients) {
2146 stopInput(client->portId());
2147 releaseInput(client->portId());
2148 }
2149}
2150
2151
Eric Laurentd4692962014-05-05 18:13:44 -07002152void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002153 bool patchRemoved = false;
2154
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002155 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002156 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002157 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002158 if (patch_index >= 0) {
2159 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002160 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002161 mAudioPatches.removeItemsAt(patch_index);
2162 patchRemoved = true;
2163 }
Eric Laurentfe231122017-11-17 17:48:06 -08002164 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002165 }
jiabin829a00b2018-04-04 16:28:32 -07002166 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002167 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002168 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002169 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002170
2171 if (patchRemoved) {
2172 mpClientInterface->onAudioPatchListUpdate();
2173 }
Eric Laurentd4692962014-05-05 18:13:44 -07002174}
2175
Eric Laurente0720872014-03-11 09:30:41 -07002176void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002177 int indexMin,
2178 int indexMax)
2179{
2180 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002181 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002182
2183 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002184 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2185 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002186 continue;
2187 }
2188 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002189 }
Eric Laurente552edb2014-03-10 17:42:56 -07002190}
2191
Eric Laurente0720872014-03-11 09:30:41 -07002192status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002193 int index,
2194 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002195{
2196
Nadav Bar7c605f62017-12-25 00:01:52 +02002197 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2198 // app that has MODIFY_PHONE_STATE permission.
2199 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2200 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002201 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002202 return BAD_VALUE;
2203 }
2204 if (!audio_is_output_device(device)) {
2205 return BAD_VALUE;
2206 }
2207
2208 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002209 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002210
Eric Laurent1fd372e2016-04-06 14:23:53 -07002211 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002212 stream, device, index);
2213
Eric Laurent28d09f02016-03-08 10:43:05 -08002214 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002215 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2216 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002217 continue;
2218 }
2219 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2220 }
Eric Laurente552edb2014-03-10 17:42:56 -07002221
Eric Laurent1fd372e2016-04-06 14:23:53 -07002222 // update volume on all outputs and streams matching the following:
2223 // - The requested stream (or a stream matching for volume control) is active on the output
2224 // - The device (or devices) selected by the strategy corresponding to this stream includes
2225 // the requested device
2226 // - For non default requested device, currently selected device on the output is either the
2227 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002228 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2229 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002230 status_t status = NO_ERROR;
2231 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002232 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2233 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002234 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002235 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002236 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002237 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002238 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002239 continue;
2240 }
Eric Laurent794fde22016-03-11 09:50:45 -08002241 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002242 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2243 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002244 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2245 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002246 continue;
2247 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002248 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002249 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002250 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002251 applyVolume = (curDevice & curStreamDevice) != 0;
2252 } else {
2253 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002254 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002255 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002256 // rescale index before applying to curStream as ranges may be different for
2257 // stream and curStream
2258 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002259 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002260 //FIXME: workaround for truncated touch sounds
2261 // delayed volume change for system stream to be removed when the problem is
2262 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002263 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002264 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002265 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002266 if (volStatus != NO_ERROR) {
2267 status = volStatus;
2268 }
2269 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002270 }
Eric Laurente552edb2014-03-10 17:42:56 -07002271 }
2272 return status;
2273}
2274
Eric Laurente0720872014-03-11 09:30:41 -07002275status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002276 int *index,
2277 audio_devices_t device)
2278{
2279 if (index == NULL) {
2280 return BAD_VALUE;
2281 }
2282 if (!audio_is_output_device(device)) {
2283 return BAD_VALUE;
2284 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002285 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002286 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002287 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002288 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2289 }
François Gaffiedfd74092015-03-19 12:10:59 +01002290 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002291
François Gaffied1ab2bd2015-12-02 18:20:06 +01002292 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002293 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2294 return NO_ERROR;
2295}
2296
Eric Laurent36829f92017-04-07 19:04:42 -07002297audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002298{
2299 // select one output among several suitable for global effects.
2300 // The priority is as follows:
2301 // 1: An offloaded output. If the effect ends up not being offloadable,
2302 // AudioFlinger will invalidate the track and the offloaded output
2303 // will be closed causing the effect to be moved to a PCM output.
2304 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002305 // 3: The primary output
2306 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002307
Eric Laurent3b73df72014-03-11 09:06:29 -07002308 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002309 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002310 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002311
Eric Laurent36829f92017-04-07 19:04:42 -07002312 if (outputs.size() == 0) {
2313 return AUDIO_IO_HANDLE_NONE;
2314 }
Eric Laurente552edb2014-03-10 17:42:56 -07002315
Eric Laurent36829f92017-04-07 19:04:42 -07002316 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2317 bool activeOnly = true;
2318
2319 while (output == AUDIO_IO_HANDLE_NONE) {
2320 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2321 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2322 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2323
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002324 for (audio_io_handle_t output : outputs) {
2325 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002326 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2327 continue;
2328 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002329 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2330 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002331 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002332 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002333 }
2334 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002335 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002336 }
2337 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002338 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002339 }
2340 }
2341 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2342 output = outputOffloaded;
2343 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2344 output = outputDeepBuffer;
2345 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2346 output = outputPrimary;
2347 } else {
2348 output = outputs[0];
2349 }
2350 activeOnly = false;
2351 }
2352
2353 if (output != mMusicEffectOutput) {
2354 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2355 mMusicEffectOutput = output;
2356 }
2357
2358 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002359 return output;
2360}
2361
Eric Laurent36829f92017-04-07 19:04:42 -07002362audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2363{
2364 return selectOutputForMusicEffects();
2365}
2366
Eric Laurente0720872014-03-11 09:30:41 -07002367status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002368 audio_io_handle_t io,
2369 uint32_t strategy,
2370 int session,
2371 int id)
2372{
2373 ssize_t index = mOutputs.indexOfKey(io);
2374 if (index < 0) {
2375 index = mInputs.indexOfKey(io);
2376 if (index < 0) {
2377 ALOGW("registerEffect() unknown io %d", io);
2378 return INVALID_OPERATION;
2379 }
2380 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002381 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002382}
2383
Eric Laurentc75307b2015-03-17 15:29:32 -07002384bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2385{
Eric Laurent28d09f02016-03-08 10:43:05 -08002386 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002387 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2388 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002389 continue;
2390 }
2391 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2392 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002393 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002394}
2395
2396bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2397{
2398 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2399}
2400
Eric Laurente0720872014-03-11 09:30:41 -07002401bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002402{
2403 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002404 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002405 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002406 return true;
2407 }
2408 }
2409 return false;
2410}
2411
Eric Laurent275e8e92014-11-30 15:14:47 -08002412// Register a list of custom mixes with their attributes and format.
2413// When a mix is registered, corresponding input and output profiles are
2414// added to the remote submix hw module. The profile contains only the
2415// parameters (sampling rate, format...) specified by the mix.
2416// The corresponding input remote submix device is also connected.
2417//
2418// When a remote submix device is connected, the address is checked to select the
2419// appropriate profile and the corresponding input or output stream is opened.
2420//
2421// When capture starts, getInputForAttr() will:
2422// - 1 look for a mix matching the address passed in attribtutes tags if any
2423// - 2 if none found, getDeviceForInputSource() will:
2424// - 2.1 look for a mix matching the attributes source
2425// - 2.2 if none found, default to device selection by policy rules
2426// At this time, the corresponding output remote submix device is also connected
2427// and active playback use cases can be transferred to this mix if needed when reconnecting
2428// after AudioTracks are invalidated
2429//
2430// When playback starts, getOutputForAttr() will:
2431// - 1 look for a mix matching the address passed in attribtutes tags if any
2432// - 2 if none found, look for a mix matching the attributes usage
2433// - 3 if none found, default to device and output selection by policy rules.
2434
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002435status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002436{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002437 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2438 status_t res = NO_ERROR;
2439
2440 sp<HwModule> rSubmixModule;
2441 // examine each mix's route type
2442 for (size_t i = 0; i < mixes.size(); i++) {
2443 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2444 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2445 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002446 break;
2447 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002448 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002449 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002450 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002451 rSubmixModule = mHwModules.getModuleFromName(
2452 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2453 if (rSubmixModule == 0) {
2454 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2455 i);
2456 res = INVALID_OPERATION;
2457 break;
2458 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002459 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002460
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002461 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002462
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002463 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002464 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002465 res = INVALID_OPERATION;
2466 break;
2467 }
2468 audio_config_t outputConfig = mixes[i].mFormat;
2469 audio_config_t inputConfig = mixes[i].mFormat;
2470 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2471 // stereo and let audio flinger do the channel conversion if needed.
2472 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2473 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2474 rSubmixModule->addOutputProfile(address, &outputConfig,
2475 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2476 rSubmixModule->addInputProfile(address, &inputConfig,
2477 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002478
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002479 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2480 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2481 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2482 address.string(), "remote-submix");
2483 } else {
2484 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2485 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2486 address.string(), "remote-submix");
2487 }
2488 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002489 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002490 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002491 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2492 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002493
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002494 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002495 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2497 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2498 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2499 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2500 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002501 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2502 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002503 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2504 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002505 } else {
2506 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002507 }
2508 break;
2509 }
2510 }
2511
2512 if (res != NO_ERROR) {
2513 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002514 i, device, address.string());
2515 res = INVALID_OPERATION;
2516 break;
2517 } else if (!foundOutput) {
2518 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2519 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002520 res = INVALID_OPERATION;
2521 break;
2522 }
Eric Laurentc722f302014-12-10 11:21:49 -08002523 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002524 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002525 if (res != NO_ERROR) {
2526 unregisterPolicyMixes(mixes);
2527 }
2528 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002529}
2530
2531status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2532{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002533 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 status_t res = NO_ERROR;
2535 sp<HwModule> rSubmixModule;
2536 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002537 for (const auto& mix : mixes) {
2538 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002539
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002541 rSubmixModule = mHwModules.getModuleFromName(
2542 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2543 if (rSubmixModule == 0) {
2544 res = INVALID_OPERATION;
2545 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 }
2547 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002548
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002549 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002550
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2552 res = INVALID_OPERATION;
2553 continue;
2554 }
2555
2556 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2557 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2558 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2559 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2560 address.string(), "remote-submix");
2561 }
2562 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2563 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2564 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2565 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2566 address.string(), "remote-submix");
2567 }
2568 rSubmixModule->removeOutputProfile(address);
2569 rSubmixModule->removeInputProfile(address);
2570
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002571 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2572 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 res = INVALID_OPERATION;
2574 continue;
2575 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002576 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002577 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002578 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002579}
2580
Eric Laurente552edb2014-03-10 17:42:56 -07002581
Eric Laurente0720872014-03-11 09:30:41 -07002582status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002583{
Eric Laurente552edb2014-03-10 17:42:56 -07002584 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002585 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2586 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002587 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002588 std::string stateLiteral;
2589 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002590 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2591 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2592 "communications", "media", "record", "dock", "system",
2593 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2594 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2595 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2596 result.appendFormat(" Force use for %s: %d\n",
2597 forceUses[i], mEngine->getForceUse(i));
2598 }
2599 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2600 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2601 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002602 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002603
François Gaffie112b0af2015-11-19 16:13:25 +01002604 mAvailableOutputDevices.dump(fd, String8("Available output"));
2605 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002606 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002607 mOutputs.dump(fd);
2608 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002609 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002610 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002611 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002612 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002613
2614 return NO_ERROR;
2615}
2616
2617// This function checks for the parameters which can be offloaded.
2618// This can be enhanced depending on the capability of the DSP and policy
2619// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002620bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002621{
2622 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002623 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002624 offloadInfo.sample_rate, offloadInfo.channel_mask,
2625 offloadInfo.format,
2626 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2627 offloadInfo.has_video);
2628
Andy Hung2ddee192015-12-18 17:34:44 -08002629 if (mMasterMono) {
2630 return false; // no offloading if mono is set.
2631 }
2632
Eric Laurente552edb2014-03-10 17:42:56 -07002633 // Check if offload has been disabled
2634 char propValue[PROPERTY_VALUE_MAX];
2635 if (property_get("audio.offload.disable", propValue, "0")) {
2636 if (atoi(propValue) != 0) {
2637 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2638 return false;
2639 }
2640 }
2641
2642 // Check if stream type is music, then only allow offload as of now.
2643 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2644 {
2645 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2646 return false;
2647 }
2648
2649 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002650 const bool allowOffloadWithVideo =
2651 property_get_bool("audio.offload.video", false /* default_value */);
2652 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002653 ALOGV("isOffloadSupported: has_video == true, returning false");
2654 return false;
2655 }
2656
2657 //If duration is less than minimum value defined in property, return false
2658 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2659 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2660 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2661 return false;
2662 }
2663 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2664 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2665 return false;
2666 }
2667
2668 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2669 // creating an offloaded track and tearing it down immediately after start when audioflinger
2670 // detects there is an active non offloadable effect.
2671 // FIXME: We should check the audio session here but we do not have it in this context.
2672 // This may prevent offloading in rare situations where effects are left active by apps
2673 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002674 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002675 return false;
2676 }
2677
2678 // See if there is a profile to support this.
2679 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002680 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002681 offloadInfo.sample_rate,
2682 offloadInfo.format,
2683 offloadInfo.channel_mask,
2684 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002685 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2686 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002687}
2688
Eric Laurent6a94d692014-05-20 11:18:06 -07002689status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2690 audio_port_type_t type,
2691 unsigned int *num_ports,
2692 struct audio_port *ports,
2693 unsigned int *generation)
2694{
2695 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2696 generation == NULL) {
2697 return BAD_VALUE;
2698 }
2699 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2700 if (ports == NULL) {
2701 *num_ports = 0;
2702 }
2703
2704 size_t portsWritten = 0;
2705 size_t portsMax = *num_ports;
2706 *num_ports = 0;
2707 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002708 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2709 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002710 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002711 for (const auto& dev : mAvailableOutputDevices) {
2712 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002713 continue;
2714 }
2715 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002716 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002717 }
2718 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002719 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002720 }
2721 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002722 for (const auto& dev : mAvailableInputDevices) {
2723 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002724 continue;
2725 }
2726 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002727 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002728 }
2729 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002730 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002731 }
2732 }
2733 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2734 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2735 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2736 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2737 }
2738 *num_ports += mInputs.size();
2739 }
2740 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002741 size_t numOutputs = 0;
2742 for (size_t i = 0; i < mOutputs.size(); i++) {
2743 if (!mOutputs[i]->isDuplicated()) {
2744 numOutputs++;
2745 if (portsWritten < portsMax) {
2746 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2747 }
2748 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002749 }
Eric Laurent84c70242014-06-23 08:46:27 -07002750 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002751 }
2752 }
2753 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002754 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002755 return NO_ERROR;
2756}
2757
Eric Laurent99fcae42018-05-17 16:59:18 -07002758status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002759{
Eric Laurent99fcae42018-05-17 16:59:18 -07002760 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2761 return BAD_VALUE;
2762 }
2763 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2764 if (dev != 0) {
2765 dev->toAudioPort(port);
2766 return NO_ERROR;
2767 }
2768 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2769 if (dev != 0) {
2770 dev->toAudioPort(port);
2771 return NO_ERROR;
2772 }
2773 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2774 if (out != 0) {
2775 out->toAudioPort(port);
2776 return NO_ERROR;
2777 }
2778 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2779 if (in != 0) {
2780 in->toAudioPort(port);
2781 return NO_ERROR;
2782 }
2783 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002784}
2785
Eric Laurent6a94d692014-05-20 11:18:06 -07002786status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2787 audio_patch_handle_t *handle,
2788 uid_t uid)
2789{
2790 ALOGV("createAudioPatch()");
2791
2792 if (handle == NULL || patch == NULL) {
2793 return BAD_VALUE;
2794 }
2795 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2796
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002797 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002798 return BAD_VALUE;
2799 }
2800 // only one source per audio patch supported for now
2801 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002802 return INVALID_OPERATION;
2803 }
Eric Laurent874c42872014-08-08 15:13:39 -07002804
2805 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002806 return INVALID_OPERATION;
2807 }
Eric Laurent874c42872014-08-08 15:13:39 -07002808 for (size_t i = 0; i < patch->num_sinks; i++) {
2809 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2810 return INVALID_OPERATION;
2811 }
2812 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002813
2814 sp<AudioPatch> patchDesc;
2815 ssize_t index = mAudioPatches.indexOfKey(*handle);
2816
Eric Laurent6a94d692014-05-20 11:18:06 -07002817 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2818 patch->sources[0].role,
2819 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002820#if LOG_NDEBUG == 0
2821 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002822 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002823 patch->sinks[i].role,
2824 patch->sinks[i].type);
2825 }
2826#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002827
2828 if (index >= 0) {
2829 patchDesc = mAudioPatches.valueAt(index);
2830 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2831 mUidCached, patchDesc->mUid, uid);
2832 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2833 return INVALID_OPERATION;
2834 }
2835 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002836 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002837 }
2838
2839 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002840 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002841 if (outputDesc == NULL) {
2842 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2843 return BAD_VALUE;
2844 }
Eric Laurent84c70242014-06-23 08:46:27 -07002845 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2846 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 if (patchDesc != 0) {
2848 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2849 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2850 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2851 return BAD_VALUE;
2852 }
2853 }
Eric Laurent874c42872014-08-08 15:13:39 -07002854 DeviceVector devices;
2855 for (size_t i = 0; i < patch->num_sinks; i++) {
2856 // Only support mix to devices connection
2857 // TODO add support for mix to mix connection
2858 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2859 ALOGV("createAudioPatch() source mix but sink is not a device");
2860 return INVALID_OPERATION;
2861 }
2862 sp<DeviceDescriptor> devDesc =
2863 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2864 if (devDesc == 0) {
2865 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2866 return BAD_VALUE;
2867 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002868
François Gaffie53615e22015-03-19 09:24:12 +01002869 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002870 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002871 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002872 NULL, // updatedSamplingRate
2873 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002874 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002875 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002876 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002877 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002878 ALOGV("createAudioPatch() profile not supported for device %08x",
2879 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002880 return INVALID_OPERATION;
2881 }
2882 devices.add(devDesc);
2883 }
2884 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002885 return INVALID_OPERATION;
2886 }
Eric Laurent874c42872014-08-08 15:13:39 -07002887
Eric Laurent6a94d692014-05-20 11:18:06 -07002888 // TODO: reconfigure output format and channels here
2889 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002890 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002891 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002892 index = mAudioPatches.indexOfKey(*handle);
2893 if (index >= 0) {
2894 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2895 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2896 }
2897 patchDesc = mAudioPatches.valueAt(index);
2898 patchDesc->mUid = uid;
2899 ALOGV("createAudioPatch() success");
2900 } else {
2901 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2902 return INVALID_OPERATION;
2903 }
2904 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2905 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2906 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002907 // only one sink supported when connecting an input device to a mix
2908 if (patch->num_sinks > 1) {
2909 return INVALID_OPERATION;
2910 }
François Gaffie53615e22015-03-19 09:24:12 +01002911 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002912 if (inputDesc == NULL) {
2913 return BAD_VALUE;
2914 }
2915 if (patchDesc != 0) {
2916 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2917 return BAD_VALUE;
2918 }
2919 }
2920 sp<DeviceDescriptor> devDesc =
2921 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2922 if (devDesc == 0) {
2923 return BAD_VALUE;
2924 }
2925
François Gaffie53615e22015-03-19 09:24:12 +01002926 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002927 devDesc->mAddress,
2928 patch->sinks[0].sample_rate,
2929 NULL, /*updatedSampleRate*/
2930 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002931 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002932 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002933 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002934 // FIXME for the parameter type,
2935 // and the NONE
2936 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002937 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002938 return INVALID_OPERATION;
2939 }
2940 // TODO: reconfigure output format and channels here
2941 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002942 devDesc->type(), inputDesc->mIoHandle);
2943 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002944 index = mAudioPatches.indexOfKey(*handle);
2945 if (index >= 0) {
2946 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2947 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2948 }
2949 patchDesc = mAudioPatches.valueAt(index);
2950 patchDesc->mUid = uid;
2951 ALOGV("createAudioPatch() success");
2952 } else {
2953 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2954 return INVALID_OPERATION;
2955 }
2956 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2957 // device to device connection
2958 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002959 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002960 return BAD_VALUE;
2961 }
2962 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002963 sp<DeviceDescriptor> srcDeviceDesc =
2964 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002965 if (srcDeviceDesc == 0) {
2966 return BAD_VALUE;
2967 }
Eric Laurent874c42872014-08-08 15:13:39 -07002968
Eric Laurent6a94d692014-05-20 11:18:06 -07002969 //update source and sink with our own data as the data passed in the patch may
2970 // be incomplete.
2971 struct audio_patch newPatch = *patch;
2972 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002973
Eric Laurent874c42872014-08-08 15:13:39 -07002974 for (size_t i = 0; i < patch->num_sinks; i++) {
2975 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2976 ALOGV("createAudioPatch() source device but one sink is not a device");
2977 return INVALID_OPERATION;
2978 }
2979
2980 sp<DeviceDescriptor> sinkDeviceDesc =
2981 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2982 if (sinkDeviceDesc == 0) {
2983 return BAD_VALUE;
2984 }
2985 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2986
Eric Laurent3bcf8592015-04-03 12:13:24 -07002987 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08002988 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07002989 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002990 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002991 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002992 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002993 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002994 return INVALID_OPERATION;
2995 }
Eric Laurent874c42872014-08-08 15:13:39 -07002996 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002997 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002998 // if the sink device is reachable via an opened output stream, request to go via
2999 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003000 audio_io_handle_t output = selectOutput(outputs,
3001 AUDIO_OUTPUT_FLAG_NONE,
3002 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003003 if (output != AUDIO_IO_HANDLE_NONE) {
3004 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3005 if (outputDesc->isDuplicated()) {
3006 return INVALID_OPERATION;
3007 }
3008 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003009 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003010 newPatch.num_sources = 2;
3011 }
Eric Laurent83b88082014-06-20 18:31:16 -07003012 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003013 }
3014 // TODO: check from routing capabilities in config file and other conflicting patches
3015
Mikhail Naganovdc769682018-05-04 15:34:08 -07003016 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3017 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003018 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3019 status);
3020 return INVALID_OPERATION;
3021 }
3022 } else {
3023 return BAD_VALUE;
3024 }
3025 } else {
3026 return BAD_VALUE;
3027 }
3028 return NO_ERROR;
3029}
3030
3031status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3032 uid_t uid)
3033{
3034 ALOGV("releaseAudioPatch() patch %d", handle);
3035
3036 ssize_t index = mAudioPatches.indexOfKey(handle);
3037
3038 if (index < 0) {
3039 return BAD_VALUE;
3040 }
3041 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3042 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3043 mUidCached, patchDesc->mUid, uid);
3044 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3045 return INVALID_OPERATION;
3046 }
3047
3048 struct audio_patch *patch = &patchDesc->mPatch;
3049 patchDesc->mUid = mUidCached;
3050 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003051 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003052 if (outputDesc == NULL) {
3053 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3054 return BAD_VALUE;
3055 }
3056
Eric Laurentc75307b2015-03-17 15:29:32 -07003057 setOutputDevice(outputDesc,
3058 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003059 true,
3060 0,
3061 NULL);
3062 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3063 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003064 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 if (inputDesc == NULL) {
3066 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3067 return BAD_VALUE;
3068 }
3069 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003070 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003071 true,
3072 NULL);
3073 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003074 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3075 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3076 status, patchDesc->mAfPatchHandle);
3077 removeAudioPatch(patchDesc->mHandle);
3078 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003079 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003080 } else {
3081 return BAD_VALUE;
3082 }
3083 } else {
3084 return BAD_VALUE;
3085 }
3086 return NO_ERROR;
3087}
3088
3089status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3090 struct audio_patch *patches,
3091 unsigned int *generation)
3092{
François Gaffie53615e22015-03-19 09:24:12 +01003093 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003094 return BAD_VALUE;
3095 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003096 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003097 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003098}
3099
Eric Laurente1715a42014-05-20 11:30:42 -07003100status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003101{
Eric Laurente1715a42014-05-20 11:30:42 -07003102 ALOGV("setAudioPortConfig()");
3103
3104 if (config == NULL) {
3105 return BAD_VALUE;
3106 }
3107 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3108 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003109 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3110 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003111 }
3112
Eric Laurenta121f902014-06-03 13:32:54 -07003113 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003114 if (config->type == AUDIO_PORT_TYPE_MIX) {
3115 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003116 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003117 if (outputDesc == NULL) {
3118 return BAD_VALUE;
3119 }
Eric Laurent84c70242014-06-23 08:46:27 -07003120 ALOG_ASSERT(!outputDesc->isDuplicated(),
3121 "setAudioPortConfig() called on duplicated output %d",
3122 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003123 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003124 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003125 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003126 if (inputDesc == NULL) {
3127 return BAD_VALUE;
3128 }
Eric Laurenta121f902014-06-03 13:32:54 -07003129 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003130 } else {
3131 return BAD_VALUE;
3132 }
3133 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3134 sp<DeviceDescriptor> deviceDesc;
3135 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3136 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3137 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3138 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3139 } else {
3140 return BAD_VALUE;
3141 }
3142 if (deviceDesc == NULL) {
3143 return BAD_VALUE;
3144 }
Eric Laurenta121f902014-06-03 13:32:54 -07003145 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003146 } else {
3147 return BAD_VALUE;
3148 }
3149
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003150 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003151 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3152 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003153 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003154 audioPortConfig->toAudioPortConfig(&newConfig, config);
3155 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003156 }
Eric Laurenta121f902014-06-03 13:32:54 -07003157 if (status != NO_ERROR) {
3158 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003159 }
Eric Laurente1715a42014-05-20 11:30:42 -07003160
3161 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003162}
3163
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003164void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3165{
Eric Laurentd60560a2015-04-10 11:31:20 -07003166 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003167 clearAudioPatches(uid);
3168 clearSessionRoutes(uid);
3169}
3170
Eric Laurent6a94d692014-05-20 11:18:06 -07003171void AudioPolicyManager::clearAudioPatches(uid_t uid)
3172{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003173 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003174 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3175 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003176 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003177 }
3178 }
3179}
3180
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003181void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3182 audio_io_handle_t ouptutToSkip)
3183{
3184 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3185 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3186 for (size_t j = 0; j < mOutputs.size(); j++) {
3187 if (mOutputs.keyAt(j) == ouptutToSkip) {
3188 continue;
3189 }
3190 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3191 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3192 continue;
3193 }
3194 // If the default device for this strategy is on another output mix,
3195 // invalidate all tracks in this strategy to force re connection.
3196 // Otherwise select new device on the output mix.
3197 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003198 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003199 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3200 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3201 }
3202 }
3203 } else {
3204 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3205 setOutputDevice(outputDesc, newDevice, false);
3206 }
3207 }
3208}
3209
3210void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3211{
3212 // remove output routes associated with this uid
3213 SortedVector<routing_strategy> affectedStrategies;
3214 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3215 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3216 if (route->mUid == uid) {
3217 mOutputRoutes.removeItemsAt(i);
3218 if (route->mDeviceDescriptor != 0) {
3219 affectedStrategies.add(getStrategy(route->mStreamType));
3220 }
3221 }
3222 }
3223 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003224 for (const auto& strategy : affectedStrategies) {
3225 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003226 }
3227
3228 // remove input routes associated with this uid
3229 SortedVector<audio_source_t> affectedSources;
3230 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3231 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3232 if (route->mUid == uid) {
3233 mInputRoutes.removeItemsAt(i);
3234 if (route->mDeviceDescriptor != 0) {
3235 affectedSources.add(route->mSource);
3236 }
3237 }
3238 }
3239 // reroute inputs if necessary
3240 SortedVector<audio_io_handle_t> inputsToClose;
3241 for (size_t i = 0; i < mInputs.size(); i++) {
3242 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003243 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003244 inputsToClose.add(inputDesc->mIoHandle);
3245 }
3246 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003247 for (const auto& input : inputsToClose) {
3248 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003249 }
3250}
3251
Eric Laurentd60560a2015-04-10 11:31:20 -07003252void AudioPolicyManager::clearAudioSources(uid_t uid)
3253{
3254 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3255 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3256 if (sourceDesc->mUid == uid) {
3257 stopAudioSource(mAudioSources.keyAt(i));
3258 }
3259 }
3260}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003261
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003262status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3263 audio_io_handle_t *ioHandle,
3264 audio_devices_t *device)
3265{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003266 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3267 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003268 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003269
François Gaffiedf372692015-03-19 10:43:27 +01003270 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003271}
3272
Eric Laurentd60560a2015-04-10 11:31:20 -07003273status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3274 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003275 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003276 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003277{
Eric Laurentd60560a2015-04-10 11:31:20 -07003278 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3279 if (source == NULL || attributes == NULL || handle == NULL) {
3280 return BAD_VALUE;
3281 }
3282
Glenn Kasten559d4392016-03-29 13:42:57 -07003283 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003284
3285 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3286 source->type != AUDIO_PORT_TYPE_DEVICE) {
3287 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3288 return INVALID_OPERATION;
3289 }
3290
3291 sp<DeviceDescriptor> srcDeviceDesc =
3292 mAvailableInputDevices.getDevice(source->ext.device.type,
3293 String8(source->ext.device.address));
3294 if (srcDeviceDesc == 0) {
3295 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3296 return BAD_VALUE;
3297 }
3298 sp<AudioSourceDescriptor> sourceDesc =
3299 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3300
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003301 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003302 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3303 sourceDesc->mPatchDesc = patchDesc;
3304
3305 status_t status = connectAudioSource(sourceDesc);
3306 if (status == NO_ERROR) {
3307 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3308 *handle = sourceDesc->getHandle();
3309 }
3310 return status;
3311}
3312
3313status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3314{
3315 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3316
3317 // make sure we only have one patch per source.
3318 disconnectAudioSource(sourceDesc);
3319
3320 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003321 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003322 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3323
3324 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3325 sp<DeviceDescriptor> sinkDeviceDesc =
3326 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3327
3328 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003329
3330 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3331 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003332 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003333 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3334 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3335 // create patch between src device and output device
3336 // create Hwoutput and add to mHwOutputs
3337 } else {
3338 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3339 audio_io_handle_t output =
3340 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3341 if (output == AUDIO_IO_HANDLE_NONE) {
3342 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3343 return INVALID_OPERATION;
3344 }
3345 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3346 if (outputDesc->isDuplicated()) {
3347 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3348 return INVALID_OPERATION;
3349 }
Eric Laurent733ce942017-12-07 12:18:25 -08003350 status_t status = outputDesc->start();
3351 if (status != NO_ERROR) {
3352 return status;
3353 }
3354
Eric Laurentd60560a2015-04-10 11:31:20 -07003355 // create a special patch with no sink and two sources:
3356 // - the second source indicates to PatchPanel through which output mix this patch should
3357 // be connected as well as the stream type for volume control
3358 // - the sink is defined by whatever output device is currently selected for the output
3359 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003360 PatchBuilder patchBuilder;
3361 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3362 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003363 &afPatchHandle,
3364 0);
3365 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3366 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003367 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003368 if (status != NO_ERROR) {
3369 ALOGW("%s patch panel could not connect device patch, error %d",
3370 __FUNCTION__, status);
3371 return INVALID_OPERATION;
3372 }
3373 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003374 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003375
3376 if (status != NO_ERROR) {
3377 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3378 return status;
3379 }
3380 sourceDesc->mSwOutput = outputDesc;
3381 if (delayMs != 0) {
3382 usleep(delayMs * 1000);
3383 }
3384 }
3385
3386 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3387 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3388
3389 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003390}
3391
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07003392status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle)
Eric Laurent554a2772015-04-10 11:29:24 -07003393{
Eric Laurentd60560a2015-04-10 11:31:20 -07003394 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3395 ALOGV("%s handle %d", __FUNCTION__, handle);
3396 if (sourceDesc == 0) {
3397 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3398 return BAD_VALUE;
3399 }
3400 status_t status = disconnectAudioSource(sourceDesc);
3401
3402 mAudioSources.removeItem(handle);
3403 return status;
3404}
3405
Andy Hung2ddee192015-12-18 17:34:44 -08003406status_t AudioPolicyManager::setMasterMono(bool mono)
3407{
3408 if (mMasterMono == mono) {
3409 return NO_ERROR;
3410 }
3411 mMasterMono = mono;
3412 // if enabling mono we close all offloaded devices, which will invalidate the
3413 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3414 // for recreating the new AudioTrack as non-offloaded PCM.
3415 //
3416 // If disabling mono, we leave all tracks as is: we don't know which clients
3417 // and tracks are able to be recreated as offloaded. The next "song" should
3418 // play back offloaded.
3419 if (mMasterMono) {
3420 Vector<audio_io_handle_t> offloaded;
3421 for (size_t i = 0; i < mOutputs.size(); ++i) {
3422 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3423 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3424 offloaded.push(desc->mIoHandle);
3425 }
3426 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003427 for (const auto& handle : offloaded) {
3428 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003429 }
3430 }
3431 // update master mono for all remaining outputs
3432 for (size_t i = 0; i < mOutputs.size(); ++i) {
3433 updateMono(mOutputs.keyAt(i));
3434 }
3435 return NO_ERROR;
3436}
3437
3438status_t AudioPolicyManager::getMasterMono(bool *mono)
3439{
3440 *mono = mMasterMono;
3441 return NO_ERROR;
3442}
3443
Eric Laurentac9cef52017-06-09 15:46:26 -07003444float AudioPolicyManager::getStreamVolumeDB(
3445 audio_stream_type_t stream, int index, audio_devices_t device)
3446{
3447 return computeVolume(stream, index, device);
3448}
3449
jiabin81772902018-04-02 17:52:27 -07003450status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3451 FormatVector& formats) {
3452 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3453 return BAD_VALUE;
3454 }
3455 String8 reply;
3456 reply = mpClientInterface->getParameters(
3457 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3458 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3459 AudioParameter repliedParameters(reply);
3460 if (repliedParameters.get(
3461 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3462 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3463 return BAD_VALUE;
3464 }
3465 for (auto format : formatsFromString(reply.string())) {
3466 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3467 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3468 if (format == AAC_FORMATS[i]) {
3469 format = AUDIO_FORMAT_AAC_LC;
3470 break;
3471 }
3472 }
3473 bool exist = false;
3474 for (size_t i = 0; i < formats.size(); i++) {
3475 if (format == formats[i]) {
3476 exist = true;
3477 break;
3478 }
3479 }
3480 bool isSurroundFormat = false;
3481 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3482 if (SURROUND_FORMATS[i] == format) {
3483 isSurroundFormat = true;
3484 break;
3485 }
3486 }
3487 if (!exist && isSurroundFormat) {
3488 formats.add(format);
3489 }
3490 }
3491 return NO_ERROR;
3492}
3493
3494status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3495 audio_format_t *surroundFormats,
3496 bool *surroundFormatsEnabled,
3497 bool reported)
3498{
3499 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3500 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3501 return BAD_VALUE;
3502 }
3503 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3504 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3505
3506 // Only return value if there is HDMI output.
3507 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3508 return INVALID_OPERATION;
3509 }
3510
3511 size_t formatsWritten = 0;
3512 size_t formatsMax = *numSurroundFormats;
3513 *numSurroundFormats = 0;
3514 FormatVector formats;
3515 if (reported) {
3516 // Only get surround formats which are reported by device.
3517 // First list already open outputs that can be routed to this device
3518 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3519 SortedVector<audio_io_handle_t> outputs;
3520 bool reportedFormatFound = false;
3521 status_t status;
3522 sp<SwAudioOutputDescriptor> desc;
3523 for (size_t i = 0; i < mOutputs.size(); i++) {
3524 desc = mOutputs.valueAt(i);
3525 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3526 outputs.add(mOutputs.keyAt(i));
3527 }
3528 }
3529 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003530 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003531 AUDIO_DEVICE_OUT_HDMI);
3532 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3533 String8 address = hdmiOutputDevices[i]->mAddress;
3534 for (const auto& hwModule : mHwModules) {
3535 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3536 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3537 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3538 profile->supportDeviceAddress(address)) {
3539 size_t j;
3540 for (j = 0; j < outputs.size(); j++) {
3541 desc = mOutputs.valueFor(outputs.itemAt(j));
3542 if (!desc->isDuplicated() && desc->mProfile == profile) {
3543 break;
3544 }
3545 }
3546 if (j != outputs.size()) {
3547 status = getSupportedFormats(outputs.itemAt(j), formats);
3548 reportedFormatFound |= (status == NO_ERROR);
3549 continue;
3550 }
3551
3552 if (!profile->canOpenNewIo()) {
3553 ALOGW("Max Output number %u already opened for this profile %s",
3554 profile->maxOpenCount, profile->getTagName().c_str());
3555 continue;
3556 }
3557
3558 ALOGV("opening output for device %08x with params %s profile %p name %s",
3559 device, address.string(), profile.get(), profile->getName().string());
3560 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3561 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3562 status_t status = desc->open(nullptr, device, address,
3563 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3564 &output);
3565
3566 if (status == NO_ERROR) {
3567 status = getSupportedFormats(output, formats);
3568 reportedFormatFound |= (status == NO_ERROR);
3569 desc->close();
3570 output = AUDIO_IO_HANDLE_NONE;
3571 }
3572 }
3573 }
3574 }
3575 }
3576
3577 if (!reportedFormatFound) {
3578 return UNKNOWN_ERROR;
3579 }
3580 } else {
3581 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3582 formats.add(SURROUND_FORMATS[i]);
3583 }
3584 }
3585 for (size_t i = 0; i < formats.size(); i++) {
3586 if (formatsWritten < formatsMax) {
3587 surroundFormats[formatsWritten] = formats[i];
3588 bool formatEnabled = false;
3589 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3590 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3591 formatEnabled =
3592 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3593 break;
3594 }
3595 } else {
3596 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3597 }
3598 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3599 }
3600 (*numSurroundFormats)++;
3601 }
3602 return NO_ERROR;
3603}
3604
3605status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3606{
3607 // Check if audio format is a surround formats.
3608 bool isSurroundFormat = false;
3609 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3610 if (audioFormat == SURROUND_FORMATS[i]) {
3611 isSurroundFormat = true;
3612 break;
3613 }
3614 }
3615 if (!isSurroundFormat) {
3616 return BAD_VALUE;
3617 }
3618
3619 // Should only be called when MANUAL.
3620 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3621 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3622 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3623 return INVALID_OPERATION;
3624 }
3625
3626 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3627 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3628 return NO_ERROR;
3629 }
3630
3631 // The operation is valid only when there is HDMI output available.
3632 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3633 return INVALID_OPERATION;
3634 }
3635
3636 if (enabled) {
3637 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3638 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3639 mSurroundFormats.insert(AAC_FORMATS[i]);
3640 }
3641 } else {
3642 mSurroundFormats.insert(audioFormat);
3643 }
3644 } else {
3645 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3646 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3647 mSurroundFormats.erase(AAC_FORMATS[i]);
3648 }
3649 } else {
3650 mSurroundFormats.erase(audioFormat);
3651 }
3652 }
3653
3654 sp<SwAudioOutputDescriptor> outputDesc;
3655 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003656 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003657 AUDIO_DEVICE_OUT_HDMI);
3658 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3659 // Simulate reconnection to update enabled surround sound formats.
3660 String8 address = hdmiOutputDevices[i]->mAddress;
3661 String8 name = hdmiOutputDevices[i]->getName();
3662 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3663 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3664 address.c_str(),
3665 name.c_str());
3666 if (status != NO_ERROR) {
3667 continue;
3668 }
3669 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3670 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3671 address.c_str(),
3672 name.c_str());
3673 profileUpdated |= (status == NO_ERROR);
3674 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003675 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003676 AUDIO_DEVICE_IN_HDMI);
3677 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3678 // Simulate reconnection to update enabled surround sound formats.
3679 String8 address = hdmiInputDevices[i]->mAddress;
3680 String8 name = hdmiInputDevices[i]->getName();
3681 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3682 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3683 address.c_str(),
3684 name.c_str());
3685 if (status != NO_ERROR) {
3686 continue;
3687 }
3688 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3689 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3690 address.c_str(),
3691 name.c_str());
3692 profileUpdated |= (status == NO_ERROR);
3693 }
3694
3695 // Undo the surround formats change due to no audio profiles updated.
3696 if (!profileUpdated) {
3697 if (enabled) {
3698 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3699 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3700 mSurroundFormats.erase(AAC_FORMATS[i]);
3701 }
3702 } else {
3703 mSurroundFormats.erase(audioFormat);
3704 }
3705 } else {
3706 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3707 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3708 mSurroundFormats.insert(AAC_FORMATS[i]);
3709 }
3710 } else {
3711 mSurroundFormats.insert(audioFormat);
3712 }
3713 }
3714 }
3715
3716 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3717}
3718
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003719void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3720{
3721 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3722
3723 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3724 for (size_t i = 0; i < activeInputs.size(); i++) {
3725 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3726 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3727 for (size_t j = 0; j < activeSessions.size(); j++) {
3728 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3729 if (activeSession->uid() == uid) {
3730 activeSession->setSilenced(silenced);
3731 }
3732 }
3733 }
3734}
3735
Eric Laurentd60560a2015-04-10 11:31:20 -07003736status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3737{
3738 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3739
3740 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3741 if (patchDesc == 0) {
3742 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3743 sourceDesc->mPatchDesc->mHandle);
3744 return BAD_VALUE;
3745 }
3746 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3747
Eric Laurent28d09f02016-03-08 10:43:05 -08003748 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003749 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3750 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003751 status_t status = stopSource(swOutputDesc, stream, false);
3752 if (status == NO_ERROR) {
3753 swOutputDesc->stop();
3754 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003755 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3756 } else {
3757 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3758 if (hwOutputDesc != 0) {
3759 // release patch between src device and output device
3760 // close Hwoutput and remove from mHwOutputs
3761 } else {
3762 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3763 }
3764 }
3765 return NO_ERROR;
3766}
3767
3768sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3769 audio_io_handle_t output, routing_strategy strategy)
3770{
3771 sp<AudioSourceDescriptor> source;
3772 for (size_t i = 0; i < mAudioSources.size(); i++) {
3773 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3774 routing_strategy sourceStrategy =
3775 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3776 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3777 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3778 source = sourceDesc;
3779 break;
3780 }
3781 }
3782 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003783}
3784
Eric Laurente552edb2014-03-10 17:42:56 -07003785// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003786// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003787// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003788uint32_t AudioPolicyManager::nextAudioPortGeneration()
3789{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003790 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003791}
3792
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003793#ifdef USE_XML_AUDIO_POLICY_CONF
3794// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3795static const char *kConfigLocationList[] =
3796 {"/odm/etc", "/vendor/etc", "/system/etc"};
3797static const int kConfigLocationListSize =
3798 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3799
3800static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3801 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003802 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003803 status_t ret;
3804
Petri Gyntherf497f292018-04-17 18:46:10 -07003805 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3806 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3807 // A2DP offload supported but disabled: try to use special XML file
3808 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3809 }
3810 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3811
3812 for (const char* fileName : fileNames) {
3813 for (int i = 0; i < kConfigLocationListSize; i++) {
3814 PolicySerializer serializer;
3815 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3816 "%s/%s", kConfigLocationList[i], fileName);
3817 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3818 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003819 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003820 return ret;
3821 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003822 }
3823 }
3824 return ret;
3825}
3826#endif
3827
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003828AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3829 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003830 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003831 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003832 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003833 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003834 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003835#ifdef USE_XML_AUDIO_POLICY_CONF
3836 mVolumeCurves(new VolumeCurvesCollection()),
3837 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003838 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003839#else
3840 mVolumeCurves(new StreamDescriptorCollection()),
3841 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3842 mDefaultOutputDevice),
3843#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003844 mAudioPortGeneration(1),
3845 mBeaconMuteRefCount(0),
3846 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003847 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003848 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003849 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003850 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3851 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003852{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003853}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003854
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003855AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3856 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3857{
3858 loadConfig();
3859 initialize();
3860}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003861
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003862void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003863#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003864 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003865#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003866 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3867 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003868#endif
3869 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003870 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003871 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003872}
3873
3874status_t AudioPolicyManager::initialize() {
3875 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003876
3877 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003878 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3879 if (!engineInstance) {
3880 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003881 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003882 }
3883 // Retrieve the Policy Manager Interface
3884 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3885 if (mEngine == NULL) {
3886 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003887 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003888 }
3889 mEngine->setObserver(this);
3890 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003891 if (status != NO_ERROR) {
3892 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3893 return status;
3894 }
François Gaffie2110e042015-03-24 08:41:51 +01003895
Eric Laurent3a4311c2014-03-17 12:00:47 -07003896 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003897 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003898 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3899 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003900 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003901 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003902 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3903 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003904 continue;
3905 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003906 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003907 // open all output streams needed to access attached devices
3908 // except for direct output streams that are only opened when they are actually
3909 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003910 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003911 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003912 if (!outProfile->canOpenNewIo()) {
3913 ALOGE("Invalid Output profile max open count %u for profile %s",
3914 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3915 continue;
3916 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003917 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003918 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003919 continue;
3920 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003921 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003922 mTtsOutputAvailable = true;
3923 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003924
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003925 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003926 continue;
3927 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003928 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003929 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3930 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003931 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003932 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003933 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003934 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003935 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003936 if ((profileType & outputDeviceTypes) == 0) {
3937 continue;
3938 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003939 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3940 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003941 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003942 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3943 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003944 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3945 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003946 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003947 status_t status = outputDesc->open(nullptr, profileType, address,
3948 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003949
3950 if (status != NO_ERROR) {
3951 ALOGW("Cannot open output stream for device %08x on hw module %s",
3952 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003953 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003954 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003955 for (const auto& dev : supportedDevices) {
3956 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003958 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003959 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003960 }
3961 }
3962 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003963 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003964 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003965 }
3966 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003967 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003968 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003969 true,
3970 0,
3971 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003972 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003973 }
Eric Laurente552edb2014-03-10 17:42:56 -07003974 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003975 // open input streams needed to access attached devices to validate
3976 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003977 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003978 if (!inProfile->canOpenNewIo()) {
3979 ALOGE("Invalid Input profile max open count %u for profile %s",
3980 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3981 continue;
3982 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003983 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003984 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003985 continue;
3986 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003987 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003988 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003989 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3990
Eric Laurentd78f1532014-09-16 16:38:20 -07003991 if ((profileType & inputDeviceTypes) == 0) {
3992 continue;
3993 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003994 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003995 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003996
Mikhail Naganov708e0382018-05-30 09:53:04 -07003997 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003998 // the inputs vector must be of size >= 1, but we don't want to crash here
3999 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4000 : String8("");
4001 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4002 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4003
Eric Laurentd78f1532014-09-16 16:38:20 -07004004 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004005 status_t status = inputDesc->open(nullptr,
4006 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004007 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004008 AUDIO_SOURCE_MIC,
4009 AUDIO_INPUT_FLAG_NONE,
4010 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004011
4012 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004013 for (const auto& dev : inProfile->getSupportedDevices()) {
4014 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004015 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004016 if (index >= 0) {
4017 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4018 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004019 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004020 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004021 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004022 }
4023 }
Eric Laurentfe231122017-11-17 17:48:06 -08004024 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004025 } else {
4026 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004027 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004028 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004029 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004030 }
4031 }
4032 // make sure all attached devices have been allocated a unique ID
4033 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004034 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004035 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004036 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4037 continue;
4038 }
François Gaffie2110e042015-03-24 08:41:51 +01004039 // The device is now validated and can be appended to the available devices of the engine
4040 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4041 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004042 i++;
4043 }
4044 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004045 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004046 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004047 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4048 continue;
4049 }
François Gaffie2110e042015-03-24 08:41:51 +01004050 // The device is now validated and can be appended to the available devices of the engine
4051 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4052 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004053 i++;
4054 }
4055 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004056 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004057 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004058 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 }
jiabin9ff780e2018-03-19 18:19:52 -07004060 // If microphones address is empty, set it according to device type
4061 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4062 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4063 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4064 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4065 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4066 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4067 }
4068 }
4069 }
Eric Laurente552edb2014-03-10 17:42:56 -07004070
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004071 if (mPrimaryOutput == 0) {
4072 ALOGE("Failed to open primary output");
4073 status = NO_INIT;
4074 }
Eric Laurente552edb2014-03-10 17:42:56 -07004075
4076 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004077 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004078}
4079
Eric Laurente0720872014-03-11 09:30:41 -07004080AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004081{
Eric Laurente552edb2014-03-10 17:42:56 -07004082 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004083 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
4085 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004086 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004087 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004088 mAvailableOutputDevices.clear();
4089 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004090 mOutputs.clear();
4091 mInputs.clear();
4092 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004093 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004094 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004095}
4096
Eric Laurente0720872014-03-11 09:30:41 -07004097status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004098{
Eric Laurent87ffa392015-05-22 10:32:38 -07004099 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004100}
4101
Eric Laurente552edb2014-03-10 17:42:56 -07004102// ---
4103
Eric Laurent98e38192018-02-15 18:31:53 -08004104void AudioPolicyManager::addOutput(audio_io_handle_t output,
4105 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004106{
Eric Laurent1c333e22014-05-20 10:48:17 -07004107 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004108 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004109 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004110 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004111 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004112}
4113
François Gaffie53615e22015-03-19 09:24:12 +01004114void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4115{
4116 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004117 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004118}
4119
Eric Laurent98e38192018-02-15 18:31:53 -08004120void AudioPolicyManager::addInput(audio_io_handle_t input,
4121 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004122{
Eric Laurent1c333e22014-05-20 10:48:17 -07004123 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004124 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004125}
Eric Laurente552edb2014-03-10 17:42:56 -07004126
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004127void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004128 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004129 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004130 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004131 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004132 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004133 if (devDesc != 0) {
4134 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4135 desc->mIoHandle, address.string());
4136 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004137 }
4138}
4139
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004140status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004141 audio_policy_dev_state_t state,
4142 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004143 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004144{
François Gaffie53615e22015-03-19 09:24:12 +01004145 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004146 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004147
4148 if (audio_device_is_digital(device)) {
4149 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004150 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004151 }
Eric Laurente552edb2014-03-10 17:42:56 -07004152
Eric Laurent3b73df72014-03-11 09:06:29 -07004153 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004154 // first list already open outputs that can be routed to this device
4155 for (size_t i = 0; i < mOutputs.size(); i++) {
4156 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004157 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004158 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004159 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4160 outputs.add(mOutputs.keyAt(i));
4161 } else {
4162 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004163 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004164 }
Eric Laurente552edb2014-03-10 17:42:56 -07004165 }
4166 }
4167 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004168 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004169 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004170 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4171 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004172 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004173 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004174 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004175 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004176 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4177 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004178 }
Eric Laurente552edb2014-03-10 17:42:56 -07004179 }
4180 }
4181 }
4182
Eric Laurent7b279bb2015-12-14 10:18:23 -08004183 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004184
Eric Laurente552edb2014-03-10 17:42:56 -07004185 if (profiles.isEmpty() && outputs.isEmpty()) {
4186 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4187 return BAD_VALUE;
4188 }
4189
4190 // open outputs for matching profiles if needed. Direct outputs are also opened to
4191 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4192 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004193 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004194
4195 // nothing to do if one output is already opened for this profile
4196 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004197 for (j = 0; j < outputs.size(); j++) {
4198 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004199 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004200 // matching profile: save the sample rates, format and channel masks supported
4201 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004202 if (audio_device_is_digital(device)) {
4203 devDesc->importAudioPort(profile);
4204 }
Eric Laurente552edb2014-03-10 17:42:56 -07004205 break;
4206 }
4207 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004208 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004209 continue;
4210 }
4211
Eric Laurent3974e3b2017-12-07 17:58:43 -08004212 if (!profile->canOpenNewIo()) {
4213 ALOGW("Max Output number %u already opened for this profile %s",
4214 profile->maxOpenCount, profile->getTagName().c_str());
4215 continue;
4216 }
4217
Eric Laurent83efe1c2017-07-09 16:51:08 -07004218 ALOGV("opening output for device %08x with params %s profile %p name %s",
4219 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004220 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004221 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004222 status_t status = desc->open(nullptr, device, address,
4223 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004224
Eric Laurentfe231122017-11-17 17:48:06 -08004225 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004226 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004227 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004228 char *param = audio_device_address_to_parameter(device, address);
4229 mpClientInterface->setParameters(output, String8(param));
4230 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004231 }
Phil Burk00eeb322016-03-31 12:41:00 -07004232 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004233 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004234 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004235 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004236 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004237 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004238 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004239 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004240 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4241 profile->pickAudioProfile(
4242 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004243 config.offload_info.sample_rate = config.sample_rate;
4244 config.offload_info.channel_mask = config.channel_mask;
4245 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004246
4247 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4248 AUDIO_OUTPUT_FLAG_NONE, &output);
4249 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004250 output = AUDIO_IO_HANDLE_NONE;
4251 }
Eric Laurentd4692962014-05-05 18:13:44 -07004252 }
4253
Eric Laurentcf2c0212014-07-25 16:20:43 -07004254 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004255 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004256 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004257 sp<AudioPolicyMix> policyMix;
4258 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004259 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4260 address.string());
4261 }
François Gaffie036e1e92015-03-19 10:16:24 +01004262 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004263 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004264
Eric Laurent87ffa392015-05-22 10:32:38 -07004265 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4266 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004267 // no duplicated output for direct outputs and
4268 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004269 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004270
Eric Laurentd4692962014-05-05 18:13:44 -07004271 //TODO: configure audio effect output stage here
4272
4273 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004274 sp<SwAudioOutputDescriptor> dupOutputDesc =
4275 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4276 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4277 &duplicatedOutput);
4278 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004279 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004280 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004281 } else {
4282 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004283 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004284 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004285 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004286 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004287 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004288 }
Eric Laurente552edb2014-03-10 17:42:56 -07004289 }
4290 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004291 } else {
4292 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004294 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004295 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004296 profiles.removeAt(profile_index);
4297 profile_index--;
4298 } else {
4299 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004300 // Load digital format info only for digital devices
4301 if (audio_device_is_digital(device)) {
4302 devDesc->importAudioPort(profile);
4303 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004304
François Gaffie53615e22015-03-19 09:24:12 +01004305 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004306 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4307 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004308 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004309 NULL/*patch handle*/, address.string());
4310 }
Eric Laurente552edb2014-03-10 17:42:56 -07004311 ALOGV("checkOutputsForDevice(): adding output %d", output);
4312 }
4313 }
4314
4315 if (profiles.isEmpty()) {
4316 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4317 return BAD_VALUE;
4318 }
Eric Laurentd4692962014-05-05 18:13:44 -07004319 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004320 // check if one opened output is not needed any more after disconnecting one device
4321 for (size_t i = 0; i < mOutputs.size(); i++) {
4322 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004323 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004324 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004325 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004326 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004327 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004328 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4330 mOutputs.keyAt(i));
4331 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004332 }
Eric Laurente552edb2014-03-10 17:42:56 -07004333 }
4334 }
Eric Laurentd4692962014-05-05 18:13:44 -07004335 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004336 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004337 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4338 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004339 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004340 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004341 "clearing direct output profile %zu on module %s",
4342 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004343 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
4345 }
4346 }
4347 }
4348 return NO_ERROR;
4349}
4350
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004351status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004352 audio_policy_dev_state_t state,
4353 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004354 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004355{
Paul McLean9080a4c2015-06-18 08:24:02 -07004356 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004357 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004358
4359 if (audio_device_is_digital(device)) {
4360 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004361 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004362 }
4363
Eric Laurentd4692962014-05-05 18:13:44 -07004364 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4365 // first list already open inputs that can be routed to this device
4366 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4367 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004368 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004369 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4370 inputs.add(mInputs.keyAt(input_index));
4371 }
4372 }
4373
4374 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004375 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004376 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004377 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004378 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004379 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004380 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004381
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004382 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004383 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004384 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004385 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004386 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4387 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004388 }
Eric Laurentd4692962014-05-05 18:13:44 -07004389 }
4390 }
4391 }
4392
4393 if (profiles.isEmpty() && inputs.isEmpty()) {
4394 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4395 return BAD_VALUE;
4396 }
4397
4398 // open inputs for matching profiles if needed. Direct inputs are also opened to
4399 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4400 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4401
Eric Laurent1c333e22014-05-20 10:48:17 -07004402 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004403
Eric Laurentd4692962014-05-05 18:13:44 -07004404 // nothing to do if one input is already opened for this profile
4405 size_t input_index;
4406 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4407 desc = mInputs.valueAt(input_index);
4408 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004409 if (audio_device_is_digital(device)) {
4410 devDesc->importAudioPort(profile);
4411 }
Eric Laurentd4692962014-05-05 18:13:44 -07004412 break;
4413 }
4414 }
4415 if (input_index != mInputs.size()) {
4416 continue;
4417 }
4418
Eric Laurent3974e3b2017-12-07 17:58:43 -08004419 if (!profile->canOpenNewIo()) {
4420 ALOGW("Max Input number %u already opened for this profile %s",
4421 profile->maxOpenCount, profile->getTagName().c_str());
4422 continue;
4423 }
4424
Eric Laurentfe231122017-11-17 17:48:06 -08004425 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004426 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004427 status_t status = desc->open(nullptr,
4428 device,
4429 address,
4430 AUDIO_SOURCE_MIC,
4431 AUDIO_INPUT_FLAG_NONE,
4432 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004433
Eric Laurentcf2c0212014-07-25 16:20:43 -07004434 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004435 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004436 char *param = audio_device_address_to_parameter(device, address);
4437 mpClientInterface->setParameters(input, String8(param));
4438 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004439 }
Phil Burk00eeb322016-03-31 12:41:00 -07004440 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004441 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004442 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004443 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004444 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004445 }
4446
4447 if (input != 0) {
4448 addInput(input, desc);
4449 }
4450 } // endif input != 0
4451
Eric Laurentcf2c0212014-07-25 16:20:43 -07004452 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004453 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004454 profiles.removeAt(profile_index);
4455 profile_index--;
4456 } else {
4457 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004458 if (audio_device_is_digital(device)) {
4459 devDesc->importAudioPort(profile);
4460 }
Eric Laurentd4692962014-05-05 18:13:44 -07004461 ALOGV("checkInputsForDevice(): adding input %d", input);
4462 }
4463 } // end scan profiles
4464
4465 if (profiles.isEmpty()) {
4466 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4467 return BAD_VALUE;
4468 }
4469 } else {
4470 // Disconnect
4471 // check if one opened input is not needed any more after disconnecting one device
4472 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4473 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004474 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004475 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4476 mInputs.keyAt(input_index));
4477 inputs.add(mInputs.keyAt(input_index));
4478 }
4479 }
4480 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004481 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004482 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004483 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004484 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004485 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004486 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004487 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4488 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004489 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004490 }
4491 }
4492 }
4493 } // end disconnect
4494
4495 return NO_ERROR;
4496}
4497
4498
Eric Laurente0720872014-03-11 09:30:41 -07004499void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004500{
4501 ALOGV("closeOutput(%d)", output);
4502
Eric Laurentc75307b2015-03-17 15:29:32 -07004503 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004504 if (outputDesc == NULL) {
4505 ALOGW("closeOutput() unknown output %d", output);
4506 return;
4507 }
François Gaffie036e1e92015-03-19 10:16:24 +01004508 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004509
Eric Laurente552edb2014-03-10 17:42:56 -07004510 // look for duplicated outputs connected to the output being removed.
4511 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004512 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004513 if (dupOutputDesc->isDuplicated() &&
4514 (dupOutputDesc->mOutput1 == outputDesc ||
4515 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004516 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004517 if (dupOutputDesc->mOutput1 == outputDesc) {
4518 outputDesc2 = dupOutputDesc->mOutput2;
4519 } else {
4520 outputDesc2 = dupOutputDesc->mOutput1;
4521 }
4522 // As all active tracks on duplicated output will be deleted,
4523 // and as they were also referenced on the other output, the reference
4524 // count for their stream type must be adjusted accordingly on
4525 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004526 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004527 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004528 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004529 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004530 }
Eric Laurent733ce942017-12-07 12:18:25 -08004531 // stop() will be a no op if the output is still active but is needed in case all
4532 // active streams refcounts where cleared above
4533 if (wasActive) {
4534 outputDesc2->stop();
4535 }
Eric Laurente552edb2014-03-10 17:42:56 -07004536 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4537 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4538
4539 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004540 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004541 }
4542 }
4543
Eric Laurent05b90f82014-08-27 15:32:29 -07004544 nextAudioPortGeneration();
4545
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004546 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004547 if (index >= 0) {
4548 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004549 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004550 mAudioPatches.removeItemsAt(index);
4551 mpClientInterface->onAudioPatchListUpdate();
4552 }
4553
Eric Laurentfe231122017-11-17 17:48:06 -08004554 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004555
François Gaffie53615e22015-03-19 09:24:12 +01004556 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004557 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004558}
4559
4560void AudioPolicyManager::closeInput(audio_io_handle_t input)
4561{
4562 ALOGV("closeInput(%d)", input);
4563
4564 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4565 if (inputDesc == NULL) {
4566 ALOGW("closeInput() unknown input %d", input);
4567 return;
4568 }
4569
Eric Laurent6a94d692014-05-20 11:18:06 -07004570 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004571
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004572 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004573 if (index >= 0) {
4574 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004575 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004576 mAudioPatches.removeItemsAt(index);
4577 mpClientInterface->onAudioPatchListUpdate();
4578 }
4579
Eric Laurentfe231122017-11-17 17:48:06 -08004580 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004581 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004582}
4583
Eric Laurentc75307b2015-03-17 15:29:32 -07004584SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4585 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004586 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004587{
4588 SortedVector<audio_io_handle_t> outputs;
4589
4590 ALOGVV("getOutputsForDevice() device %04x", device);
4591 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004592 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004593 i, openOutputs.valueAt(i)->isDuplicated(),
4594 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004595 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4596 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4597 outputs.add(openOutputs.keyAt(i));
4598 }
4599 }
4600 return outputs;
4601}
4602
Mikhail Naganov37977152018-07-11 15:54:44 -07004603void AudioPolicyManager::checkForDeviceAndOutputChanges()
4604{
4605 checkForDeviceAndOutputChanges([](){ return false; });
4606}
4607
4608void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4609{
4610 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4611 // output is suspended before any tracks are moved to it
4612 checkA2dpSuspend();
4613 checkOutputForAllStrategies();
4614 if (onOutputsChecked()) checkA2dpSuspend();
4615 updateDevicesAndOutputs();
4616}
4617
Eric Laurente0720872014-03-11 09:30:41 -07004618void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004619{
4620 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4621 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4622 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4623 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4624
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004625 // also take into account external policy-related changes: add all outputs which are
4626 // associated with policies in the "before" and "after" output vectors
4627 ALOGVV("checkOutputForStrategy(): policy related outputs");
4628 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004629 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004630 if (desc != 0 && desc->mPolicyMix != NULL) {
4631 srcOutputs.add(desc->mIoHandle);
4632 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4633 }
4634 }
4635 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004636 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004637 if (desc != 0 && desc->mPolicyMix != NULL) {
4638 dstOutputs.add(desc->mIoHandle);
4639 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4640 }
4641 }
4642
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004643 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004644 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4645 // audio from invalidated tracks will be rendered when unmuting
4646 uint32_t maxLatency = 0;
4647 for (audio_io_handle_t srcOut : srcOutputs) {
4648 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4649 if (desc != 0 && maxLatency < desc->latency()) {
4650 maxLatency = desc->latency();
4651 }
4652 }
Eric Laurente552edb2014-03-10 17:42:56 -07004653 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4654 strategy, srcOutputs[0], dstOutputs[0]);
4655 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004656 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004657 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4658 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004659 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004660 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004662 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004663 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004664 if (source != 0){
4665 connectAudioSource(source);
4666 }
Eric Laurente552edb2014-03-10 17:42:56 -07004667 }
4668
4669 // Move effects associated to this strategy from previous output to new output
4670 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004671 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004672 }
4673 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004674 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004675 if (getStrategy((audio_stream_type_t)i) == strategy) {
4676 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004677 }
4678 }
4679 }
4680}
4681
Eric Laurente0720872014-03-11 09:30:41 -07004682void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004683{
François Gaffie2110e042015-03-24 08:41:51 +01004684 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004685 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004686 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004687 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004688 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004689 checkOutputForStrategy(STRATEGY_SONIFICATION);
4690 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004691 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004692 checkOutputForStrategy(STRATEGY_MEDIA);
4693 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004694 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004695}
4696
Eric Laurente0720872014-03-11 09:30:41 -07004697void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004698{
François Gaffie53615e22015-03-19 09:24:12 +01004699 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004700 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004701 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004702 return;
4703 }
4704
Eric Laurent3a4311c2014-03-17 12:00:47 -07004705 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004706 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4707 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4708 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004709
4710 // if suspended, restore A2DP output if:
4711 // ((SCO device is NOT connected) ||
4712 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4713 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004714 //
Eric Laurentf732e072016-08-03 19:30:28 -07004715 // if not suspended, suspend A2DP output if:
4716 // (SCO device is connected) &&
4717 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4718 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004719 //
4720 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004721 if (!isScoConnected ||
4722 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4723 AUDIO_POLICY_FORCE_BT_SCO) &&
4724 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4725 AUDIO_POLICY_FORCE_BT_SCO) &&
4726 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004727 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004728
4729 mpClientInterface->restoreOutput(a2dpOutput);
4730 mA2dpSuspended = false;
4731 }
4732 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004733 if (isScoConnected &&
4734 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4735 AUDIO_POLICY_FORCE_BT_SCO) ||
4736 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4737 AUDIO_POLICY_FORCE_BT_SCO) ||
4738 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004739 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004740
4741 mpClientInterface->suspendOutput(a2dpOutput);
4742 mA2dpSuspended = true;
4743 }
4744 }
4745}
4746
Eric Laurentc75307b2015-03-17 15:29:32 -07004747audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4748 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004749{
4750 audio_devices_t device = AUDIO_DEVICE_NONE;
4751
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004752 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004753 if (index >= 0) {
4754 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4755 if (patchDesc->mUid != mUidCached) {
4756 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004757 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 return outputDesc->device();
4759 }
4760 }
4761
Eric Laurentf3a5a602018-05-22 18:42:55 -07004762 // Check if an explicit routing request exists for an active stream on this output and
4763 // use it in priority before any other rule
4764 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4765 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4766 audio_devices_t forcedDevice =
4767 mOutputRoutes.getActiveDeviceForStream(
4768 (audio_stream_type_t)stream, mAvailableOutputDevices);
4769
4770 if (forcedDevice != AUDIO_DEVICE_NONE) {
4771 return forcedDevice;
4772 }
4773 }
4774 }
4775
Eric Laurente552edb2014-03-10 17:42:56 -07004776 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004777 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004778 // use device for strategy enforced audible
4779 // 2: we are in call or the strategy phone is active on the output:
4780 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004781 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004782 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004783 // 4: the strategy for enforced audible is active but not enforced on the output:
4784 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004785 // 5: the strategy accessibility is active on the output:
4786 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004787 // 6: the strategy "respectful" sonification is active on the output:
4788 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004789 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004790 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004791 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004792 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004793 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004794 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004795
4796 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4797 // with a refined rule considering mutually exclusive devices (using same backend)
4798 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004799 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004800 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004801 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4802 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004803 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004804 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004805 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004806 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004807 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4808 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004809 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4810 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004811 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004812 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004813 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004814 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004815 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004816 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004817 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004818 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004819 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004820 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004821 }
4822
Eric Laurent1c333e22014-05-20 10:48:17 -07004823 ALOGV("getNewOutputDevice() selected device %x", device);
4824 return device;
4825}
4826
Eric Laurentfb66dd92016-01-28 18:32:03 -08004827audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004828{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004829 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004830
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004831 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 if (index >= 0) {
4833 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4834 if (patchDesc->mUid != mUidCached) {
4835 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004836 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 return inputDesc->mDevice;
4838 }
4839 }
4840
Eric Laurentdc95a252018-04-12 12:46:56 -07004841 // If we are not in call and no client is active on this input, this methods returns
4842 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004843 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004844 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4845 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4846 }
4847 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004848 device = getDeviceAndMixForInputSource(source);
4849 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004850
Eric Laurente552edb2014-03-10 17:42:56 -07004851 return device;
4852}
4853
Eric Laurent794fde22016-03-11 09:50:45 -08004854bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4855 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004856 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004857}
4858
Eric Laurente0720872014-03-11 09:30:41 -07004859uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004860 return (uint32_t)getStrategy(stream);
4861}
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 // By checking the range of stream before calling getStrategy, we avoid
4865 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4866 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004867 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 return AUDIO_DEVICE_NONE;
4869 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004870 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004871 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4872 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004873 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004874 }
Eric Laurent794fde22016-03-11 09:50:45 -08004875 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004876 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004877 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004878 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4879 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004880 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004881 curDevices |= outputDesc->device();
4882 }
4883 }
4884 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004885 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004886
4887 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4888 and doesn't really need to.*/
4889 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4890 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4891 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4892 }
Eric Laurente552edb2014-03-10 17:42:56 -07004893 return devices;
4894}
4895
François Gaffie2110e042015-03-24 08:41:51 +01004896routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4897{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004898 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004899 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004900}
4901
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004902uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4903 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004904 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4905 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4906 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004907 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4908 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4909 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004910 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004911 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004912}
4913
Eric Laurente0720872014-03-11 09:30:41 -07004914void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004915 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004916 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004917 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4918 updateDevicesAndOutputs();
4919 break;
4920 default:
4921 break;
4922 }
4923}
4924
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004925uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004926
4927 // skip beacon mute management if a dedicated TTS output is available
4928 if (mTtsOutputAvailable) {
4929 return 0;
4930 }
4931
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004932 switch(event) {
4933 case STARTING_OUTPUT:
4934 mBeaconMuteRefCount++;
4935 break;
4936 case STOPPING_OUTPUT:
4937 if (mBeaconMuteRefCount > 0) {
4938 mBeaconMuteRefCount--;
4939 }
4940 break;
4941 case STARTING_BEACON:
4942 mBeaconPlayingRefCount++;
4943 break;
4944 case STOPPING_BEACON:
4945 if (mBeaconPlayingRefCount > 0) {
4946 mBeaconPlayingRefCount--;
4947 }
4948 break;
4949 }
4950
4951 if (mBeaconMuteRefCount > 0) {
4952 // any playback causes beacon to be muted
4953 return setBeaconMute(true);
4954 } else {
4955 // no other playback: unmute when beacon starts playing, mute when it stops
4956 return setBeaconMute(mBeaconPlayingRefCount == 0);
4957 }
4958}
4959
4960uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4961 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4962 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4963 // keep track of muted state to avoid repeating mute/unmute operations
4964 if (mBeaconMuted != mute) {
4965 // mute/unmute AUDIO_STREAM_TTS on all outputs
4966 ALOGV("\t muting %d", mute);
4967 uint32_t maxLatency = 0;
4968 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004969 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004970 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004971 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004972 0 /*delay*/, AUDIO_DEVICE_NONE);
4973 const uint32_t latency = desc->latency() * 2;
4974 if (latency > maxLatency) {
4975 maxLatency = latency;
4976 }
4977 }
4978 mBeaconMuted = mute;
4979 return maxLatency;
4980 }
4981 return 0;
4982}
4983
Eric Laurente0720872014-03-11 09:30:41 -07004984audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004985 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004986{
Eric Laurentf3a5a602018-05-22 18:42:55 -07004987 // Check if an explicit routing request exists for a stream type corresponding to the
4988 // specified strategy and use it in priority over default routing rules.
4989 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4990 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4991 audio_devices_t forcedDevice =
4992 mOutputRoutes.getActiveDeviceForStream(
4993 (audio_stream_type_t)stream, mAvailableOutputDevices);
4994 if (forcedDevice != AUDIO_DEVICE_NONE) {
4995 return forcedDevice;
4996 }
Paul McLeanaa981192015-03-21 09:55:15 -07004997 }
4998 }
4999
Eric Laurente552edb2014-03-10 17:42:56 -07005000 if (fromCache) {
5001 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5002 strategy, mDeviceForStrategy[strategy]);
5003 return mDeviceForStrategy[strategy];
5004 }
François Gaffie2110e042015-03-24 08:41:51 +01005005 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005006}
5007
Eric Laurente0720872014-03-11 09:30:41 -07005008void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005009{
5010 for (int i = 0; i < NUM_STRATEGIES; i++) {
5011 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5012 }
5013 mPreviousOutputs = mOutputs;
5014}
5015
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005016uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005017 audio_devices_t prevDevice,
5018 uint32_t delayMs)
5019{
5020 // mute/unmute strategies using an incompatible device combination
5021 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5022 // if unmuting, unmute only after the specified delay
5023 if (outputDesc->isDuplicated()) {
5024 return 0;
5025 }
5026
5027 uint32_t muteWaitMs = 0;
5028 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005029 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005030
5031 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5032 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005033 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005034 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5035 bool doMute = false;
5036
5037 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5038 doMute = true;
5039 outputDesc->mStrategyMutedByDevice[i] = true;
5040 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5041 doMute = true;
5042 outputDesc->mStrategyMutedByDevice[i] = false;
5043 }
Eric Laurent99401132014-05-07 19:48:15 -07005044 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005045 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005046 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005047 // skip output if it does not share any device with current output
5048 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5049 == AUDIO_DEVICE_NONE) {
5050 continue;
5051 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005052 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005053 mute ? "muting" : "unmuting", i, curDevice);
5054 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005055 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005056 if (mute) {
5057 // FIXME: should not need to double latency if volume could be applied
5058 // immediately by the audioflinger mixer. We must account for the delay
5059 // between now and the next time the audioflinger thread for this output
5060 // will process a buffer (which corresponds to one buffer size,
5061 // usually 1/2 or 1/4 of the latency).
5062 if (muteWaitMs < desc->latency() * 2) {
5063 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005064 }
5065 }
5066 }
5067 }
5068 }
5069 }
5070
Eric Laurent99401132014-05-07 19:48:15 -07005071 // temporary mute output if device selection changes to avoid volume bursts due to
5072 // different per device volumes
5073 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005074 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5075 // temporary mute duration is conservatively set to 4 times the reported latency
5076 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5077 if (muteWaitMs < tempMuteWaitMs) {
5078 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005079 }
Eric Laurentdc462862016-07-19 12:29:53 -07005080
Eric Laurent99401132014-05-07 19:48:15 -07005081 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005082 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005083 // make sure that we do not start the temporary mute period too early in case of
5084 // delayed device change
5085 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005086 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005087 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005088 }
5089 }
5090 }
5091
Eric Laurente552edb2014-03-10 17:42:56 -07005092 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5093 if (muteWaitMs > delayMs) {
5094 muteWaitMs -= delayMs;
5095 usleep(muteWaitMs * 1000);
5096 return muteWaitMs;
5097 }
5098 return 0;
5099}
5100
Eric Laurentc75307b2015-03-17 15:29:32 -07005101uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005102 audio_devices_t device,
5103 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005105 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005106 const char *address,
5107 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005108{
Eric Laurentc75307b2015-03-17 15:29:32 -07005109 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005110 AudioParameter param;
5111 uint32_t muteWaitMs;
5112
5113 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005114 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5115 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5116 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5117 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005118 return muteWaitMs;
5119 }
5120 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5121 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005122 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005123 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005124 return 0;
5125 }
5126
5127 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005128 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005129
5130 audio_devices_t prevDevice = outputDesc->mDevice;
5131
Paul McLeanaa981192015-03-21 09:55:15 -07005132 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005133
5134 if (device != AUDIO_DEVICE_NONE) {
5135 outputDesc->mDevice = device;
5136 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005137
5138 // if the outputs are not materially active, there is no need to mute.
5139 if (requiresMuteCheck) {
5140 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5141 } else {
5142 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5143 muteWaitMs = 0;
5144 }
Eric Laurente552edb2014-03-10 17:42:56 -07005145
5146 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005147 // the requested device is AUDIO_DEVICE_NONE
5148 // OR the requested device is the same as current device
5149 // AND force is not specified
5150 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005151 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005152 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5153 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005154 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005155 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005156 return muteWaitMs;
5157 }
5158
5159 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005160
Eric Laurente552edb2014-03-10 17:42:56 -07005161 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005162 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005163 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005164 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005165 DeviceVector deviceList;
5166 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005167 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005168 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005169 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5170 device, String8(address));
5171 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005172 }
5173
Eric Laurent1c333e22014-05-20 10:48:17 -07005174 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005175 PatchBuilder patchBuilder;
5176 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005177 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005178 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005179 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005180 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005181 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005182
5183 // inform all input as well
5184 for (size_t i = 0; i < mInputs.size(); i++) {
5185 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005186 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005187 AudioParameter inputCmd = AudioParameter();
5188 ALOGV("%s: inform input %d of device:%d", __func__,
5189 inputDescriptor->mIoHandle, device);
5190 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5191 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5192 inputCmd.toString(),
5193 delayMs);
5194 }
5195 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005196 }
Eric Laurente552edb2014-03-10 17:42:56 -07005197
5198 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005199 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005200
5201 return muteWaitMs;
5202}
5203
Eric Laurentc75307b2015-03-17 15:29:32 -07005204status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 int delayMs,
5206 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005207{
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 ssize_t index;
5209 if (patchHandle) {
5210 index = mAudioPatches.indexOfKey(*patchHandle);
5211 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005212 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 }
5214 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005215 return INVALID_OPERATION;
5216 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5218 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005219 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005220 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 removeAudioPatch(patchDesc->mHandle);
5222 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005223 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005224 return status;
5225}
5226
5227status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5228 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 bool force,
5230 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005231{
5232 status_t status = NO_ERROR;
5233
Eric Laurent1f2f2232014-06-02 12:01:23 -07005234 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005235 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5236 inputDesc->mDevice = device;
5237
Mikhail Naganov708e0382018-05-30 09:53:04 -07005238 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005239 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005240 PatchBuilder patchBuilder;
5241 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005242 // AUDIO_SOURCE_HOTWORD is for internal use only:
5243 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005244 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5245 auto result = usecase;
5246 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5247 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5248 }
5249 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005250 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005251 addSource(deviceList.itemAt(0));
5252 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005253 }
5254 }
5255 return status;
5256}
5257
Eric Laurent6a94d692014-05-20 11:18:06 -07005258status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5259 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005260{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005261 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 ssize_t index;
5263 if (patchHandle) {
5264 index = mAudioPatches.indexOfKey(*patchHandle);
5265 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005266 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 }
5268 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005269 return INVALID_OPERATION;
5270 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5272 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005273 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005274 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 removeAudioPatch(patchDesc->mHandle);
5276 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005277 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005278 return status;
5279}
5280
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005281sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005282 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005283 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005284 audio_format_t& format,
5285 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005286 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005287{
5288 // Choose an input profile based on the requested capture parameters: select the first available
5289 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005290 //
5291 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5292 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005293
Glenn Kasten730b9262018-03-29 15:01:26 -07005294 sp<IOProfile> firstInexact;
5295 uint32_t updatedSamplingRate = 0;
5296 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5297 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005298 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005299 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005300 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005301 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005302 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005303 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005304 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005305 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005306 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005307 &channelMask /*updatedChannelMask*/,
5308 // FIXME ugly cast
5309 (audio_output_flags_t) flags,
5310 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005311 return profile;
5312 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005313 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5314 samplingRate,
5315 &updatedSamplingRate,
5316 format,
5317 &updatedFormat,
5318 channelMask,
5319 &updatedChannelMask,
5320 // FIXME ugly cast
5321 (audio_output_flags_t) flags,
5322 false /*exactMatchRequiredForInputFlags*/)) {
5323 firstInexact = profile;
5324 }
5325
Eric Laurente552edb2014-03-10 17:42:56 -07005326 }
5327 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005328 if (firstInexact != nullptr) {
5329 samplingRate = updatedSamplingRate;
5330 format = updatedFormat;
5331 channelMask = updatedChannelMask;
5332 return firstInexact;
5333 }
Eric Laurente552edb2014-03-10 17:42:56 -07005334 return NULL;
5335}
5336
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005337
5338audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005339 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005340{
François Gaffie036e1e92015-03-19 10:16:24 +01005341 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5342 audio_devices_t selectedDeviceFromMix =
5343 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005344
François Gaffie036e1e92015-03-19 10:16:24 +01005345 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5346 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005347 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005348 return getDeviceForInputSource(inputSource);
5349}
5350
5351audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5352{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005353 // Routing
5354 // Scan the whole RouteMap to see if we have an explicit route:
5355 // if the input source in the RouteMap is the same as the argument above,
5356 // and activity count is non-zero and the device in the route descriptor is available
5357 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005358 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5359 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005360 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005361 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005362 return route->mDeviceDescriptor->type();
5363 }
5364 }
5365
5366 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005367}
5368
Eric Laurente0720872014-03-11 09:30:41 -07005369float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005370 int index,
5371 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005372{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005373 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005374
5375 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5376 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5377 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5378 // the ringtone volume
5379 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5380 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5381 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5382 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5383 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5384 }
5385
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005386 // in-call: always cap volume by voice volume + some low headroom
5387 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005388 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005389 switch (stream) {
5390 case AUDIO_STREAM_SYSTEM:
5391 case AUDIO_STREAM_RING:
5392 case AUDIO_STREAM_MUSIC:
5393 case AUDIO_STREAM_ALARM:
5394 case AUDIO_STREAM_NOTIFICATION:
5395 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5396 case AUDIO_STREAM_DTMF:
5397 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005398 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005399 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005400 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005401 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005402 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005403 if (volumeDB > maxVoiceVolDb) {
5404 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5405 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5406 volumeDB = maxVoiceVolDb;
5407 }
5408 } break;
5409 default:
5410 break;
5411 }
5412 }
5413
Eric Laurente552edb2014-03-10 17:42:56 -07005414 // if a headset is connected, apply the following rules to ring tones and notifications
5415 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005416 // - always attenuate notifications volume by 6dB
5417 // - attenuate ring tones volume by 6dB unless music is not playing and
5418 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005419 // - if music is playing, always limit the volume to current music volume,
5420 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005421 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005422 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5423 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5424 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005425 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005426 AUDIO_DEVICE_OUT_USB_HEADSET |
5427 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005428 ((stream_strategy == STRATEGY_SONIFICATION)
5429 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005430 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005431 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005432 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005433 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005434 // when the phone is ringing we must consider that music could have been paused just before
5435 // by the music application and behave as if music was active if the last music track was
5436 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005437 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005438 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005439 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005440 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005441 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005442 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5443 musicDevice),
5444 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005445 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5446 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005447 if (volumeDB > minVolDB) {
5448 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005449 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005450 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005451 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5452 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5453 // on A2DP, also ensure notification volume is not too low compared to media when
5454 // intended to be played
5455 if ((volumeDB > -96.0f) &&
5456 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5457 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5458 stream, device,
5459 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5460 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5461 }
5462 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005463 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5464 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005465 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005466 }
5467 }
5468
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005469 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005470}
5471
Eric Laurent3839bc02018-07-10 18:33:34 -07005472int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5473 audio_stream_type_t srcStream,
5474 audio_stream_type_t dstStream)
5475{
5476 if (srcStream == dstStream) {
5477 return srcIndex;
5478 }
5479 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5480 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5481 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5482 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5483
5484 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5485}
5486
Eric Laurente0720872014-03-11 09:30:41 -07005487status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005488 int index,
5489 const sp<AudioOutputDescriptor>& outputDesc,
5490 audio_devices_t device,
5491 int delayMs,
5492 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005493{
Eric Laurente552edb2014-03-10 17:42:56 -07005494 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005495 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005496 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005497 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005498 return NO_ERROR;
5499 }
François Gaffie2110e042015-03-24 08:41:51 +01005500 audio_policy_forced_cfg_t forceUseForComm =
5501 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005502 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005503 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5504 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005505 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005506 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005507 return INVALID_OPERATION;
5508 }
5509
Eric Laurentc75307b2015-03-17 15:29:32 -07005510 if (device == AUDIO_DEVICE_NONE) {
5511 device = outputDesc->device();
5512 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005513
Eric Laurentffbc80f2015-03-18 18:30:19 -07005514 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005515 if (outputDesc->isFixedVolume(device) ||
5516 // Force VoIP volume to max for bluetooth SCO
5517 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5518 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005519 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005520 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005521
Eric Laurentffbc80f2015-03-18 18:30:19 -07005522 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005523
Eric Laurent3b73df72014-03-11 09:06:29 -07005524 if (stream == AUDIO_STREAM_VOICE_CALL ||
5525 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005526 float voiceVolume;
5527 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005528 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005529 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005530 } else {
5531 voiceVolume = 1.0;
5532 }
5533
Eric Laurent18fba842016-03-31 14:41:26 -07005534 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005535 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5536 mLastVoiceVolume = voiceVolume;
5537 }
5538 }
5539
5540 return NO_ERROR;
5541}
5542
Eric Laurentc75307b2015-03-17 15:29:32 -07005543void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5544 audio_devices_t device,
5545 int delayMs,
5546 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005547{
Eric Laurentc75307b2015-03-17 15:29:32 -07005548 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005549
Eric Laurent794fde22016-03-11 09:50:45 -08005550 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005551 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005552 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005553 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005554 device,
5555 delayMs,
5556 force);
5557 }
5558}
5559
Eric Laurente0720872014-03-11 09:30:41 -07005560void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005561 bool on,
5562 const sp<AudioOutputDescriptor>& outputDesc,
5563 int delayMs,
5564 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005565{
Eric Laurent72249d52015-06-08 11:12:15 -07005566 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5567 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005568 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005569 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005570 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005571 }
5572 }
5573}
5574
Eric Laurente0720872014-03-11 09:30:41 -07005575void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005576 bool on,
5577 const sp<AudioOutputDescriptor>& outputDesc,
5578 int delayMs,
5579 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005580{
Eric Laurente552edb2014-03-10 17:42:56 -07005581 if (device == AUDIO_DEVICE_NONE) {
5582 device = outputDesc->device();
5583 }
5584
Eric Laurentc75307b2015-03-17 15:29:32 -07005585 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5586 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005587
5588 if (on) {
5589 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005590 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005592 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005593 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005594 }
5595 }
5596 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5597 outputDesc->mMuteCount[stream]++;
5598 } else {
5599 if (outputDesc->mMuteCount[stream] == 0) {
5600 ALOGV("setStreamMute() unmuting non muted stream!");
5601 return;
5602 }
5603 if (--outputDesc->mMuteCount[stream] == 0) {
5604 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005605 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005606 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005607 device,
5608 delayMs);
5609 }
5610 }
5611}
5612
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005613audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5614{
5615 // flags to stream type mapping
5616 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5617 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5618 }
5619 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5620 return AUDIO_STREAM_BLUETOOTH_SCO;
5621 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005622 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5623 return AUDIO_STREAM_TTS;
5624 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005625
5626 // usage to stream type mapping
5627 switch (attr->usage) {
5628 case AUDIO_USAGE_MEDIA:
5629 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005630 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005631 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5632 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005633 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5634 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005635 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5636 return AUDIO_STREAM_SYSTEM;
5637 case AUDIO_USAGE_VOICE_COMMUNICATION:
5638 return AUDIO_STREAM_VOICE_CALL;
5639
5640 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5641 return AUDIO_STREAM_DTMF;
5642
5643 case AUDIO_USAGE_ALARM:
5644 return AUDIO_STREAM_ALARM;
5645 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5646 return AUDIO_STREAM_RING;
5647
5648 case AUDIO_USAGE_NOTIFICATION:
5649 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5650 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5651 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5652 case AUDIO_USAGE_NOTIFICATION_EVENT:
5653 return AUDIO_STREAM_NOTIFICATION;
5654
5655 case AUDIO_USAGE_UNKNOWN:
5656 default:
5657 return AUDIO_STREAM_MUSIC;
5658 }
5659}
Eric Laurente83b55d2014-11-14 10:06:21 -08005660
François Gaffie53615e22015-03-19 09:24:12 +01005661bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5662{
Eric Laurente83b55d2014-11-14 10:06:21 -08005663 // has flags that map to a strategy?
5664 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5665 return true;
5666 }
5667
5668 // has known usage?
5669 switch (paa->usage) {
5670 case AUDIO_USAGE_UNKNOWN:
5671 case AUDIO_USAGE_MEDIA:
5672 case AUDIO_USAGE_VOICE_COMMUNICATION:
5673 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5674 case AUDIO_USAGE_ALARM:
5675 case AUDIO_USAGE_NOTIFICATION:
5676 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5677 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5678 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5679 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5680 case AUDIO_USAGE_NOTIFICATION_EVENT:
5681 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5682 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5683 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5684 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005685 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005686 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005687 break;
5688 default:
5689 return false;
5690 }
5691 return true;
5692}
5693
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005694bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005695 routing_strategy strategy, uint32_t inPastMs,
5696 nsecs_t sysTime) const
5697{
5698 if ((sysTime == 0) && (inPastMs != 0)) {
5699 sysTime = systemTime();
5700 }
Eric Laurent794fde22016-03-11 09:50:45 -08005701 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005702 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5703 (NUM_STRATEGIES == strategy)) &&
5704 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5705 return true;
5706 }
5707 }
5708 return false;
5709}
5710
Eric Laurent484e9272018-06-07 17:29:23 -07005711bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5712 routing_strategy strategy, uint32_t inPastMs,
5713 nsecs_t sysTime) const
5714{
5715 for (size_t i = 0; i < mOutputs.size(); i++) {
5716 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5717 if (outputDesc->sharesHwModuleWith(desc)
5718 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5719 return true;
5720 }
5721 }
5722 return false;
5723}
5724
François Gaffie2110e042015-03-24 08:41:51 +01005725audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5726{
5727 return mEngine->getForceUse(usage);
5728}
5729
5730bool AudioPolicyManager::isInCall()
5731{
5732 return isStateInCall(mEngine->getPhoneState());
5733}
5734
5735bool AudioPolicyManager::isStateInCall(int state)
5736{
5737 return is_state_in_call(state);
5738}
5739
Eric Laurentd60560a2015-04-10 11:31:20 -07005740void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5741{
5742 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5743 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5744 if (sourceDesc->mDevice->equals(deviceDesc)) {
5745 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5746 stopAudioSource(sourceDesc->getHandle());
5747 }
5748 }
5749
5750 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5751 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5752 bool release = false;
5753 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5754 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5755 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5756 source->ext.device.type == deviceDesc->type()) {
5757 release = true;
5758 }
5759 }
5760 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5761 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5762 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5763 sink->ext.device.type == deviceDesc->type()) {
5764 release = true;
5765 }
5766 }
5767 if (release) {
5768 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5769 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5770 }
5771 }
5772}
5773
Phil Burk09bc4612016-02-24 15:58:15 -08005774// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005775void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5776 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005777 // TODO Set this based on Config properties.
5778 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005779
5780 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5781 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005782 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005783
jiabin81772902018-04-02 17:52:27 -07005784 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5785 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5786 formats.clear();
5787 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5788 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005789 }
jiabin81772902018-04-02 17:52:27 -07005790 // Always enable IEC61937 when in MANUAL mode.
5791 formats.add(AUDIO_FORMAT_IEC61937);
5792 } else { // NEVER, AUTO or ALWAYS
5793 // Analyze original support for various formats.
5794 bool supportsAC3 = false;
5795 bool supportsOtherSurround = false;
5796 bool supportsIEC61937 = false;
5797 mSurroundFormats.clear();
5798 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5799 audio_format_t format = formats[formatIndex];
5800 switch (format) {
5801 case AUDIO_FORMAT_AC3:
5802 supportsAC3 = true;
5803 break;
5804 case AUDIO_FORMAT_E_AC3:
5805 case AUDIO_FORMAT_DTS:
5806 case AUDIO_FORMAT_DTS_HD:
5807 // If ALWAYS, remove all other surround formats here
5808 // since we will add them later.
5809 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5810 formats.removeAt(formatIndex);
5811 formatIndex--;
5812 }
5813 supportsOtherSurround = true;
5814 break;
5815 case AUDIO_FORMAT_IEC61937:
5816 supportsIEC61937 = true;
5817 break;
5818 default:
5819 break;
5820 }
5821 }
Phil Burk09bc4612016-02-24 15:58:15 -08005822
jiabin81772902018-04-02 17:52:27 -07005823 // Modify formats based on surround preferences.
5824 // If NEVER, remove support for surround formats.
5825 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5826 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5827 // Remove surround sound related formats.
5828 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5829 audio_format_t format = formats[formatIndex];
5830 switch(format) {
5831 case AUDIO_FORMAT_AC3:
5832 case AUDIO_FORMAT_E_AC3:
5833 case AUDIO_FORMAT_DTS:
5834 case AUDIO_FORMAT_DTS_HD:
5835 case AUDIO_FORMAT_IEC61937:
5836 formats.removeAt(formatIndex);
5837 break;
5838 default:
5839 formatIndex++; // keep it
5840 break;
5841 }
5842 }
5843 supportsAC3 = false;
5844 supportsOtherSurround = false;
5845 supportsIEC61937 = false;
5846 }
5847 } else { // AUTO or ALWAYS
5848 // Most TVs support AC3 even if they do not report it in the EDID.
5849 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5850 && !supportsAC3) {
5851 formats.add(AUDIO_FORMAT_AC3);
5852 supportsAC3 = true;
5853 }
5854
5855 // If ALWAYS, add support for raw surround formats if all are missing.
5856 // This assumes that if any of these formats are reported by the HAL
5857 // then the report is valid and should not be modified.
5858 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5859 formats.add(AUDIO_FORMAT_E_AC3);
5860 formats.add(AUDIO_FORMAT_DTS);
5861 formats.add(AUDIO_FORMAT_DTS_HD);
5862 supportsOtherSurround = true;
5863 }
5864
5865 // Add support for IEC61937 if any raw surround supported.
5866 // The HAL could do this but add it here, just in case.
5867 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5868 formats.add(AUDIO_FORMAT_IEC61937);
5869 supportsIEC61937 = true;
5870 }
5871
5872 // Add reported surround sound formats to enabled surround formats.
5873 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005874 audio_format_t format = formats[formatIndex];
5875 switch(format) {
5876 case AUDIO_FORMAT_AC3:
5877 case AUDIO_FORMAT_E_AC3:
5878 case AUDIO_FORMAT_DTS:
5879 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005880 case AUDIO_FORMAT_AAC_LC:
5881 case AUDIO_FORMAT_DOLBY_TRUEHD:
5882 case AUDIO_FORMAT_E_AC3_JOC:
5883 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005884 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005885 break;
5886 }
Phil Burk09bc4612016-02-24 15:58:15 -08005887 }
Phil Burk07ac1142016-03-25 13:39:29 -07005888 }
Phil Burk09bc4612016-02-24 15:58:15 -08005889 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005890}
5891
5892// Modify the list of channel masks supported.
5893void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5894 ChannelsVector &channelMasks = *channelMasksPtr;
5895 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5896 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5897
5898 // If NEVER, then remove support for channelMasks > stereo.
5899 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5900 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5901 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5902 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5903 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5904 channelMasks.removeAt(maskIndex);
5905 } else {
5906 maskIndex++;
5907 }
5908 }
jiabin81772902018-04-02 17:52:27 -07005909 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5910 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5911 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005912 bool supports5dot1 = false;
5913 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005914 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005915 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5916 supports5dot1 = true;
5917 break;
5918 }
5919 }
5920 // If not then add 5.1 support.
5921 if (!supports5dot1) {
5922 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5923 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5924 }
Phil Burk09bc4612016-02-24 15:58:15 -08005925 }
5926}
5927
Phil Burk00eeb322016-03-31 12:41:00 -07005928void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5929 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005930 AudioProfileVector &profiles)
5931{
5932 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005933
François Gaffie112b0af2015-11-19 16:13:25 +01005934 // Format MUST be checked first to update the list of AudioProfile
5935 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005936 reply = mpClientInterface->getParameters(
5937 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005938 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005939 AudioParameter repliedParameters(reply);
5940 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005941 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005942 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5943 return;
5944 }
Phil Burk09bc4612016-02-24 15:58:15 -08005945 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005946 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005947 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005948 }
Phil Burk09bc4612016-02-24 15:58:15 -08005949 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005950 }
François Gaffie112b0af2015-11-19 16:13:25 +01005951
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005952 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005953 ChannelsVector channelMasks;
5954 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005955 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005956 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005957
5958 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005959 reply = mpClientInterface->getParameters(
5960 ioHandle,
5961 requestedParameters.toString() + ";" +
5962 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005963 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005964 AudioParameter repliedParameters(reply);
5965 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005966 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005967 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005968 }
5969 }
5970 if (profiles.hasDynamicChannelsFor(format)) {
5971 reply = mpClientInterface->getParameters(ioHandle,
5972 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005973 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005974 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005975 AudioParameter repliedParameters(reply);
5976 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005977 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005978 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005979 if (device == AUDIO_DEVICE_OUT_HDMI) {
5980 filterSurroundChannelMasks(&channelMasks);
5981 }
François Gaffie112b0af2015-11-19 16:13:25 +01005982 }
5983 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005984 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005985 }
5986}
Eric Laurentd60560a2015-04-10 11:31:20 -07005987
Mikhail Naganovdc769682018-05-04 15:34:08 -07005988status_t AudioPolicyManager::installPatch(const char *caller,
5989 audio_patch_handle_t *patchHandle,
5990 AudioIODescriptorInterface *ioDescriptor,
5991 const struct audio_patch *patch,
5992 int delayMs)
5993{
5994 ssize_t index = mAudioPatches.indexOfKey(
5995 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5996 *patchHandle : ioDescriptor->getPatchHandle());
5997 sp<AudioPatch> patchDesc;
5998 status_t status = installPatch(
5999 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6000 if (status == NO_ERROR) {
6001 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6002 }
6003 return status;
6004}
6005
6006status_t AudioPolicyManager::installPatch(const char *caller,
6007 ssize_t index,
6008 audio_patch_handle_t *patchHandle,
6009 const struct audio_patch *patch,
6010 int delayMs,
6011 uid_t uid,
6012 sp<AudioPatch> *patchDescPtr)
6013{
6014 sp<AudioPatch> patchDesc;
6015 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6016 if (index >= 0) {
6017 patchDesc = mAudioPatches.valueAt(index);
6018 afPatchHandle = patchDesc->mAfPatchHandle;
6019 }
6020
6021 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6022 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6023 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6024 if (status == NO_ERROR) {
6025 if (index < 0) {
6026 patchDesc = new AudioPatch(patch, uid);
6027 addAudioPatch(patchDesc->mHandle, patchDesc);
6028 } else {
6029 patchDesc->mPatch = *patch;
6030 }
6031 patchDesc->mAfPatchHandle = afPatchHandle;
6032 if (patchHandle) {
6033 *patchHandle = patchDesc->mHandle;
6034 }
6035 nextAudioPortGeneration();
6036 mpClientInterface->onAudioPatchListUpdate();
6037 }
6038 if (patchDescPtr) *patchDescPtr = patchDesc;
6039 return status;
6040}
6041
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006042} // namespace android