blob: a16b12340e0d0a93be7a1fc2be1a891c6e01d527 [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"
François Gaffief4ad6e52015-11-19 16:59:57 +010029
Eric Laurentd4692962014-05-05 18:13:44 -070030#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070031#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070032
François Gaffie2110e042015-03-24 08:41:51 +010033#include <AudioPolicyManagerInterface.h>
34#include <AudioPolicyEngineInstance.h>
Mathias Agopian05d19b02017-02-28 16:28:19 -080035#include <cutils/atomic.h>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070041#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070042#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010045#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010047#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010048#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010049#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010050#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurent3b73df72014-03-11 09:06:29 -070052namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurentdc462862016-07-19 12:29:53 -070054//FIXME: workaround for truncated touch sounds
55// to be removed when the problem is handled by system UI
56#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070057
58// Largest difference in dB on earpiece in call between the voice volume and another
59// media / notification / system volume.
60constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
61
Eric Laurente552edb2014-03-10 17:42:56 -070062// ----------------------------------------------------------------------------
63// AudioPolicyInterface implementation
64// ----------------------------------------------------------------------------
65
Eric Laurente0720872014-03-11 09:30:41 -070066status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080067 audio_policy_dev_state_t state,
68 const char *device_address,
69 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070070{
Paul McLeane743a472015-01-28 11:07:31 -080071 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080072}
73
François Gaffie44481e72016-04-20 07:49:57 +020074void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
75 audio_policy_dev_state_t state,
76 const String8 &device_address)
77{
78 AudioParameter param(device_address);
79 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070080 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020081 param.addInt(key, device);
82 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
83}
84
Eric Laurentc73ca6e2014-12-12 14:34:22 -080085status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080086 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080087 const char *device_address,
88 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089{
Paul McLeane743a472015-01-28 11:07:31 -080090 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
91- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070092
93 // connect/disconnect only 1 device at a time
94 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
95
François Gaffie53615e22015-03-19 09:24:12 +010096 sp<DeviceDescriptor> devDesc =
97 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080098
Eric Laurente552edb2014-03-10 17:42:56 -070099 // handle output devices
100 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700101 SortedVector <audio_io_handle_t> outputs;
102
Eric Laurent3a4311c2014-03-17 12:00:47 -0700103 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
104
Eric Laurente552edb2014-03-10 17:42:56 -0700105 // save a copy of the opened output descriptors before any output is opened or closed
106 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
107 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700108 switch (state)
109 {
110 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800111 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700113 ALOGW("setDeviceConnectionState() device already connected: %x", device);
114 return INVALID_OPERATION;
115 }
116 ALOGV("setDeviceConnectionState() connecting device %x", device);
117
Eric Laurente552edb2014-03-10 17:42:56 -0700118 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700119 index = mAvailableOutputDevices.add(devDesc);
120 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700122 if (module == 0) {
123 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
124 device);
125 mAvailableOutputDevices.remove(devDesc);
126 return INVALID_OPERATION;
127 }
Paul McLeane743a472015-01-28 11:07:31 -0800128 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 } else {
130 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 }
132
François Gaffie44481e72016-04-20 07:49:57 +0200133 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
134 // parameters on newly connected devices (instead of opening the outputs...)
135 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
136
Eric Laurenta1d525f2015-01-29 13:36:45 -0800137 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700138 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200139
140 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
141 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700142 return INVALID_OPERATION;
143 }
François Gaffie2110e042015-03-24 08:41:51 +0100144 // Propagate device availability to Engine
145 mEngine->setDeviceConnectionState(devDesc, state);
146
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700147 // outputs should never be empty here
148 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
149 "checkOutputsForDevice() returned no outputs but status OK");
150 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
151 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800152
Eric Laurent3ae5f312015-02-03 17:12:08 -0800153 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700154 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700155 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700157 ALOGW("setDeviceConnectionState() device not connected: %x", device);
158 return INVALID_OPERATION;
159 }
160
Paul McLean5c477aa2014-08-20 16:47:57 -0700161 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
162
Paul McLeane743a472015-01-28 11:07:31 -0800163 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200164 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700165
Eric Laurente552edb2014-03-10 17:42:56 -0700166 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700167 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700168
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100170
171 // Propagate device availability to Engine
172 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700173 } break;
174
175 default:
176 ALOGE("setDeviceConnectionState() invalid state: %x", state);
177 return BAD_VALUE;
178 }
179
Eric Laurent3a4311c2014-03-17 12:00:47 -0700180 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
181 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700182 checkA2dpSuspend();
183 checkOutputForAllStrategies();
184 // outputs must be closed after checkOutputForAllStrategies() is executed
185 if (!outputs.isEmpty()) {
186 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700187 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // close unused outputs after device disconnection or direct outputs that have been
189 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700191 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
192 (desc->mDirectOpenCount == 0))) {
193 closeOutput(outputs[i]);
194 }
195 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196 // check again after closing A2DP output to reset mA2dpSuspended if needed
197 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700198 }
199
200 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700201 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
203 updateCallRouting(newDevice);
204 }
Eric Laurente552edb2014-03-10 17:42:56 -0700205 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700206 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
207 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
208 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700209 // do not force device change on duplicated output because if device is 0, it will
210 // also force a device 0 for the two outputs it is duplicated to which may override
211 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700212 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100213 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700214 // always force when disconnecting (a non-duplicated device)
215 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700216 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 }
Eric Laurente552edb2014-03-10 17:42:56 -0700218 }
219
Eric Laurentd60560a2015-04-10 11:31:20 -0700220 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
221 cleanUpForDevice(devDesc);
222 }
223
Eric Laurent72aa32f2014-05-30 18:51:48 -0700224 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700225 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700226 } // end if is output device
227
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle input devices
229 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700230 SortedVector <audio_io_handle_t> inputs;
231
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700233 switch (state)
234 {
235 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700236 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700238 ALOGW("setDeviceConnectionState() device already connected: %d", device);
239 return INVALID_OPERATION;
240 }
François Gaffie53615e22015-03-19 09:24:12 +0100241 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700242 if (module == NULL) {
243 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
244 device);
245 return INVALID_OPERATION;
246 }
François Gaffie44481e72016-04-20 07:49:57 +0200247
248 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
249 // parameters on newly connected devices (instead of opening the inputs...)
250 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
251
Paul McLean9080a4c2015-06-18 08:24:02 -0700252 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200253 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
254 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700255 return INVALID_OPERATION;
256 }
257
Eric Laurent3a4311c2014-03-17 12:00:47 -0700258 index = mAvailableInputDevices.add(devDesc);
259 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800260 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 } else {
262 return NO_MEMORY;
263 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800264
François Gaffie2110e042015-03-24 08:41:51 +0100265 // Propagate device availability to Engine
266 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700267 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700268
269 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700270 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700271 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700272 ALOGW("setDeviceConnectionState() device not connected: %d", device);
273 return INVALID_OPERATION;
274 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700275
276 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
277
278 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200279 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700280
Paul McLean9080a4c2015-06-18 08:24:02 -0700281 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700283
François Gaffie2110e042015-03-24 08:41:51 +0100284 // Propagate device availability to Engine
285 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700286 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700287
288 default:
289 ALOGE("setDeviceConnectionState() invalid state: %x", state);
290 return BAD_VALUE;
291 }
292
Eric Laurentd4692962014-05-05 18:13:44 -0700293 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700294 // As the input device list can impact the output device selection, update
295 // getDeviceForStrategy() cache
296 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700297
Eric Laurent87ffa392015-05-22 10:32:38 -0700298 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700299 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
300 updateCallRouting(newDevice);
301 }
302
Eric Laurentd60560a2015-04-10 11:31:20 -0700303 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
304 cleanUpForDevice(devDesc);
305 }
306
Eric Laurentb52c1522014-05-20 11:27:36 -0700307 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700308 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700309 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700310
311 ALOGW("setDeviceConnectionState() invalid device: %x", device);
312 return BAD_VALUE;
313}
314
Eric Laurente0720872014-03-11 09:30:41 -0700315audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100316 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700317{
Eric Laurent634b7142016-04-20 13:48:02 -0700318 sp<DeviceDescriptor> devDesc =
319 mHwModules.getDeviceDescriptor(device, device_address, "",
320 (strlen(device_address) != 0)/*matchAddress*/);
321
322 if (devDesc == 0) {
323 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
324 device, device_address);
325 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
326 }
François Gaffie53615e22015-03-19 09:24:12 +0100327
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 DeviceVector *deviceVector;
329
Eric Laurente552edb2014-03-10 17:42:56 -0700330 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700331 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700332 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 deviceVector = &mAvailableInputDevices;
334 } else {
335 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
336 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700337 }
Eric Laurent634b7142016-04-20 13:48:02 -0700338
339 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
340 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800341}
342
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800343status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
344 const char *device_address,
345 const char *device_name)
346{
347 status_t status;
348
349 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
350 device, device_address, device_name);
351
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800352 // connect/disconnect only 1 device at a time
353 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
354
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800355 // Check if the device is currently connected
356 sp<DeviceDescriptor> devDesc =
357 mHwModules.getDeviceDescriptor(device, device_address, device_name);
358 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
359 if (index < 0) {
360 // Nothing to do: device is not connected
361 return NO_ERROR;
362 }
363
364 // Toggle the device state: UNAVAILABLE -> AVAILABLE
365 // This will force reading again the device configuration
366 status = setDeviceConnectionState(device,
367 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
368 device_address, device_name);
369 if (status != NO_ERROR) {
370 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
371 status);
372 return status;
373 }
374
375 status = setDeviceConnectionState(device,
376 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
377 device_address, device_name);
378 if (status != NO_ERROR) {
379 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
380 status);
381 return status;
382 }
383
384 return NO_ERROR;
385}
386
Eric Laurentdc462862016-07-19 12:29:53 -0700387uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700388{
389 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700390 status_t status;
391 audio_patch_handle_t afPatchHandle;
392 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700393 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700394
Andy Hunga76c7de2016-12-13 19:14:31 -0800395 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700396 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700397 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800398 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700399 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
400
401 // release existing RX patch if any
402 if (mCallRxPatch != 0) {
403 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
404 mCallRxPatch.clear();
405 }
406 // release TX patch if any
407 if (mCallTxPatch != 0) {
408 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
409 mCallTxPatch.clear();
410 }
411
412 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
413 // via setOutputDevice() on primary output.
414 // Otherwise, create two audio patches for TX and RX path.
415 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700416 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700417 // If the TX device is also on the primary HW module, setOutputDevice() will take care
418 // of it due to legacy implementation. If not, create a patch.
419 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
420 == AUDIO_DEVICE_NONE) {
421 createTxPatch = true;
422 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700423 } else { // create RX path audio patch
424 struct audio_patch patch;
425
426 patch.num_sources = 1;
427 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700428 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
429 ALOG_ASSERT(!deviceList.isEmpty(),
430 "updateCallRouting() selected device not in output device list");
431 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
432 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
433 ALOG_ASSERT(!deviceList.isEmpty(),
434 "updateCallRouting() no telephony RX device");
435 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
436
437 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
438 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
439
440 // request to reuse existing output stream if one is already opened to reach the RX device
441 SortedVector<audio_io_handle_t> outputs =
442 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700443 audio_io_handle_t output = selectOutput(outputs,
444 AUDIO_OUTPUT_FLAG_NONE,
445 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700447 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700448 ALOG_ASSERT(!outputDesc->isDuplicated(),
449 "updateCallRouting() RX device output is duplicated");
450 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700451 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700452 patch.num_sources = 2;
453 }
454
455 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700456 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
458 status);
459 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100460 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 mCallRxPatch->mAfPatchHandle = afPatchHandle;
462 mCallRxPatch->mUid = mUidCached;
463 }
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700467 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700468
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469 patch.num_sources = 1;
470 patch.num_sinks = 1;
471 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
472 ALOG_ASSERT(!deviceList.isEmpty(),
473 "updateCallRouting() selected device not in input device list");
474 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
475 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
476 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
477 ALOG_ASSERT(!deviceList.isEmpty(),
478 "updateCallRouting() no telephony TX device");
479 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
480 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
481
482 SortedVector<audio_io_handle_t> outputs =
483 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700484 audio_io_handle_t output = selectOutput(outputs,
485 AUDIO_OUTPUT_FLAG_NONE,
486 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487 // request to reuse existing output stream if one is already opened to reach the TX
488 // path output device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "updateCallRouting() RX device output is duplicated");
493 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700494 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700495 patch.num_sources = 2;
496 }
497
Eric Laurentc0a889f2015-10-14 14:36:34 -0700498 // terminate active capture if on the same HW module as the call TX source device
499 // FIXME: would be better to refine to only inputs whose profile connects to the
500 // call TX device but this information is not in the audio patch and logic here must be
501 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
503 for (size_t i = 0; i < activeInputs.size(); i++) {
504 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
505 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
506 AudioSessionCollection activeSessions =
507 activeDesc->getAudioSessions(true /*activeOnly*/);
508 for (size_t j = 0; j < activeSessions.size(); j++) {
509 audio_session_t activeSession = activeSessions.keyAt(j);
510 stopInput(activeDesc->mIoHandle, activeSession);
511 releaseInput(activeDesc->mIoHandle, activeSession);
512 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700513 }
514 }
515
Eric Laurentc2730ba2014-07-20 15:47:07 -0700516 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700517 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700518 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
519 status);
520 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100521 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700522 mCallTxPatch->mAfPatchHandle = afPatchHandle;
523 mCallTxPatch->mUid = mUidCached;
524 }
525 }
Eric Laurentdc462862016-07-19 12:29:53 -0700526
527 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528}
529
Eric Laurente0720872014-03-11 09:30:41 -0700530void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700531{
532 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100533 // store previous phone state for management of sonification strategy below
534 int oldState = mEngine->getPhoneState();
535
536 if (mEngine->setPhoneState(state) != NO_ERROR) {
537 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700538 return;
539 }
François Gaffie2110e042015-03-24 08:41:51 +0100540 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700541 // if leaving call state, handle special case of active streams
542 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700543 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700544 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800545 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700546 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700547 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800548
Eric Laurent63dea1d2015-07-02 17:10:28 -0700549 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800550 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700551 }
552
François Gaffie2110e042015-03-24 08:41:51 +0100553 /**
554 * Switching to or from incall state or switching between telephony and VoIP lead to force
555 * routing command.
556 */
557 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
558 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700559
560 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700561 checkA2dpSuspend();
562 checkOutputForAllStrategies();
563 updateDevicesAndOutputs();
564
Eric Laurente552edb2014-03-10 17:42:56 -0700565 int delayMs = 0;
566 if (isStateInCall(state)) {
567 nsecs_t sysTime = systemTime();
568 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700569 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700570 // mute media and sonification strategies and delay device switch by the largest
571 // latency of any output where either strategy is active.
572 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100573 if ((isStrategyActive(desc, STRATEGY_MEDIA,
574 SONIFICATION_HEADSET_MUSIC_DELAY,
575 sysTime) ||
576 isStrategyActive(desc, STRATEGY_SONIFICATION,
577 SONIFICATION_HEADSET_MUSIC_DELAY,
578 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 (delayMs < (int)desc->latency()*2)) {
580 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700581 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 setStrategyMute(STRATEGY_MEDIA, true, desc);
583 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700584 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700585 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
586 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700587 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
588 }
589 }
590
Eric Laurent87ffa392015-05-22 10:32:38 -0700591 if (hasPrimaryOutput()) {
592 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
593 // the device returned is not necessarily reachable via this output
594 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
595 // force routing command to audio hardware when ending call
596 // even if no device change is needed
597 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
598 rxDevice = mPrimaryOutput->device();
599 }
Eric Laurente552edb2014-03-10 17:42:56 -0700600
Eric Laurent87ffa392015-05-22 10:32:38 -0700601 if (state == AUDIO_MODE_IN_CALL) {
602 updateCallRouting(rxDevice, delayMs);
603 } else if (oldState == AUDIO_MODE_IN_CALL) {
604 if (mCallRxPatch != 0) {
605 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
606 mCallRxPatch.clear();
607 }
608 if (mCallTxPatch != 0) {
609 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
610 mCallTxPatch.clear();
611 }
612 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
613 } else {
614 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700615 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616 }
Eric Laurente552edb2014-03-10 17:42:56 -0700617 // if entering in call state, handle special case of active streams
618 // pertaining to sonification strategy see handleIncallSonification()
619 if (isStateInCall(state)) {
620 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800621 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700622 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700623 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700624
625 // force reevaluating accessibility routing when call starts
626 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700627 }
628
629 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700630 if (state == AUDIO_MODE_RINGTONE &&
631 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700632 mLimitRingtoneVolume = true;
633 } else {
634 mLimitRingtoneVolume = false;
635 }
636}
637
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700638audio_mode_t AudioPolicyManager::getPhoneState() {
639 return mEngine->getPhoneState();
640}
641
Eric Laurente0720872014-03-11 09:30:41 -0700642void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700643 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700644{
François Gaffie2110e042015-03-24 08:41:51 +0100645 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700646 if (config == mEngine->getForceUse(usage)) {
647 return;
648 }
Eric Laurente552edb2014-03-10 17:42:56 -0700649
François Gaffie2110e042015-03-24 08:41:51 +0100650 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
651 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
652 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700653 }
François Gaffie2110e042015-03-24 08:41:51 +0100654 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
655 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
656 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700657
658 // check for device and output changes triggered by new force usage
659 checkA2dpSuspend();
660 checkOutputForAllStrategies();
661 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800662
Eric Laurentdc462862016-07-19 12:29:53 -0700663 //FIXME: workaround for truncated touch sounds
664 // to be removed when the problem is handled by system UI
665 uint32_t delayMs = 0;
666 uint32_t waitMs = 0;
667 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
668 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
669 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700670 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700672 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673 }
Eric Laurente552edb2014-03-10 17:42:56 -0700674 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
676 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
677 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700678 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
679 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700680 }
Eric Laurente552edb2014-03-10 17:42:56 -0700681 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700682 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700683 }
684 }
685
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
687 for (size_t i = 0; i < activeInputs.size(); i++) {
688 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
689 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700690 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800691 if (activeDesc->mProfile->getSupportedDevices().types() &
692 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
693 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700694 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800695 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700696 }
Eric Laurente552edb2014-03-10 17:42:56 -0700697 }
Eric Laurente552edb2014-03-10 17:42:56 -0700698}
699
Eric Laurente0720872014-03-11 09:30:41 -0700700void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700701{
702 ALOGV("setSystemProperty() property %s, value %s", property, value);
703}
704
705// Find a direct output profile compatible with the parameters passed, even if the input flags do
706// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800707sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700708 audio_devices_t device,
709 uint32_t samplingRate,
710 audio_format_t format,
711 audio_channel_mask_t channelMask,
712 audio_output_flags_t flags)
713{
Eric Laurent861a6282015-05-18 15:40:16 -0700714 // only retain flags that will drive the direct output profile selection
715 // if explicitly requested
716 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700717 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
718 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700719 flags =
720 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
721
722 sp<IOProfile> profile;
723
Eric Laurente552edb2014-03-10 17:42:56 -0700724 for (size_t i = 0; i < mHwModules.size(); i++) {
725 if (mHwModules[i]->mHandle == 0) {
726 continue;
727 }
728 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
730 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700731 samplingRate, NULL /*updatedSamplingRate*/,
732 format, NULL /*updatedFormat*/,
733 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700734 flags)) {
735 continue;
736 }
737 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100738 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700739 continue;
740 }
741 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100742 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700743 continue;
744 }
745 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100746 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700747 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700748 }
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750 }
Eric Laurent861a6282015-05-18 15:40:16 -0700751 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700752}
753
Eric Laurente0720872014-03-11 09:30:41 -0700754audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100755 uint32_t samplingRate,
756 audio_format_t format,
757 audio_channel_mask_t channelMask,
758 audio_output_flags_t flags,
759 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
Eric Laurent3b73df72014-03-11 09:06:29 -0700761 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700762 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
763 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
764 device, stream, samplingRate, format, channelMask, flags);
765
Kevin Rocard169753c2017-03-06 14:18:23 -0800766 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, stream, samplingRate, format,
767 channelMask, flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768}
769
Eric Laurente83b55d2014-11-14 10:06:21 -0800770status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
771 audio_io_handle_t *output,
772 audio_session_t session,
773 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700774 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800775 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800776 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700777 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800778 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700779{
Eric Laurente83b55d2014-11-14 10:06:21 -0800780 audio_attributes_t attributes;
781 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
797 // TODO: check for existing client for this port ID
798 if (*portId == AUDIO_PORT_HANDLE_NONE) {
799 *portId = AudioPort::getNextUniqueId();
800 }
801
Eric Laurentc75307b2015-03-17 15:29:32 -0700802 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800803 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100804 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800805 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100806 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800807 }
François Gaffie036e1e92015-03-19 10:16:24 +0100808 *stream = streamTypefromAttributesInt(&attributes);
809 *output = desc->mIoHandle;
810 ALOGV("getOutputForAttr() returns output %d", *output);
811 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800812 }
813 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
814 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
815 return BAD_VALUE;
816 }
817
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700818 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
819 " session %d selectedDeviceId %d",
820 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700821 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700822
823 *stream = streamTypefromAttributesInt(&attributes);
824
825 // Explicit routing?
826 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700827 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
828 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
829 if (mAvailableOutputDevices[i]->getId() == *selectedDeviceId) {
830 deviceDesc = mAvailableOutputDevices[i];
831 break;
832 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700833 }
834 }
835 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700836
Eric Laurente83b55d2014-11-14 10:06:21 -0800837 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700838 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700839
Eric Laurente83b55d2014-11-14 10:06:21 -0800840 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700841 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
842 }
843
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700844 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800845 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846
Kevin Rocard169753c2017-03-06 14:18:23 -0800847 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800848 config->sample_rate, config->format, config->channel_mask,
849 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700851 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800852 return INVALID_OPERATION;
853 }
Paul McLeanaa981192015-03-21 09:55:15 -0700854
Eric Laurent2ac76942017-06-22 17:17:09 -0700855 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
856 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
857 : AUDIO_PORT_HANDLE_NONE;
858
859 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
860
Eric Laurente83b55d2014-11-14 10:06:21 -0800861 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700862}
863
864audio_io_handle_t AudioPolicyManager::getOutputForDevice(
865 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800866 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700867 audio_stream_type_t stream,
868 uint32_t samplingRate,
869 audio_format_t format,
870 audio_channel_mask_t channelMask,
871 audio_output_flags_t flags,
872 const audio_offload_info_t *offloadInfo)
873{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700875 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700876
Eric Laurente552edb2014-03-10 17:42:56 -0700877#ifdef AUDIO_POLICY_TEST
878 if (mCurOutput != 0) {
879 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
880 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
881
882 if (mTestOutputs[mCurOutput] == 0) {
883 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700884 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
885 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700887 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700888 outputDesc->mFlags =
889 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700891 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
892 config.sample_rate = mTestSamplingRate;
893 config.channel_mask = mTestChannels;
894 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700895 if (offloadInfo != NULL) {
896 config.offload_info = *offloadInfo;
897 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700898 status = mpClientInterface->openOutput(0,
899 &mTestOutputs[mCurOutput],
900 &config,
901 &outputDesc->mDevice,
902 String8(""),
903 &outputDesc->mLatency,
904 outputDesc->mFlags);
905 if (status == NO_ERROR) {
906 outputDesc->mSamplingRate = config.sample_rate;
907 outputDesc->mFormat = config.format;
908 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700909 AudioParameter outputCmd = AudioParameter();
910 outputCmd.addInt(String8("set_id"),mCurOutput);
911 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
912 addOutput(mTestOutputs[mCurOutput], outputDesc);
913 }
914 }
915 return mTestOutputs[mCurOutput];
916 }
917#endif //AUDIO_POLICY_TEST
918
919 // open a direct output if required by specified parameters
920 //force direct flag if offload flag is set: offloading implies a direct output stream
921 // and all common behaviors are driven by checking only the direct flag
922 // this should normally be set appropriately in the policy configuration file
923 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700924 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700926 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
928 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800929 // only allow deep buffering for music stream type
930 if (stream != AUDIO_STREAM_MUSIC) {
931 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700932 } else if (/* stream == AUDIO_STREAM_MUSIC && */
933 flags == AUDIO_OUTPUT_FLAG_NONE &&
934 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
935 // use DEEP_BUFFER as default output for music stream type
936 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800937 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700938 if (stream == AUDIO_STREAM_TTS) {
939 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700940 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700941 audio_is_linear_pcm(format)) {
942 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
943 AUDIO_OUTPUT_FLAG_DIRECT);
944 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700945 }
Eric Laurente552edb2014-03-10 17:42:56 -0700946
Eric Laurentb732cf52014-09-24 19:08:21 -0700947 sp<IOProfile> profile;
948
949 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700950 // and not explicitly requested
951 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800952 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700953 audio_channel_count_from_out_mask(channelMask) <= 2) {
954 goto non_direct_output;
955 }
956
Andy Hung2ddee192015-12-18 17:34:44 -0800957 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
958 // This prevents creating an offloaded track and tearing it down immediately after start
959 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700960 // FIXME: We should check the audio session here but we do not have it in this context.
961 // This may prevent offloading in rare situations where effects are left active by apps
962 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700963
Eric Laurente552edb2014-03-10 17:42:56 -0700964 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800965 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700966 profile = getProfileForDirectOutput(device,
967 samplingRate,
968 format,
969 channelMask,
970 (audio_output_flags_t)flags);
971 }
972
Eric Laurent1c333e22014-05-20 10:48:17 -0700973 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700974 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700975
976 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700978 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
979 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800980 // reuse direct output if currently open by the same client
981 // and configured with same parameters
Eric Laurente552edb2014-03-10 17:42:56 -0700982 if ((samplingRate == outputDesc->mSamplingRate) &&
Kevin Rocard551061a2017-02-06 15:59:29 -0800983 audio_formats_match(format, outputDesc->mFormat) &&
984 (channelMask == outputDesc->mChannelMask)) {
Kevin Rocard169753c2017-03-06 14:18:23 -0800985 if (session == outputDesc->mDirectClientSession) {
Kevin Rocard551061a2017-02-06 15:59:29 -0800986 outputDesc->mDirectOpenCount++;
Kevin Rocard169753c2017-03-06 14:18:23 -0800987 ALOGV("getOutput() reusing direct output %d for session %d",
988 mOutputs.keyAt(i), session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800989 return mOutputs.keyAt(i);
990 } else {
Kevin Rocard169753c2017-03-06 14:18:23 -0800991 ALOGV("getOutput() do not reuse direct output because current client (%d) "
992 "is not the same as requesting client (%d)",
993 outputDesc->mDirectClientSession, session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800994 goto non_direct_output;
995 }
Eric Laurente552edb2014-03-10 17:42:56 -0700996 }
997 }
998 }
999 // close direct output if currently open and configured with different parameters
1000 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001001 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001002 }
Eric Laurent861a6282015-05-18 15:40:16 -07001003
1004 // if the selected profile is offloaded and no offload info was specified,
1005 // create a default one
1006 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001007 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -07001008 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1009 defaultOffloadInfo.sample_rate = samplingRate;
1010 defaultOffloadInfo.channel_mask = channelMask;
1011 defaultOffloadInfo.format = format;
1012 defaultOffloadInfo.stream_type = stream;
1013 defaultOffloadInfo.bit_rate = 0;
1014 defaultOffloadInfo.duration_us = -1;
1015 defaultOffloadInfo.has_video = true; // conservative
1016 defaultOffloadInfo.is_streaming = true; // likely
1017 offloadInfo = &defaultOffloadInfo;
1018 }
1019
Eric Laurentc75307b2015-03-17 15:29:32 -07001020 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07001021 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001022 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -07001023 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001024 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1025 config.sample_rate = samplingRate;
1026 config.channel_mask = channelMask;
1027 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001028 if (offloadInfo != NULL) {
1029 config.offload_info = *offloadInfo;
1030 }
Eric Laurente3014102017-05-03 11:15:43 -07001031 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
1032 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1033 : String8("");
Eric Laurent322b4d22015-04-03 15:57:54 -07001034 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 &output,
1036 &config,
1037 &outputDesc->mDevice,
Eric Laurente3014102017-05-03 11:15:43 -07001038 address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001039 &outputDesc->mLatency,
1040 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001041
1042 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001043 if (status != NO_ERROR ||
1044 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001045 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001046 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001047 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1048 "format %d %d, channelMask %04x %04x", output, samplingRate,
1049 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1050 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001051 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001052 mpClientInterface->closeOutput(output);
1053 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001054 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001055 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001056 goto non_direct_output;
1057 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001058 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001059 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001060 outputDesc->mSamplingRate = config.sample_rate;
1061 outputDesc->mChannelMask = config.channel_mask;
1062 outputDesc->mFormat = config.format;
1063 outputDesc->mRefCount[stream] = 0;
1064 outputDesc->mStopTime[stream] = 0;
1065 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001066 outputDesc->mDirectClientSession = session;
1067
Eric Laurente552edb2014-03-10 17:42:56 -07001068 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 mPreviousOutputs = mOutputs;
1070 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001071 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001072 return output;
1073 }
1074
Eric Laurentb732cf52014-09-24 19:08:21 -07001075non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001076
1077 // A request for HW A/V sync cannot fallback to a mixed output because time
1078 // stamps are embedded in audio data
1079 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1080 return AUDIO_IO_HANDLE_NONE;
1081 }
1082
Eric Laurente552edb2014-03-10 17:42:56 -07001083 // ignoring channel mask due to downmix capability in mixer
1084
1085 // open a non direct output
1086
1087 // for non direct outputs, only PCM is supported
1088 if (audio_is_linear_pcm(format)) {
1089 // get which output is suitable for the specified stream. The actual
1090 // routing change will happen when startOutput() will be called
1091 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1092
Eric Laurent8838a382014-09-08 16:44:28 -07001093 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1094 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1095 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001096 }
1097 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1098 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1099
Eric Laurente552edb2014-03-10 17:42:56 -07001100 return output;
1101}
1102
Eric Laurente0720872014-03-11 09:30:41 -07001103audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001104 audio_output_flags_t flags,
1105 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001106{
1107 // select one output among several that provide a path to a particular device or set of
1108 // devices (the list was previously build by getOutputsForDevice()).
1109 // The priority is as follows:
1110 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001111 // 2: the output with the bit depth the closest to the requested one
1112 // 3: the primary output
1113 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001114
1115 if (outputs.size() == 0) {
1116 return 0;
1117 }
1118 if (outputs.size() == 1) {
1119 return outputs[0];
1120 }
1121
1122 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001123 audio_io_handle_t outputForFlags = 0;
1124 audio_io_handle_t outputForPrimary = 0;
1125 audio_io_handle_t outputForFormat = 0;
1126 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1127 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001128
1129 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001130 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001132 // if a valid format is specified, skip output if not compatible
1133 if (format != AUDIO_FORMAT_INVALID) {
1134 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001135 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001136 continue;
1137 }
1138 } else if (!audio_is_linear_pcm(format)) {
1139 continue;
1140 }
Eric Laurente6930022016-02-11 10:20:40 -08001141 if (AudioPort::isBetterFormatMatch(
1142 outputDesc->mFormat, bestFormat, format)) {
1143 outputForFormat = outputs[i];
1144 bestFormat = outputDesc->mFormat;
1145 }
Eric Laurent8838a382014-09-08 16:44:28 -07001146 }
1147
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001148 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001149 if (commonFlags >= maxCommonFlags) {
1150 if (commonFlags == maxCommonFlags) {
1151 if (AudioPort::isBetterFormatMatch(
1152 outputDesc->mFormat, bestFormatForFlags, format)) {
1153 outputForFlags = outputs[i];
1154 bestFormatForFlags = outputDesc->mFormat;
1155 }
1156 } else {
1157 outputForFlags = outputs[i];
1158 maxCommonFlags = commonFlags;
1159 bestFormatForFlags = outputDesc->mFormat;
1160 }
Eric Laurente552edb2014-03-10 17:42:56 -07001161 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1162 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001163 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001164 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001165 }
1166 }
1167 }
1168
Eric Laurente6930022016-02-11 10:20:40 -08001169 if (outputForFlags != 0) {
1170 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001171 }
Eric Laurente6930022016-02-11 10:20:40 -08001172 if (outputForFormat != 0) {
1173 return outputForFormat;
1174 }
1175 if (outputForPrimary != 0) {
1176 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001177 }
1178
1179 return outputs[0];
1180}
1181
Eric Laurente0720872014-03-11 09:30:41 -07001182status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001183 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001184 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001185{
Paul McLeanaa981192015-03-21 09:55:15 -07001186 ALOGV("startOutput() output %d, stream %d, session %d",
1187 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001188 ssize_t index = mOutputs.indexOfKey(output);
1189 if (index < 0) {
1190 ALOGW("startOutput() unknown output %d", output);
1191 return BAD_VALUE;
1192 }
1193
Eric Laurentc75307b2015-03-17 15:29:32 -07001194 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1195
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001196 // Routing?
1197 mOutputRoutes.incRouteActivity(session);
1198
Eric Laurentc75307b2015-03-17 15:29:32 -07001199 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001200 AudioMix *policyMix = NULL;
1201 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001202 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001203 policyMix = outputDesc->mPolicyMix;
1204 address = policyMix->mDeviceAddress.string();
1205 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1206 newDevice = policyMix->mDeviceType;
1207 } else {
1208 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1209 }
Eric Laurent493404d2015-04-21 15:07:36 -07001210 } else if (mOutputRoutes.hasRouteChanged(session)) {
1211 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001212 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001213 } else {
1214 newDevice = AUDIO_DEVICE_NONE;
1215 }
1216
1217 uint32_t delayMs = 0;
1218
Eric Laurentc40d9692016-04-13 19:14:13 -07001219 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001220
1221 if (status != NO_ERROR) {
1222 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001223 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001224 }
1225 // Automatically enable the remote submix input when output is started on a re routing mix
1226 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001227 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1228 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001229 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1230 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001231 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001232 "remote-submix");
1233 }
1234
1235 if (delayMs != 0) {
1236 usleep(delayMs * 1000);
1237 }
1238
1239 return status;
1240}
1241
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001242status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001243 audio_stream_type_t stream,
1244 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001245 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001246 uint32_t *delayMs)
1247{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001248 // cannot start playback of STREAM_TTS if any other output is being used
1249 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001250
1251 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001252 if (stream == AUDIO_STREAM_TTS) {
1253 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001254 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001255 return INVALID_OPERATION;
1256 } else {
1257 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1258 }
1259 } else {
1260 // some playback other than beacon starts
1261 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1262 }
1263
Eric Laurent77305a62016-07-25 16:39:22 -07001264 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001265 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001266 bool force = !outputDesc->isActive() &&
1267 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001268
Eric Laurente552edb2014-03-10 17:42:56 -07001269 // increment usage count for this stream on the requested output:
1270 // NOTE that the usage count is the same for duplicated output and hardware output which is
1271 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1272 outputDesc->changeRefCount(stream, 1);
1273
Eric Laurent36829f92017-04-07 19:04:42 -07001274 if (stream == AUDIO_STREAM_MUSIC) {
1275 selectOutputForMusicEffects();
1276 }
1277
Eric Laurent493404d2015-04-21 15:07:36 -07001278 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001279 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001280 if (device == AUDIO_DEVICE_NONE) {
1281 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001282 }
Eric Laurent36829f92017-04-07 19:04:42 -07001283
Eric Laurente552edb2014-03-10 17:42:56 -07001284 routing_strategy strategy = getStrategy(stream);
1285 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001286 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1287 (beaconMuteLatency > 0);
1288 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001289 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001290 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001291 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001292 // force a device change if any other output is:
1293 // - managed by the same hw module
1294 // - has a current device selection that differs from selected device.
1295 // - supports currently selected device
1296 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001297 // In this case, the audio HAL must receive the new device selection so that it can
1298 // change the device currently selected by the other active output.
1299 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001300 desc->device() != device &&
1301 desc->supportedDevices() & device &&
1302 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001303 force = true;
1304 }
1305 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001306 // a notification so that audio focus effect can propagate, or that a mute/unmute
1307 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001308 uint32_t latency = desc->latency();
1309 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1310 waitMs = latency;
1311 }
1312 }
1313 }
Eric Laurentdc462862016-07-19 12:29:53 -07001314 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001315
1316 // handle special case for sonification while in call
1317 if (isInCall()) {
1318 handleIncallSonification(stream, true, false);
1319 }
1320
1321 // apply volume rules for current stream and device if necessary
1322 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001323 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001324 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001325 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001326
1327 // update the outputs if starting an output with a stream that can affect notification
1328 // routing
1329 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001330
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001331 // force reevaluating accessibility routing when ringtone or alarm starts
1332 if (strategy == STRATEGY_SONIFICATION) {
1333 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1334 }
Eric Laurentdc462862016-07-19 12:29:53 -07001335
1336 if (waitMs > muteWaitMs) {
1337 *delayMs = waitMs - muteWaitMs;
1338 }
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
Eric Laurentdc462862016-07-19 12:29:53 -07001340
Eric Laurente552edb2014-03-10 17:42:56 -07001341 return NO_ERROR;
1342}
1343
1344
Eric Laurente0720872014-03-11 09:30:41 -07001345status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001346 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001347 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001348{
1349 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1350 ssize_t index = mOutputs.indexOfKey(output);
1351 if (index < 0) {
1352 ALOGW("stopOutput() unknown output %d", output);
1353 return BAD_VALUE;
1354 }
1355
Eric Laurentc75307b2015-03-17 15:29:32 -07001356 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001357
Eric Laurentc75307b2015-03-17 15:29:32 -07001358 if (outputDesc->mRefCount[stream] == 1) {
1359 // Automatically disable the remote submix input when output is stopped on a
1360 // re routing mix of type MIX_TYPE_RECORDERS
1361 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1362 outputDesc->mPolicyMix != NULL &&
1363 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1364 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1365 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001366 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001367 "remote-submix");
1368 }
1369 }
1370
1371 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001374 int activityCount = mOutputRoutes.decRouteActivity(session);
1375 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1376
1377 if (forceDeviceUpdate) {
1378 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1379 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001380 }
1381
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001382 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001383}
1384
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001385status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001386 audio_stream_type_t stream,
1387 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001388{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001389 // always handle stream stop, check which stream type is stopping
1390 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1391
Eric Laurente552edb2014-03-10 17:42:56 -07001392 // handle special case for sonification while in call
1393 if (isInCall()) {
1394 handleIncallSonification(stream, false, false);
1395 }
1396
1397 if (outputDesc->mRefCount[stream] > 0) {
1398 // decrement usage count of this stream on the output
1399 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001400
Eric Laurente552edb2014-03-10 17:42:56 -07001401 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001402 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001403 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001404 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001405 // delay the device switch by twice the latency because stopOutput() is executed when
1406 // the track stop() command is received and at that time the audio track buffer can
1407 // still contain data that needs to be drained. The latency only covers the audio HAL
1408 // and kernel buffers. Also the latency does not always include additional delay in the
1409 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001411
1412 // force restoring the device selection on other active outputs if it differs from the
1413 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001414 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001415 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001416 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001417 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001418 desc->isActive() &&
1419 outputDesc->sharesHwModuleWith(desc) &&
1420 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001421 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1422 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001423 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001424 newDevice2,
1425 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001426 delayMs);
1427 // re-apply device specific volume if not done by setOutputDevice()
1428 if (!force) {
1429 applyStreamVolumes(desc, newDevice2, delayMs);
1430 }
Eric Laurente552edb2014-03-10 17:42:56 -07001431 }
1432 }
1433 // update the outputs if stopping one with a stream that can affect notification routing
1434 handleNotificationRoutingForStream(stream);
1435 }
Eric Laurent36829f92017-04-07 19:04:42 -07001436 if (stream == AUDIO_STREAM_MUSIC) {
1437 selectOutputForMusicEffects();
1438 }
Eric Laurente552edb2014-03-10 17:42:56 -07001439 return NO_ERROR;
1440 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001441 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001442 return INVALID_OPERATION;
1443 }
1444}
1445
Eric Laurente83b55d2014-11-14 10:06:21 -08001446void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001447 audio_stream_type_t stream __unused,
1448 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001449{
1450 ALOGV("releaseOutput() %d", output);
1451 ssize_t index = mOutputs.indexOfKey(output);
1452 if (index < 0) {
1453 ALOGW("releaseOutput() releasing unknown output %d", output);
1454 return;
1455 }
1456
1457#ifdef AUDIO_POLICY_TEST
1458 int testIndex = testOutputIndex(output);
1459 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001460 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001461 if (outputDesc->isActive()) {
1462 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001463 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001464 mTestOutputs[testIndex] = 0;
1465 }
1466 return;
1467 }
1468#endif //AUDIO_POLICY_TEST
1469
Paul McLeanaa981192015-03-21 09:55:15 -07001470 // Routing
1471 mOutputRoutes.removeRoute(session);
1472
Eric Laurentc75307b2015-03-17 15:29:32 -07001473 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001474 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001475 if (desc->mDirectOpenCount <= 0) {
1476 ALOGW("releaseOutput() invalid open count %d for output %d",
1477 desc->mDirectOpenCount, output);
1478 return;
1479 }
1480 if (--desc->mDirectOpenCount == 0) {
1481 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001482 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001483 }
1484 }
1485}
1486
1487
Eric Laurentcaf7f482014-11-25 17:50:47 -08001488status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1489 audio_io_handle_t *input,
1490 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001491 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001492 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001493 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001494 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001495 input_type_t *inputType,
1496 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001497{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001498 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1499 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001500 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001501
Eric Laurentcb4dae22017-07-01 19:39:32 -07001502 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1503 // possible
1504 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1505 *input != AUDIO_IO_HANDLE_NONE) {
1506 ssize_t index = mInputs.indexOfKey(*input);
1507 if (index < 0) {
1508 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1509 return BAD_VALUE;
1510 }
1511 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1512 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1513 if (audioSession == 0) {
1514 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1515 return BAD_VALUE;
1516 }
1517 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1518 // The second call is for the first active client and sets the UID. Any further call
1519 // corresponds to a new client and is only permitted from the same UId.
1520 if (audioSession->openCount() == 1) {
1521 audioSession->setUid(uid);
1522 } else if (audioSession->uid() != uid) {
1523 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1524 uid, session, audioSession->uid());
1525 return INVALID_OPERATION;
1526 }
1527 audioSession->changeOpenCount(1);
1528 *inputType = API_INPUT_LEGACY;
1529 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1530 *portId = AudioPort::getNextUniqueId();
1531 }
1532 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1533 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1534 : AUDIO_PORT_HANDLE_NONE;
1535 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1536 return NO_ERROR;
1537 }
1538
Eric Laurentcaf7f482014-11-25 17:50:47 -08001539 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001540 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001541
Eric Laurent275e8e92014-11-30 15:14:47 -08001542 audio_devices_t device;
1543 // handle legacy remote submix case where the address was not always specified
1544 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001545 audio_source_t inputSource = attr->source;
1546 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001547 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001548
Eric Laurentc447ded2015-01-06 08:47:05 -08001549 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1550 inputSource = AUDIO_SOURCE_MIC;
1551 }
1552 halInputSource = inputSource;
1553
Eric Laurent20b9ef02016-12-05 11:03:16 -08001554 // TODO: check for existing client for this port ID
1555 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1556 *portId = AudioPort::getNextUniqueId();
1557 }
1558
Paul McLean466dc8e2015-04-17 13:15:36 -06001559 // Explicit routing?
1560 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001561 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1562 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1563 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1564 deviceDesc = mAvailableInputDevices[i];
1565 break;
1566 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001567 }
1568 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001569 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001570
Eric Laurentc447ded2015-01-06 08:47:05 -08001571 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001572 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001573 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001574 if (ret != NO_ERROR) {
1575 return ret;
1576 }
1577 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001578 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1579 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001580 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001581 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001582 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001583 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001584 return BAD_VALUE;
1585 }
Eric Laurentc722f302014-12-10 11:21:49 -08001586 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001587 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001588 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1589 // there is an external policy, but this input is attached to a mix of recorders,
1590 // meaning it receives audio injected into the framework, so the recorder doesn't
1591 // know about it and is therefore considered "legacy"
1592 *inputType = API_INPUT_LEGACY;
1593 } else {
1594 // recording a mix of players defined by an external policy, we're rerouting for
1595 // an external policy
1596 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1597 }
Eric Laurentc722f302014-12-10 11:21:49 -08001598 } else if (audio_is_remote_submix_device(device)) {
1599 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001600 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001601 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1602 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001603 } else {
1604 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001605 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001606
Eric Laurent599c7582015-12-07 18:05:55 -08001607 }
1608
1609 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001610 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001611 policyMix);
1612 if (*input == AUDIO_IO_HANDLE_NONE) {
1613 mInputRoutes.removeRoute(session);
1614 return INVALID_OPERATION;
1615 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001616
Eric Laurent2ac76942017-06-22 17:17:09 -07001617 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1618 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1619 : AUDIO_PORT_HANDLE_NONE;
1620
1621 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1622 *input, *inputType, *selectedDeviceId);
1623
Eric Laurent599c7582015-12-07 18:05:55 -08001624 return NO_ERROR;
1625}
1626
1627
1628audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1629 String8 address,
1630 audio_session_t session,
1631 uid_t uid,
1632 audio_source_t inputSource,
1633 uint32_t samplingRate,
1634 audio_format_t format,
1635 audio_channel_mask_t channelMask,
1636 audio_input_flags_t flags,
1637 AudioMix *policyMix)
1638{
1639 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1640 audio_source_t halInputSource = inputSource;
1641 bool isSoundTrigger = false;
1642
1643 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1644 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1645 if (index >= 0) {
1646 input = mSoundTriggerSessions.valueFor(session);
1647 isSoundTrigger = true;
1648 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1649 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1650 } else {
1651 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001652 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001653 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001654 audio_is_linear_pcm(format)) {
1655 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001656 }
1657
Andy Hungf129b032015-04-07 13:45:50 -07001658 // find a compatible input profile (not necessarily identical in parameters)
1659 sp<IOProfile> profile;
1660 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001661 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001662 audio_format_t profileFormat = format;
1663 audio_channel_mask_t profileChannelMask = channelMask;
1664 audio_input_flags_t profileFlags = flags;
1665 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001666 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001667 profileSamplingRate, profileFormat, profileChannelMask,
1668 profileFlags);
1669 if (profile != 0) {
1670 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001671 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1672 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001673 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1674 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1675 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001676 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1677 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001678 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001679 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001680 }
Eric Laurente552edb2014-03-10 17:42:56 -07001681 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001682 // Pick input sampling rate if not specified by client
1683 if (samplingRate == 0) {
1684 samplingRate = profileSamplingRate;
1685 }
Eric Laurente552edb2014-03-10 17:42:56 -07001686
Eric Laurent322b4d22015-04-03 15:57:54 -07001687 if (profile->getModuleHandle() == 0) {
1688 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001689 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001690 }
1691
Eric Laurent599c7582015-12-07 18:05:55 -08001692 sp<AudioSession> audioSession = new AudioSession(session,
1693 inputSource,
1694 format,
1695 samplingRate,
1696 channelMask,
1697 flags,
1698 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001699 isSoundTrigger,
1700 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001701
Eric Laurent74708e72017-04-07 17:13:42 -07001702// FIXME: disable concurrent capture until UI is ready
1703#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001704 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001705 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001706 for (size_t i = 0; i < mInputs.size(); i++) {
1707 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001708 // reuse input if:
1709 // - it shares the same profile
1710 // AND
1711 // - it is not a reroute submix input
1712 // AND
1713 // - it is: not used for sound trigger
1714 // OR
1715 // used for sound trigger and all clients use the same session ID
1716 //
1717 if ((profile == desc->mProfile) &&
1718 (isSoundTrigger == desc->isSoundTrigger()) &&
1719 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001720
1721 sp<AudioSession> as = desc->getAudioSession(session);
1722 if (as != 0) {
1723 // do not allow unmatching properties on same session
1724 if (as->matches(audioSession)) {
1725 as->changeOpenCount(1);
1726 } else {
1727 ALOGW("getInputForDevice() record with different attributes"
1728 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001729 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001730 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001731 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001732 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001733 }
Eric Laurentbb948092017-01-23 18:33:30 -08001734
Eric Laurent555530a2017-02-07 18:17:24 -08001735 // Reuse the already opened input stream on this profile if:
1736 // - the new capture source is background OR
1737 // - the path requested configurations match OR
1738 // - the new source priority is less than the highest source priority on this input
1739 // If the input stream cannot be reused, close it before opening a new stream
1740 // on the same profile for the new client so that the requested path configuration
1741 // can be selected.
1742 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001743 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001744 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001745 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001746 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001747 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001748 reusedInputDesc = desc;
1749 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001750 } else {
1751 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001752 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1753 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001754 }
Eric Laurent599c7582015-12-07 18:05:55 -08001755 }
1756 }
Eric Laurent599c7582015-12-07 18:05:55 -08001757
Eric Laurent555530a2017-02-07 18:17:24 -08001758 if (reusedInputDesc != 0) {
1759 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1760 for (size_t j = 0; j < sessions.size(); j++) {
1761 audio_session_t currentSession = sessions.keyAt(j);
1762 stopInput(reusedInputDesc->mIoHandle, currentSession);
1763 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1764 }
1765 }
Eric Laurent74708e72017-04-07 17:13:42 -07001766#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001767
Eric Laurentcf2c0212014-07-25 16:20:43 -07001768 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001769 config.sample_rate = profileSamplingRate;
1770 config.channel_mask = profileChannelMask;
1771 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001772
Eric Laurente3014102017-05-03 11:15:43 -07001773 if (address == "") {
1774 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1775 // the inputs vector must be of size 1, but we don't want to crash here
1776 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1777 }
1778
Eric Laurent322b4d22015-04-03 15:57:54 -07001779 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001780 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001781 &config,
1782 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001783 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001784 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001785 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001786
1787 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001788 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001789 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001790 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001791 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001792 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1793 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001794 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001795 if (input != AUDIO_IO_HANDLE_NONE) {
1796 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001797 }
Eric Laurent599c7582015-12-07 18:05:55 -08001798 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001799 }
1800
Eric Laurent1f2f2232014-06-02 12:01:23 -07001801 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001802 inputDesc->mSamplingRate = profileSamplingRate;
1803 inputDesc->mFormat = profileFormat;
1804 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001805 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001806 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001807 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001808
Eric Laurent599c7582015-12-07 18:05:55 -08001809 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001810 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001811
Eric Laurent599c7582015-12-07 18:05:55 -08001812 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001813}
1814
Eric Laurentbb948092017-01-23 18:33:30 -08001815//static
1816bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1817{
1818 return (source == AUDIO_SOURCE_HOTWORD) ||
1819 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1820 (source == AUDIO_SOURCE_FM_TUNER);
1821}
1822
Eric Laurentfb66dd92016-01-28 18:32:03 -08001823bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1824 const sp<AudioSession>& audioSession)
1825{
1826 // Do not allow capture if an active voice call is using a software patch and
1827 // the call TX source device is on the same HW module.
1828 // FIXME: would be better to refine to only inputs whose profile connects to the
1829 // call TX device but this information is not in the audio patch
1830 if (mCallTxPatch != 0 &&
1831 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1832 return false;
1833 }
1834
1835 // starting concurrent capture is enabled if:
1836 // 1) capturing for re-routing
1837 // 2) capturing for HOTWORD source
1838 // 3) capturing for FM TUNER source
1839 // 3) All other active captures are either for re-routing or HOTWORD
1840
1841 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001842 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001843 return true;
1844 }
1845
1846 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1847 for (size_t i = 0; i < activeInputs.size(); i++) {
1848 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001849 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001850 !is_virtual_input_device(activeInput->mDevice)) {
1851 return false;
1852 }
1853 }
1854
1855 return true;
1856}
1857
Chris Thornton2b864642017-06-27 21:26:07 -07001858// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1859bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1860 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1861 bool soundTriggerSupportsConcurrentCapture = false;
1862 unsigned int numModules = 0;
1863 struct sound_trigger_module_descriptor* nModules = NULL;
1864
1865 status_t status = SoundTrigger::listModules(nModules, &numModules);
1866 if (status == NO_ERROR && numModules != 0) {
1867 nModules = (struct sound_trigger_module_descriptor*) calloc(
1868 numModules, sizeof(struct sound_trigger_module_descriptor));
1869 if (nModules == NULL) {
1870 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1871 // ram the next time this function is called.
1872 ALOGE("Failed to allocate buffer for module descriptors");
1873 return false;
1874 }
1875
1876 status = SoundTrigger::listModules(nModules, &numModules);
1877 if (status == NO_ERROR) {
1878 soundTriggerSupportsConcurrentCapture = true;
1879 for (size_t i = 0; i < numModules; ++i) {
1880 soundTriggerSupportsConcurrentCapture &=
1881 nModules[i].properties.concurrent_capture;
1882 }
1883 }
1884 free(nModules);
1885 }
1886 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1887 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1888 }
1889 return mSoundTriggerSupportsConcurrentCapture;
1890}
1891
Eric Laurentfb66dd92016-01-28 18:32:03 -08001892
Eric Laurent4dc68062014-07-28 17:26:49 -07001893status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001894 audio_session_t session,
1895 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001896{
1897 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001898 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001899 ssize_t index = mInputs.indexOfKey(input);
1900 if (index < 0) {
1901 ALOGW("startInput() unknown input %d", input);
1902 return BAD_VALUE;
1903 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001904 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001905
Eric Laurent599c7582015-12-07 18:05:55 -08001906 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1907 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001908 ALOGW("startInput() unknown session %d on input %d", session, input);
1909 return BAD_VALUE;
1910 }
1911
Eric Laurent74708e72017-04-07 17:13:42 -07001912// FIXME: disable concurrent capture until UI is ready
1913#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001914 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1915 ALOGW("startInput(%d) failed: other input already started", input);
1916 return INVALID_OPERATION;
1917 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001918
Eric Laurentfb66dd92016-01-28 18:32:03 -08001919 if (isInCall()) {
1920 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1921 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001922 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001923 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001924 }
Eric Laurent74708e72017-04-07 17:13:42 -07001925#else
1926 if (!is_virtual_input_device(inputDesc->mDevice)) {
1927 if (mCallTxPatch != 0 &&
1928 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1929 ALOGW("startInput(%d) failed: call in progress", input);
1930 return INVALID_OPERATION;
1931 }
1932
1933 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1934 for (size_t i = 0; i < activeInputs.size(); i++) {
1935 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1936
1937 if (is_virtual_input_device(activeDesc->mDevice)) {
1938 continue;
1939 }
1940
Eric Laurentcb4dae22017-07-01 19:39:32 -07001941 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1942 activeDesc->getId() == inputDesc->getId()) {
1943 continue;
1944 }
1945
Eric Laurent74708e72017-04-07 17:13:42 -07001946 audio_source_t activeSource = activeDesc->inputSource(true);
1947 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1948 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1949 if (activeDesc->hasPreemptedSession(session)) {
1950 ALOGW("startInput(%d) failed for HOTWORD: "
1951 "other input %d already started for HOTWORD",
1952 input, activeDesc->mIoHandle);
1953 return INVALID_OPERATION;
1954 }
1955 } else {
1956 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1957 input, activeDesc->mIoHandle);
1958 return INVALID_OPERATION;
1959 }
1960 } else {
1961 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1962 ALOGW("startInput(%d) failed: other input %d already started",
1963 input, activeDesc->mIoHandle);
1964 return INVALID_OPERATION;
1965 }
1966 }
1967 }
1968
Chris Thornton2b864642017-06-27 21:26:07 -07001969 // We only need to check if the sound trigger session supports concurrent capture if the
1970 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1971 // that's running.
1972 const bool allowConcurrentWithSoundTrigger =
1973 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1974
Eric Laurent74708e72017-04-07 17:13:42 -07001975 // if capture is allowed, preempt currently active HOTWORD captures
1976 for (size_t i = 0; i < activeInputs.size(); i++) {
1977 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1978
1979 if (is_virtual_input_device(activeDesc->mDevice)) {
1980 continue;
1981 }
1982
Chris Thornton2b864642017-06-27 21:26:07 -07001983 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1984 continue;
1985 }
1986
Eric Laurent74708e72017-04-07 17:13:42 -07001987 audio_source_t activeSource = activeDesc->inputSource(true);
1988 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1989 AudioSessionCollection activeSessions =
1990 activeDesc->getAudioSessions(true /*activeOnly*/);
1991 audio_session_t activeSession = activeSessions.keyAt(0);
1992 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1993 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1994 sessions.add(activeSession);
1995 inputDesc->setPreemptedSessions(sessions);
1996 stopInput(activeHandle, activeSession);
1997 releaseInput(activeHandle, activeSession);
1998 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1999 input, activeDesc->mIoHandle);
2000 }
2001 }
2002 }
2003#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002004
Eric Laurent313d1e72016-01-29 09:56:57 -08002005 // increment activity count before calling getNewInputDevice() below as only active sessions
2006 // are considered for device selection
2007 audioSession->changeActiveCount(1);
2008
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002009 // Routing?
2010 mInputRoutes.incRouteActivity(session);
2011
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002012 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002013 // indicate active capture to sound trigger service if starting capture from a mic on
2014 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002015 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002016 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002017
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002018 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2019 // if input maps to a dynamic policy with an activity listener, notify of state change
2020 if ((inputDesc->mPolicyMix != NULL)
2021 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2022 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2023 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002024 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002025
Eric Laurentf7c50102016-09-30 15:19:43 -07002026 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2027 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002028 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002029 SoundTrigger::setCaptureState(true);
2030 }
2031
2032 // automatically enable the remote submix output when input is started if not
2033 // used by a policy mix of type MIX_TYPE_RECORDERS
2034 // For remote submix (a virtual device), we open only one input per capture request.
2035 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2036 String8 address = String8("");
2037 if (inputDesc->mPolicyMix == NULL) {
2038 address = String8("0");
2039 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2040 address = inputDesc->mPolicyMix->mDeviceAddress;
2041 }
2042 if (address != "") {
2043 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2044 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2045 address, "remote-submix");
2046 }
Eric Laurentc722f302014-12-10 11:21:49 -08002047 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002048 }
Eric Laurente552edb2014-03-10 17:42:56 -07002049 }
2050
Eric Laurent599c7582015-12-07 18:05:55 -08002051 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002052
Eric Laurente552edb2014-03-10 17:42:56 -07002053 return NO_ERROR;
2054}
2055
Eric Laurent4dc68062014-07-28 17:26:49 -07002056status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2057 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002058{
2059 ALOGV("stopInput() input %d", input);
2060 ssize_t index = mInputs.indexOfKey(input);
2061 if (index < 0) {
2062 ALOGW("stopInput() unknown input %d", input);
2063 return BAD_VALUE;
2064 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002065 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002066
Eric Laurent599c7582015-12-07 18:05:55 -08002067 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002068 if (index < 0) {
2069 ALOGW("stopInput() unknown session %d on input %d", session, input);
2070 return BAD_VALUE;
2071 }
2072
Eric Laurent599c7582015-12-07 18:05:55 -08002073 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002074 ALOGW("stopInput() input %d already stopped", input);
2075 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002076 }
2077
Eric Laurent599c7582015-12-07 18:05:55 -08002078 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002079
2080 // Routing?
2081 mInputRoutes.decRouteActivity(session);
2082
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002083 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002084
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002085 if (inputDesc->isActive()) {
2086 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2087 } else {
2088 // if input maps to a dynamic policy with an activity listener, notify of state change
2089 if ((inputDesc->mPolicyMix != NULL)
2090 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2091 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2092 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002093 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002094
2095 // automatically disable the remote submix output when input is stopped if not
2096 // used by a policy mix of type MIX_TYPE_RECORDERS
2097 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2098 String8 address = String8("");
2099 if (inputDesc->mPolicyMix == NULL) {
2100 address = String8("0");
2101 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2102 address = inputDesc->mPolicyMix->mDeviceAddress;
2103 }
2104 if (address != "") {
2105 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2106 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2107 address, "remote-submix");
2108 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002109 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002110
Eric Laurentf7c50102016-09-30 15:19:43 -07002111 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002112 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002113
Eric Laurentf7c50102016-09-30 15:19:43 -07002114 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2115 // primary HW module
2116 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2117 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2118 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002119 SoundTrigger::setCaptureState(false);
2120 }
2121 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002122 }
Eric Laurente552edb2014-03-10 17:42:56 -07002123 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002124 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002125}
2126
Eric Laurent4dc68062014-07-28 17:26:49 -07002127void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2128 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002129{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002130
Eric Laurente552edb2014-03-10 17:42:56 -07002131 ALOGV("releaseInput() %d", input);
2132 ssize_t index = mInputs.indexOfKey(input);
2133 if (index < 0) {
2134 ALOGW("releaseInput() releasing unknown input %d", input);
2135 return;
2136 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002137
2138 // Routing
2139 mInputRoutes.removeRoute(session);
2140
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002141 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2142 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002143
Eric Laurent599c7582015-12-07 18:05:55 -08002144 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002145 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002146 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2147 return;
2148 }
Eric Laurent599c7582015-12-07 18:05:55 -08002149
2150 if (audioSession->openCount() == 0) {
2151 ALOGW("releaseInput() invalid open count %d on session %d",
2152 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002153 return;
2154 }
Eric Laurent599c7582015-12-07 18:05:55 -08002155
2156 if (audioSession->changeOpenCount(-1) == 0) {
2157 inputDesc->removeAudioSession(session);
2158 }
2159
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002160 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002161 ALOGV("releaseInput() exit > 0");
2162 return;
2163 }
2164
Eric Laurent05b90f82014-08-27 15:32:29 -07002165 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002166 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002167 ALOGV("releaseInput() exit");
2168}
2169
Eric Laurentd4692962014-05-05 18:13:44 -07002170void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002171 bool patchRemoved = false;
2172
Eric Laurentd4692962014-05-05 18:13:44 -07002173 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002174 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002175 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002176 if (patch_index >= 0) {
2177 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002178 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002179 mAudioPatches.removeItemsAt(patch_index);
2180 patchRemoved = true;
2181 }
Eric Laurentd4692962014-05-05 18:13:44 -07002182 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2183 }
2184 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002185 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002186 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002187
2188 if (patchRemoved) {
2189 mpClientInterface->onAudioPatchListUpdate();
2190 }
Eric Laurentd4692962014-05-05 18:13:44 -07002191}
2192
Eric Laurente0720872014-03-11 09:30:41 -07002193void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002194 int indexMin,
2195 int indexMax)
2196{
2197 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002198 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002199
2200 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002201 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2202 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002203 continue;
2204 }
2205 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002206 }
Eric Laurente552edb2014-03-10 17:42:56 -07002207}
2208
Eric Laurente0720872014-03-11 09:30:41 -07002209status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002210 int index,
2211 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002212{
2213
François Gaffied1ab2bd2015-12-02 18:20:06 +01002214 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2215 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002216 return BAD_VALUE;
2217 }
2218 if (!audio_is_output_device(device)) {
2219 return BAD_VALUE;
2220 }
2221
2222 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002223 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002224
Eric Laurent1fd372e2016-04-06 14:23:53 -07002225 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002226 stream, device, index);
2227
Eric Laurent28d09f02016-03-08 10:43:05 -08002228 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002229 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2230 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002231 continue;
2232 }
2233 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2234 }
Eric Laurente552edb2014-03-10 17:42:56 -07002235
Eric Laurent1fd372e2016-04-06 14:23:53 -07002236 // update volume on all outputs and streams matching the following:
2237 // - The requested stream (or a stream matching for volume control) is active on the output
2238 // - The device (or devices) selected by the strategy corresponding to this stream includes
2239 // the requested device
2240 // - For non default requested device, currently selected device on the output is either the
2241 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002242 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2243 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002244 status_t status = NO_ERROR;
2245 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002246 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2247 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002248 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2249 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002250 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002251 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002252 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2253 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002254 continue;
2255 }
Eric Laurent794fde22016-03-11 09:50:45 -08002256 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002257 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2258 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002259 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2260 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002261 continue;
2262 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002263 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002264 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002265 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002266 applyVolume = (curDevice & curStreamDevice) != 0;
2267 } else {
2268 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002269 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002270 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002271
Eric Laurente76f29c2016-09-14 17:17:53 -07002272 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002273 //FIXME: workaround for truncated touch sounds
2274 // delayed volume change for system stream to be removed when the problem is
2275 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002276 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002277 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2278 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002279 if (volStatus != NO_ERROR) {
2280 status = volStatus;
2281 }
2282 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002283 }
Eric Laurente552edb2014-03-10 17:42:56 -07002284 }
2285 return status;
2286}
2287
Eric Laurente0720872014-03-11 09:30:41 -07002288status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002289 int *index,
2290 audio_devices_t device)
2291{
2292 if (index == NULL) {
2293 return BAD_VALUE;
2294 }
2295 if (!audio_is_output_device(device)) {
2296 return BAD_VALUE;
2297 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002298 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002299 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002300 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002301 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2302 }
François Gaffiedfd74092015-03-19 12:10:59 +01002303 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002304
François Gaffied1ab2bd2015-12-02 18:20:06 +01002305 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002306 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2307 return NO_ERROR;
2308}
2309
Eric Laurent36829f92017-04-07 19:04:42 -07002310audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002311{
2312 // select one output among several suitable for global effects.
2313 // The priority is as follows:
2314 // 1: An offloaded output. If the effect ends up not being offloadable,
2315 // AudioFlinger will invalidate the track and the offloaded output
2316 // will be closed causing the effect to be moved to a PCM output.
2317 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002318 // 3: The primary output
2319 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002320
Eric Laurent3b73df72014-03-11 09:06:29 -07002321 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002322 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002323 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002324
Eric Laurent36829f92017-04-07 19:04:42 -07002325 if (outputs.size() == 0) {
2326 return AUDIO_IO_HANDLE_NONE;
2327 }
Eric Laurente552edb2014-03-10 17:42:56 -07002328
Eric Laurent36829f92017-04-07 19:04:42 -07002329 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2330 bool activeOnly = true;
2331
2332 while (output == AUDIO_IO_HANDLE_NONE) {
2333 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2334 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2335 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2336
2337 for (size_t i = 0; i < outputs.size(); i++) {
2338 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2339 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2340 continue;
2341 }
2342 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2343 activeOnly, i, desc->mFlags);
2344 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2345 outputOffloaded = outputs[i];
2346 }
2347 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2348 outputDeepBuffer = outputs[i];
2349 }
2350 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2351 outputPrimary = outputs[i];
2352 }
2353 }
2354 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2355 output = outputOffloaded;
2356 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2357 output = outputDeepBuffer;
2358 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2359 output = outputPrimary;
2360 } else {
2361 output = outputs[0];
2362 }
2363 activeOnly = false;
2364 }
2365
2366 if (output != mMusicEffectOutput) {
2367 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2368 mMusicEffectOutput = output;
2369 }
2370
2371 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002372 return output;
2373}
2374
Eric Laurent36829f92017-04-07 19:04:42 -07002375audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2376{
2377 return selectOutputForMusicEffects();
2378}
2379
Eric Laurente0720872014-03-11 09:30:41 -07002380status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002381 audio_io_handle_t io,
2382 uint32_t strategy,
2383 int session,
2384 int id)
2385{
2386 ssize_t index = mOutputs.indexOfKey(io);
2387 if (index < 0) {
2388 index = mInputs.indexOfKey(io);
2389 if (index < 0) {
2390 ALOGW("registerEffect() unknown io %d", io);
2391 return INVALID_OPERATION;
2392 }
2393 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002394 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002395}
2396
Eric Laurentc75307b2015-03-17 15:29:32 -07002397bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2398{
Eric Laurent28d09f02016-03-08 10:43:05 -08002399 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002400 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2401 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002402 continue;
2403 }
2404 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2405 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002406 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002407}
2408
2409bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2410{
2411 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2412}
2413
Eric Laurente0720872014-03-11 09:30:41 -07002414bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002415{
2416 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002417 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002418 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002419 return true;
2420 }
2421 }
2422 return false;
2423}
2424
Eric Laurent275e8e92014-11-30 15:14:47 -08002425// Register a list of custom mixes with their attributes and format.
2426// When a mix is registered, corresponding input and output profiles are
2427// added to the remote submix hw module. The profile contains only the
2428// parameters (sampling rate, format...) specified by the mix.
2429// The corresponding input remote submix device is also connected.
2430//
2431// When a remote submix device is connected, the address is checked to select the
2432// appropriate profile and the corresponding input or output stream is opened.
2433//
2434// When capture starts, getInputForAttr() will:
2435// - 1 look for a mix matching the address passed in attribtutes tags if any
2436// - 2 if none found, getDeviceForInputSource() will:
2437// - 2.1 look for a mix matching the attributes source
2438// - 2.2 if none found, default to device selection by policy rules
2439// At this time, the corresponding output remote submix device is also connected
2440// and active playback use cases can be transferred to this mix if needed when reconnecting
2441// after AudioTracks are invalidated
2442//
2443// When playback starts, getOutputForAttr() will:
2444// - 1 look for a mix matching the address passed in attribtutes tags if any
2445// - 2 if none found, look for a mix matching the attributes usage
2446// - 3 if none found, default to device and output selection by policy rules.
2447
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002448status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002449{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002450 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2451 status_t res = NO_ERROR;
2452
2453 sp<HwModule> rSubmixModule;
2454 // examine each mix's route type
2455 for (size_t i = 0; i < mixes.size(); i++) {
2456 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2457 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2458 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002459 break;
2460 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002461 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2462 // Loop back through "remote submix"
2463 if (rSubmixModule == 0) {
2464 for (size_t j = 0; i < mHwModules.size(); j++) {
2465 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2466 && mHwModules[j]->mHandle != 0) {
2467 rSubmixModule = mHwModules[j];
2468 break;
2469 }
2470 }
2471 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002472
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002473 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002474
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002475 if (rSubmixModule == 0) {
2476 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2477 res = INVALID_OPERATION;
2478 break;
2479 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002480
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002481 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002482
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002483 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002484 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 res = INVALID_OPERATION;
2486 break;
2487 }
2488 audio_config_t outputConfig = mixes[i].mFormat;
2489 audio_config_t inputConfig = mixes[i].mFormat;
2490 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2491 // stereo and let audio flinger do the channel conversion if needed.
2492 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2493 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2494 rSubmixModule->addOutputProfile(address, &outputConfig,
2495 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2496 rSubmixModule->addInputProfile(address, &inputConfig,
2497 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002498
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002499 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2500 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2501 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2502 address.string(), "remote-submix");
2503 } else {
2504 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2505 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2506 address.string(), "remote-submix");
2507 }
2508 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002509 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002511 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2512 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002513
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002514 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002515 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2516 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2517 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2518 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2519 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2520 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002521 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2522 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2524 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002525 } else {
2526 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002527 }
2528 break;
2529 }
2530 }
2531
2532 if (res != NO_ERROR) {
2533 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002534 i, device, address.string());
2535 res = INVALID_OPERATION;
2536 break;
2537 } else if (!foundOutput) {
2538 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2539 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 res = INVALID_OPERATION;
2541 break;
2542 }
Eric Laurentc722f302014-12-10 11:21:49 -08002543 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002544 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002545 if (res != NO_ERROR) {
2546 unregisterPolicyMixes(mixes);
2547 }
2548 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002549}
2550
2551status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2552{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002553 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002554 status_t res = NO_ERROR;
2555 sp<HwModule> rSubmixModule;
2556 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002557 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002559
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002560 if (rSubmixModule == 0) {
2561 for (size_t j = 0; i < mHwModules.size(); j++) {
2562 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2563 && mHwModules[j]->mHandle != 0) {
2564 rSubmixModule = mHwModules[j];
2565 break;
2566 }
2567 }
2568 }
2569 if (rSubmixModule == 0) {
2570 res = INVALID_OPERATION;
2571 continue;
2572 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002573
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002574 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002575
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002576 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2577 res = INVALID_OPERATION;
2578 continue;
2579 }
2580
2581 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2582 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2583 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2584 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2585 address.string(), "remote-submix");
2586 }
2587 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2588 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2589 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2590 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2591 address.string(), "remote-submix");
2592 }
2593 rSubmixModule->removeOutputProfile(address);
2594 rSubmixModule->removeInputProfile(address);
2595
2596 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2597 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2598 res = INVALID_OPERATION;
2599 continue;
2600 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002601 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002602 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002604}
2605
Eric Laurente552edb2014-03-10 17:42:56 -07002606
Eric Laurente0720872014-03-11 09:30:41 -07002607status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002608{
2609 const size_t SIZE = 256;
2610 char buffer[SIZE];
2611 String8 result;
2612
2613 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2614 result.append(buffer);
2615
Eric Laurent87ffa392015-05-22 10:32:38 -07002616 snprintf(buffer, SIZE, " Primary Output: %d\n",
2617 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002618 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002619 std::string stateLiteral;
2620 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2621 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002622 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002623 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002624 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002625 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002626 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002627 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002628 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002629 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002630 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002631 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002632 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002633 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002634 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002635 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002636 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002637 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2638 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2639 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002640 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2641 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002642 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2643 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002644
François Gaffie2110e042015-03-24 08:41:51 +01002645 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002646
François Gaffie112b0af2015-11-19 16:13:25 +01002647 mAvailableOutputDevices.dump(fd, String8("Available output"));
2648 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002649 mHwModules.dump(fd);
2650 mOutputs.dump(fd);
2651 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002652 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002653 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002654 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002655 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002656
2657 return NO_ERROR;
2658}
2659
2660// This function checks for the parameters which can be offloaded.
2661// This can be enhanced depending on the capability of the DSP and policy
2662// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002663bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002664{
2665 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002666 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002667 offloadInfo.sample_rate, offloadInfo.channel_mask,
2668 offloadInfo.format,
2669 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2670 offloadInfo.has_video);
2671
Andy Hung2ddee192015-12-18 17:34:44 -08002672 if (mMasterMono) {
2673 return false; // no offloading if mono is set.
2674 }
2675
Eric Laurente552edb2014-03-10 17:42:56 -07002676 // Check if offload has been disabled
2677 char propValue[PROPERTY_VALUE_MAX];
2678 if (property_get("audio.offload.disable", propValue, "0")) {
2679 if (atoi(propValue) != 0) {
2680 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2681 return false;
2682 }
2683 }
2684
2685 // Check if stream type is music, then only allow offload as of now.
2686 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2687 {
2688 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2689 return false;
2690 }
2691
2692 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002693 const bool allowOffloadWithVideo =
2694 property_get_bool("audio.offload.video", false /* default_value */);
2695 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002696 ALOGV("isOffloadSupported: has_video == true, returning false");
2697 return false;
2698 }
2699
2700 //If duration is less than minimum value defined in property, return false
2701 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2702 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2703 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2704 return false;
2705 }
2706 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2707 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2708 return false;
2709 }
2710
2711 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2712 // creating an offloaded track and tearing it down immediately after start when audioflinger
2713 // detects there is an active non offloadable effect.
2714 // FIXME: We should check the audio session here but we do not have it in this context.
2715 // This may prevent offloading in rare situations where effects are left active by apps
2716 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002717 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002718 return false;
2719 }
2720
2721 // See if there is a profile to support this.
2722 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002723 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002724 offloadInfo.sample_rate,
2725 offloadInfo.format,
2726 offloadInfo.channel_mask,
2727 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002728 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2729 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002730}
2731
Eric Laurent6a94d692014-05-20 11:18:06 -07002732status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2733 audio_port_type_t type,
2734 unsigned int *num_ports,
2735 struct audio_port *ports,
2736 unsigned int *generation)
2737{
2738 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2739 generation == NULL) {
2740 return BAD_VALUE;
2741 }
2742 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2743 if (ports == NULL) {
2744 *num_ports = 0;
2745 }
2746
2747 size_t portsWritten = 0;
2748 size_t portsMax = *num_ports;
2749 *num_ports = 0;
2750 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002751 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2752 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002753 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002754 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2755 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2756 continue;
2757 }
2758 if (portsWritten < portsMax) {
2759 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2760 }
2761 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002762 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002763 }
2764 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002765 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2766 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2767 continue;
2768 }
2769 if (portsWritten < portsMax) {
2770 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2771 }
2772 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002773 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002774 }
2775 }
2776 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2777 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2778 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2779 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2780 }
2781 *num_ports += mInputs.size();
2782 }
2783 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002784 size_t numOutputs = 0;
2785 for (size_t i = 0; i < mOutputs.size(); i++) {
2786 if (!mOutputs[i]->isDuplicated()) {
2787 numOutputs++;
2788 if (portsWritten < portsMax) {
2789 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2790 }
2791 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002792 }
Eric Laurent84c70242014-06-23 08:46:27 -07002793 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002794 }
2795 }
2796 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002797 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 return NO_ERROR;
2799}
2800
2801status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2802{
2803 return NO_ERROR;
2804}
2805
Eric Laurent6a94d692014-05-20 11:18:06 -07002806status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2807 audio_patch_handle_t *handle,
2808 uid_t uid)
2809{
2810 ALOGV("createAudioPatch()");
2811
2812 if (handle == NULL || patch == NULL) {
2813 return BAD_VALUE;
2814 }
2815 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2816
Eric Laurent874c42872014-08-08 15:13:39 -07002817 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2818 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2819 return BAD_VALUE;
2820 }
2821 // only one source per audio patch supported for now
2822 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 return INVALID_OPERATION;
2824 }
Eric Laurent874c42872014-08-08 15:13:39 -07002825
2826 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 return INVALID_OPERATION;
2828 }
Eric Laurent874c42872014-08-08 15:13:39 -07002829 for (size_t i = 0; i < patch->num_sinks; i++) {
2830 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2831 return INVALID_OPERATION;
2832 }
2833 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002834
2835 sp<AudioPatch> patchDesc;
2836 ssize_t index = mAudioPatches.indexOfKey(*handle);
2837
Eric Laurent6a94d692014-05-20 11:18:06 -07002838 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2839 patch->sources[0].role,
2840 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002841#if LOG_NDEBUG == 0
2842 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002843 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002844 patch->sinks[i].role,
2845 patch->sinks[i].type);
2846 }
2847#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002848
2849 if (index >= 0) {
2850 patchDesc = mAudioPatches.valueAt(index);
2851 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2852 mUidCached, patchDesc->mUid, uid);
2853 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2854 return INVALID_OPERATION;
2855 }
2856 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002857 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 }
2859
2860 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002861 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002862 if (outputDesc == NULL) {
2863 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2864 return BAD_VALUE;
2865 }
Eric Laurent84c70242014-06-23 08:46:27 -07002866 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2867 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002868 if (patchDesc != 0) {
2869 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2870 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2871 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2872 return BAD_VALUE;
2873 }
2874 }
Eric Laurent874c42872014-08-08 15:13:39 -07002875 DeviceVector devices;
2876 for (size_t i = 0; i < patch->num_sinks; i++) {
2877 // Only support mix to devices connection
2878 // TODO add support for mix to mix connection
2879 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2880 ALOGV("createAudioPatch() source mix but sink is not a device");
2881 return INVALID_OPERATION;
2882 }
2883 sp<DeviceDescriptor> devDesc =
2884 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2885 if (devDesc == 0) {
2886 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2887 return BAD_VALUE;
2888 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002889
François Gaffie53615e22015-03-19 09:24:12 +01002890 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002891 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002892 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002893 NULL, // updatedSamplingRate
2894 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002895 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002896 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002897 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002898 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002899 ALOGV("createAudioPatch() profile not supported for device %08x",
2900 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002901 return INVALID_OPERATION;
2902 }
2903 devices.add(devDesc);
2904 }
2905 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002906 return INVALID_OPERATION;
2907 }
Eric Laurent874c42872014-08-08 15:13:39 -07002908
Eric Laurent6a94d692014-05-20 11:18:06 -07002909 // TODO: reconfigure output format and channels here
2910 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002911 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002912 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002913 index = mAudioPatches.indexOfKey(*handle);
2914 if (index >= 0) {
2915 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2916 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2917 }
2918 patchDesc = mAudioPatches.valueAt(index);
2919 patchDesc->mUid = uid;
2920 ALOGV("createAudioPatch() success");
2921 } else {
2922 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2923 return INVALID_OPERATION;
2924 }
2925 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2926 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2927 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002928 // only one sink supported when connecting an input device to a mix
2929 if (patch->num_sinks > 1) {
2930 return INVALID_OPERATION;
2931 }
François Gaffie53615e22015-03-19 09:24:12 +01002932 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 if (inputDesc == NULL) {
2934 return BAD_VALUE;
2935 }
2936 if (patchDesc != 0) {
2937 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2938 return BAD_VALUE;
2939 }
2940 }
2941 sp<DeviceDescriptor> devDesc =
2942 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2943 if (devDesc == 0) {
2944 return BAD_VALUE;
2945 }
2946
François Gaffie53615e22015-03-19 09:24:12 +01002947 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002948 devDesc->mAddress,
2949 patch->sinks[0].sample_rate,
2950 NULL, /*updatedSampleRate*/
2951 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002952 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002953 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002954 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002955 // FIXME for the parameter type,
2956 // and the NONE
2957 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002958 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002959 return INVALID_OPERATION;
2960 }
2961 // TODO: reconfigure output format and channels here
2962 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002963 devDesc->type(), inputDesc->mIoHandle);
2964 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002965 index = mAudioPatches.indexOfKey(*handle);
2966 if (index >= 0) {
2967 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2968 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2969 }
2970 patchDesc = mAudioPatches.valueAt(index);
2971 patchDesc->mUid = uid;
2972 ALOGV("createAudioPatch() success");
2973 } else {
2974 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2975 return INVALID_OPERATION;
2976 }
2977 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2978 // device to device connection
2979 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002980 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002981 return BAD_VALUE;
2982 }
2983 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002984 sp<DeviceDescriptor> srcDeviceDesc =
2985 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002986 if (srcDeviceDesc == 0) {
2987 return BAD_VALUE;
2988 }
Eric Laurent874c42872014-08-08 15:13:39 -07002989
Eric Laurent6a94d692014-05-20 11:18:06 -07002990 //update source and sink with our own data as the data passed in the patch may
2991 // be incomplete.
2992 struct audio_patch newPatch = *patch;
2993 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002994
Eric Laurent874c42872014-08-08 15:13:39 -07002995 for (size_t i = 0; i < patch->num_sinks; i++) {
2996 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2997 ALOGV("createAudioPatch() source device but one sink is not a device");
2998 return INVALID_OPERATION;
2999 }
3000
3001 sp<DeviceDescriptor> sinkDeviceDesc =
3002 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3003 if (sinkDeviceDesc == 0) {
3004 return BAD_VALUE;
3005 }
3006 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3007
Eric Laurent3bcf8592015-04-03 12:13:24 -07003008 // create a software bridge in PatchPanel if:
3009 // - source and sink devices are on differnt HW modules OR
3010 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003011 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003012 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003013 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003014 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003015 return INVALID_OPERATION;
3016 }
Eric Laurent874c42872014-08-08 15:13:39 -07003017 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003018 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003019 // if the sink device is reachable via an opened output stream, request to go via
3020 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003021 audio_io_handle_t output = selectOutput(outputs,
3022 AUDIO_OUTPUT_FLAG_NONE,
3023 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003024 if (output != AUDIO_IO_HANDLE_NONE) {
3025 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3026 if (outputDesc->isDuplicated()) {
3027 return INVALID_OPERATION;
3028 }
3029 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003030 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003031 newPatch.num_sources = 2;
3032 }
Eric Laurent83b88082014-06-20 18:31:16 -07003033 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003034 }
3035 // TODO: check from routing capabilities in config file and other conflicting patches
3036
3037 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3038 if (index >= 0) {
3039 afPatchHandle = patchDesc->mAfPatchHandle;
3040 }
3041
3042 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3043 &afPatchHandle,
3044 0);
3045 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3046 status, afPatchHandle);
3047 if (status == NO_ERROR) {
3048 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003049 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 addAudioPatch(patchDesc->mHandle, patchDesc);
3051 } else {
3052 patchDesc->mPatch = newPatch;
3053 }
3054 patchDesc->mAfPatchHandle = afPatchHandle;
3055 *handle = patchDesc->mHandle;
3056 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003057 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 } else {
3059 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3060 status);
3061 return INVALID_OPERATION;
3062 }
3063 } else {
3064 return BAD_VALUE;
3065 }
3066 } else {
3067 return BAD_VALUE;
3068 }
3069 return NO_ERROR;
3070}
3071
3072status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3073 uid_t uid)
3074{
3075 ALOGV("releaseAudioPatch() patch %d", handle);
3076
3077 ssize_t index = mAudioPatches.indexOfKey(handle);
3078
3079 if (index < 0) {
3080 return BAD_VALUE;
3081 }
3082 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3083 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3084 mUidCached, patchDesc->mUid, uid);
3085 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3086 return INVALID_OPERATION;
3087 }
3088
3089 struct audio_patch *patch = &patchDesc->mPatch;
3090 patchDesc->mUid = mUidCached;
3091 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003092 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003093 if (outputDesc == NULL) {
3094 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3095 return BAD_VALUE;
3096 }
3097
Eric Laurentc75307b2015-03-17 15:29:32 -07003098 setOutputDevice(outputDesc,
3099 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003100 true,
3101 0,
3102 NULL);
3103 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3104 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003105 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003106 if (inputDesc == NULL) {
3107 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3108 return BAD_VALUE;
3109 }
3110 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003111 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003112 true,
3113 NULL);
3114 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003115 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3116 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3117 status, patchDesc->mAfPatchHandle);
3118 removeAudioPatch(patchDesc->mHandle);
3119 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003120 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003121 } else {
3122 return BAD_VALUE;
3123 }
3124 } else {
3125 return BAD_VALUE;
3126 }
3127 return NO_ERROR;
3128}
3129
3130status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3131 struct audio_patch *patches,
3132 unsigned int *generation)
3133{
François Gaffie53615e22015-03-19 09:24:12 +01003134 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003135 return BAD_VALUE;
3136 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003137 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003138 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003139}
3140
Eric Laurente1715a42014-05-20 11:30:42 -07003141status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003142{
Eric Laurente1715a42014-05-20 11:30:42 -07003143 ALOGV("setAudioPortConfig()");
3144
3145 if (config == NULL) {
3146 return BAD_VALUE;
3147 }
3148 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3149 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003150 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3151 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003152 }
3153
Eric Laurenta121f902014-06-03 13:32:54 -07003154 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003155 if (config->type == AUDIO_PORT_TYPE_MIX) {
3156 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003157 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003158 if (outputDesc == NULL) {
3159 return BAD_VALUE;
3160 }
Eric Laurent84c70242014-06-23 08:46:27 -07003161 ALOG_ASSERT(!outputDesc->isDuplicated(),
3162 "setAudioPortConfig() called on duplicated output %d",
3163 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003164 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003165 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003166 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003167 if (inputDesc == NULL) {
3168 return BAD_VALUE;
3169 }
Eric Laurenta121f902014-06-03 13:32:54 -07003170 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003171 } else {
3172 return BAD_VALUE;
3173 }
3174 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3175 sp<DeviceDescriptor> deviceDesc;
3176 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3177 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3178 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3179 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3180 } else {
3181 return BAD_VALUE;
3182 }
3183 if (deviceDesc == NULL) {
3184 return BAD_VALUE;
3185 }
Eric Laurenta121f902014-06-03 13:32:54 -07003186 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003187 } else {
3188 return BAD_VALUE;
3189 }
3190
Eric Laurenta121f902014-06-03 13:32:54 -07003191 struct audio_port_config backupConfig;
3192 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3193 if (status == NO_ERROR) {
3194 struct audio_port_config newConfig;
3195 audioPortConfig->toAudioPortConfig(&newConfig, config);
3196 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003197 }
Eric Laurenta121f902014-06-03 13:32:54 -07003198 if (status != NO_ERROR) {
3199 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003200 }
Eric Laurente1715a42014-05-20 11:30:42 -07003201
3202 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003203}
3204
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003205void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3206{
Eric Laurentd60560a2015-04-10 11:31:20 -07003207 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003208 clearAudioPatches(uid);
3209 clearSessionRoutes(uid);
3210}
3211
Eric Laurent6a94d692014-05-20 11:18:06 -07003212void AudioPolicyManager::clearAudioPatches(uid_t uid)
3213{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003214 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003215 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3216 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003217 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003218 }
3219 }
3220}
3221
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003222void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3223 audio_io_handle_t ouptutToSkip)
3224{
3225 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3226 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3227 for (size_t j = 0; j < mOutputs.size(); j++) {
3228 if (mOutputs.keyAt(j) == ouptutToSkip) {
3229 continue;
3230 }
3231 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3232 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3233 continue;
3234 }
3235 // If the default device for this strategy is on another output mix,
3236 // invalidate all tracks in this strategy to force re connection.
3237 // Otherwise select new device on the output mix.
3238 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003239 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003240 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3241 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3242 }
3243 }
3244 } else {
3245 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3246 setOutputDevice(outputDesc, newDevice, false);
3247 }
3248 }
3249}
3250
3251void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3252{
3253 // remove output routes associated with this uid
3254 SortedVector<routing_strategy> affectedStrategies;
3255 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3256 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3257 if (route->mUid == uid) {
3258 mOutputRoutes.removeItemsAt(i);
3259 if (route->mDeviceDescriptor != 0) {
3260 affectedStrategies.add(getStrategy(route->mStreamType));
3261 }
3262 }
3263 }
3264 // reroute outputs if necessary
3265 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3266 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3267 }
3268
3269 // remove input routes associated with this uid
3270 SortedVector<audio_source_t> affectedSources;
3271 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3272 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3273 if (route->mUid == uid) {
3274 mInputRoutes.removeItemsAt(i);
3275 if (route->mDeviceDescriptor != 0) {
3276 affectedSources.add(route->mSource);
3277 }
3278 }
3279 }
3280 // reroute inputs if necessary
3281 SortedVector<audio_io_handle_t> inputsToClose;
3282 for (size_t i = 0; i < mInputs.size(); i++) {
3283 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003284 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003285 inputsToClose.add(inputDesc->mIoHandle);
3286 }
3287 }
3288 for (size_t i = 0; i < inputsToClose.size(); i++) {
3289 closeInput(inputsToClose[i]);
3290 }
3291}
3292
Eric Laurentd60560a2015-04-10 11:31:20 -07003293void AudioPolicyManager::clearAudioSources(uid_t uid)
3294{
3295 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3296 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3297 if (sourceDesc->mUid == uid) {
3298 stopAudioSource(mAudioSources.keyAt(i));
3299 }
3300 }
3301}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003302
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003303status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3304 audio_io_handle_t *ioHandle,
3305 audio_devices_t *device)
3306{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003307 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3308 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003309 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003310
François Gaffiedf372692015-03-19 10:43:27 +01003311 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003312}
3313
Eric Laurentd60560a2015-04-10 11:31:20 -07003314status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3315 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003316 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003317 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003318{
Eric Laurentd60560a2015-04-10 11:31:20 -07003319 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3320 if (source == NULL || attributes == NULL || handle == NULL) {
3321 return BAD_VALUE;
3322 }
3323
Glenn Kasten559d4392016-03-29 13:42:57 -07003324 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003325
3326 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3327 source->type != AUDIO_PORT_TYPE_DEVICE) {
3328 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3329 return INVALID_OPERATION;
3330 }
3331
3332 sp<DeviceDescriptor> srcDeviceDesc =
3333 mAvailableInputDevices.getDevice(source->ext.device.type,
3334 String8(source->ext.device.address));
3335 if (srcDeviceDesc == 0) {
3336 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3337 return BAD_VALUE;
3338 }
3339 sp<AudioSourceDescriptor> sourceDesc =
3340 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3341
3342 struct audio_patch dummyPatch;
3343 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3344 sourceDesc->mPatchDesc = patchDesc;
3345
3346 status_t status = connectAudioSource(sourceDesc);
3347 if (status == NO_ERROR) {
3348 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3349 *handle = sourceDesc->getHandle();
3350 }
3351 return status;
3352}
3353
3354status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3355{
3356 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3357
3358 // make sure we only have one patch per source.
3359 disconnectAudioSource(sourceDesc);
3360
3361 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003362 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003363 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3364
3365 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3366 sp<DeviceDescriptor> sinkDeviceDesc =
3367 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3368
3369 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3370 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3371
3372 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3373 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003374 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003375 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3376 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3377 // create patch between src device and output device
3378 // create Hwoutput and add to mHwOutputs
3379 } else {
3380 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3381 audio_io_handle_t output =
3382 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3383 if (output == AUDIO_IO_HANDLE_NONE) {
3384 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3385 return INVALID_OPERATION;
3386 }
3387 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3388 if (outputDesc->isDuplicated()) {
3389 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3390 return INVALID_OPERATION;
3391 }
3392 // create a special patch with no sink and two sources:
3393 // - the second source indicates to PatchPanel through which output mix this patch should
3394 // be connected as well as the stream type for volume control
3395 // - the sink is defined by whatever output device is currently selected for the output
3396 // though which this patch is routed.
3397 patch->num_sinks = 0;
3398 patch->num_sources = 2;
3399 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3400 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3401 patch->sources[1].ext.mix.usecase.stream = stream;
3402 status_t status = mpClientInterface->createAudioPatch(patch,
3403 &afPatchHandle,
3404 0);
3405 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3406 status, afPatchHandle);
3407 if (status != NO_ERROR) {
3408 ALOGW("%s patch panel could not connect device patch, error %d",
3409 __FUNCTION__, status);
3410 return INVALID_OPERATION;
3411 }
3412 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003413 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003414
3415 if (status != NO_ERROR) {
3416 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3417 return status;
3418 }
3419 sourceDesc->mSwOutput = outputDesc;
3420 if (delayMs != 0) {
3421 usleep(delayMs * 1000);
3422 }
3423 }
3424
3425 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3426 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3427
3428 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003429}
3430
Glenn Kasten559d4392016-03-29 13:42:57 -07003431status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003432{
Eric Laurentd60560a2015-04-10 11:31:20 -07003433 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3434 ALOGV("%s handle %d", __FUNCTION__, handle);
3435 if (sourceDesc == 0) {
3436 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3437 return BAD_VALUE;
3438 }
3439 status_t status = disconnectAudioSource(sourceDesc);
3440
3441 mAudioSources.removeItem(handle);
3442 return status;
3443}
3444
Andy Hung2ddee192015-12-18 17:34:44 -08003445status_t AudioPolicyManager::setMasterMono(bool mono)
3446{
3447 if (mMasterMono == mono) {
3448 return NO_ERROR;
3449 }
3450 mMasterMono = mono;
3451 // if enabling mono we close all offloaded devices, which will invalidate the
3452 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3453 // for recreating the new AudioTrack as non-offloaded PCM.
3454 //
3455 // If disabling mono, we leave all tracks as is: we don't know which clients
3456 // and tracks are able to be recreated as offloaded. The next "song" should
3457 // play back offloaded.
3458 if (mMasterMono) {
3459 Vector<audio_io_handle_t> offloaded;
3460 for (size_t i = 0; i < mOutputs.size(); ++i) {
3461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3462 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3463 offloaded.push(desc->mIoHandle);
3464 }
3465 }
3466 for (size_t i = 0; i < offloaded.size(); ++i) {
3467 closeOutput(offloaded[i]);
3468 }
3469 }
3470 // update master mono for all remaining outputs
3471 for (size_t i = 0; i < mOutputs.size(); ++i) {
3472 updateMono(mOutputs.keyAt(i));
3473 }
3474 return NO_ERROR;
3475}
3476
3477status_t AudioPolicyManager::getMasterMono(bool *mono)
3478{
3479 *mono = mMasterMono;
3480 return NO_ERROR;
3481}
3482
Eric Laurentac9cef52017-06-09 15:46:26 -07003483float AudioPolicyManager::getStreamVolumeDB(
3484 audio_stream_type_t stream, int index, audio_devices_t device)
3485{
3486 return computeVolume(stream, index, device);
3487}
3488
Eric Laurentd60560a2015-04-10 11:31:20 -07003489status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3490{
3491 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3492
3493 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3494 if (patchDesc == 0) {
3495 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3496 sourceDesc->mPatchDesc->mHandle);
3497 return BAD_VALUE;
3498 }
3499 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3500
Eric Laurent28d09f02016-03-08 10:43:05 -08003501 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003502 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3503 if (swOutputDesc != 0) {
3504 stopSource(swOutputDesc, stream, false);
3505 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3506 } else {
3507 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3508 if (hwOutputDesc != 0) {
3509 // release patch between src device and output device
3510 // close Hwoutput and remove from mHwOutputs
3511 } else {
3512 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3513 }
3514 }
3515 return NO_ERROR;
3516}
3517
3518sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3519 audio_io_handle_t output, routing_strategy strategy)
3520{
3521 sp<AudioSourceDescriptor> source;
3522 for (size_t i = 0; i < mAudioSources.size(); i++) {
3523 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3524 routing_strategy sourceStrategy =
3525 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3526 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3527 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3528 source = sourceDesc;
3529 break;
3530 }
3531 }
3532 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003533}
3534
Eric Laurente552edb2014-03-10 17:42:56 -07003535// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003536// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003537// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003538uint32_t AudioPolicyManager::nextAudioPortGeneration()
3539{
3540 return android_atomic_inc(&mAudioPortGeneration);
3541}
3542
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003543#ifdef USE_XML_AUDIO_POLICY_CONF
3544// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3545static const char *kConfigLocationList[] =
3546 {"/odm/etc", "/vendor/etc", "/system/etc"};
3547static const int kConfigLocationListSize =
3548 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3549
3550static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3551 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3552 status_t ret;
3553
3554 for (int i = 0; i < kConfigLocationListSize; i++) {
3555 PolicySerializer serializer;
3556 snprintf(audioPolicyXmlConfigFile,
3557 sizeof(audioPolicyXmlConfigFile),
3558 "%s/%s",
3559 kConfigLocationList[i],
3560 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3561 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3562 if (ret == NO_ERROR) {
3563 break;
3564 }
3565 }
3566 return ret;
3567}
3568#endif
3569
Eric Laurente0720872014-03-11 09:30:41 -07003570AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003571 :
3572#ifdef AUDIO_POLICY_TEST
3573 Thread(false),
3574#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003575 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003576 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003577 mAudioPortGeneration(1),
3578 mBeaconMuteRefCount(0),
3579 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003580 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003581 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003582 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003583 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3584 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003585{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003586 mUidCached = getuid();
3587 mpClientInterface = clientInterface;
3588
3589 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3590 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3591 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3592 bool speakerDrcEnabled = false;
3593
3594#ifdef USE_XML_AUDIO_POLICY_CONF
3595 mVolumeCurves = new VolumeCurvesCollection();
3596 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3597 mDefaultOutputDevice, speakerDrcEnabled,
3598 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003599 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003600#else
3601 mVolumeCurves = new StreamDescriptorCollection();
3602 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3603 mDefaultOutputDevice, speakerDrcEnabled);
3604 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3605 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3606#endif
3607 ALOGE("could not load audio policy configuration file, setting defaults");
3608 config.setDefault();
3609 }
3610 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3611 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3612
3613 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003614 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3615 if (!engineInstance) {
3616 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3617 return;
3618 }
3619 // Retrieve the Policy Manager Interface
3620 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3621 if (mEngine == NULL) {
3622 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3623 return;
3624 }
3625 mEngine->setObserver(this);
3626 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003627 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003628 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3629
Eric Laurent3a4311c2014-03-17 12:00:47 -07003630 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003631 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003632 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3633 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003634 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003635 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003636 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003637 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003638 continue;
3639 }
3640 // open all output streams needed to access attached devices
3641 // except for direct output streams that are only opened when they are actually
3642 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003643 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003644 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3645 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003646 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003647
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003648 if (!outProfile->hasSupportedDevices()) {
3649 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003650 continue;
3651 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003652 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003653 mTtsOutputAvailable = true;
3654 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003656 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003657 continue;
3658 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003659 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003660 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3661 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003662 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003663 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003664 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003665 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003666 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003667 if ((profileType & outputDeviceTypes) == 0) {
3668 continue;
3669 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003670 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3671 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003672 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3673 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3674 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3675 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003676
3677 outputDesc->mDevice = profileType;
3678 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3679 config.sample_rate = outputDesc->mSamplingRate;
3680 config.channel_mask = outputDesc->mChannelMask;
3681 config.format = outputDesc->mFormat;
3682 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003683 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003684 &output,
3685 &config,
3686 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003687 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003688 &outputDesc->mLatency,
3689 outputDesc->mFlags);
3690
3691 if (status != NO_ERROR) {
3692 ALOGW("Cannot open output stream for device %08x on hw module %s",
3693 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003694 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003695 } else {
3696 outputDesc->mSamplingRate = config.sample_rate;
3697 outputDesc->mChannelMask = config.channel_mask;
3698 outputDesc->mFormat = config.format;
3699
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003700 for (size_t k = 0; k < supportedDevices.size(); k++) {
3701 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003702 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003703 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3704 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003705 }
3706 }
3707 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003708 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003709 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003710 }
3711 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003712 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003713 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003714 true,
3715 0,
3716 NULL,
3717 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003718 }
Eric Laurente552edb2014-03-10 17:42:56 -07003719 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003720 // open input streams needed to access attached devices to validate
3721 // mAvailableInputDevices list
3722 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3723 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003724 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003725
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003726 if (!inProfile->hasSupportedDevices()) {
3727 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003728 continue;
3729 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003730 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003731 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003732 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3733
Eric Laurentd78f1532014-09-16 16:38:20 -07003734 if ((profileType & inputDeviceTypes) == 0) {
3735 continue;
3736 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003737 sp<AudioInputDescriptor> inputDesc =
3738 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003739
Eric Laurentd78f1532014-09-16 16:38:20 -07003740 inputDesc->mDevice = profileType;
3741
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003742 // find the address
3743 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3744 // the inputs vector must be of size 1, but we don't want to crash here
3745 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3746 : String8("");
3747 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3748 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3749
Eric Laurentd78f1532014-09-16 16:38:20 -07003750 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3751 config.sample_rate = inputDesc->mSamplingRate;
3752 config.channel_mask = inputDesc->mChannelMask;
3753 config.format = inputDesc->mFormat;
3754 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003755 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003756 &input,
3757 &config,
3758 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003759 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003760 AUDIO_SOURCE_MIC,
3761 AUDIO_INPUT_FLAG_NONE);
3762
3763 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003764 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3765 for (size_t k = 0; k < supportedDevices.size(); k++) {
3766 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003767 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003768 if (index >= 0) {
3769 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3770 if (!devDesc->isAttached()) {
3771 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003772 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003773 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003774 }
3775 }
3776 mpClientInterface->closeInput(input);
3777 } else {
3778 ALOGW("Cannot open input stream for device %08x on hw module %s",
3779 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003780 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003781 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003782 }
3783 }
3784 // make sure all attached devices have been allocated a unique ID
3785 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003786 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003787 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003788 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3789 continue;
3790 }
François Gaffie2110e042015-03-24 08:41:51 +01003791 // The device is now validated and can be appended to the available devices of the engine
3792 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3793 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003794 i++;
3795 }
3796 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003797 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003798 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003799 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3800 continue;
3801 }
François Gaffie2110e042015-03-24 08:41:51 +01003802 // The device is now validated and can be appended to the available devices of the engine
3803 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3804 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003805 i++;
3806 }
3807 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003808 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003809 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003810 }
Eric Laurente552edb2014-03-10 17:42:56 -07003811
3812 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3813
3814 updateDevicesAndOutputs();
3815
3816#ifdef AUDIO_POLICY_TEST
3817 if (mPrimaryOutput != 0) {
3818 AudioParameter outputCmd = AudioParameter();
3819 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003820 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003821
3822 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3823 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003824 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3825 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003826 mTestLatencyMs = 0;
3827 mCurOutput = 0;
3828 mDirectOutput = false;
3829 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3830 mTestOutputs[i] = 0;
3831 }
3832
3833 const size_t SIZE = 256;
3834 char buffer[SIZE];
3835 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3836 run(buffer, ANDROID_PRIORITY_AUDIO);
3837 }
3838#endif //AUDIO_POLICY_TEST
3839}
3840
Eric Laurente0720872014-03-11 09:30:41 -07003841AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003842{
3843#ifdef AUDIO_POLICY_TEST
3844 exit();
3845#endif //AUDIO_POLICY_TEST
3846 for (size_t i = 0; i < mOutputs.size(); i++) {
3847 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003848 }
3849 for (size_t i = 0; i < mInputs.size(); i++) {
3850 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003851 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003852 mAvailableOutputDevices.clear();
3853 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003854 mOutputs.clear();
3855 mInputs.clear();
3856 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003857}
3858
Eric Laurente0720872014-03-11 09:30:41 -07003859status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003860{
Eric Laurent87ffa392015-05-22 10:32:38 -07003861 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003862}
3863
3864#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003865bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003866{
3867 ALOGV("entering threadLoop()");
3868 while (!exitPending())
3869 {
3870 String8 command;
3871 int valueInt;
3872 String8 value;
3873
3874 Mutex::Autolock _l(mLock);
3875 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3876
3877 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3878 AudioParameter param = AudioParameter(command);
3879
3880 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3881 valueInt != 0) {
3882 ALOGV("Test command %s received", command.string());
3883 String8 target;
3884 if (param.get(String8("target"), target) != NO_ERROR) {
3885 target = "Manager";
3886 }
3887 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3888 param.remove(String8("test_cmd_policy_output"));
3889 mCurOutput = valueInt;
3890 }
3891 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3892 param.remove(String8("test_cmd_policy_direct"));
3893 if (value == "false") {
3894 mDirectOutput = false;
3895 } else if (value == "true") {
3896 mDirectOutput = true;
3897 }
3898 }
3899 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3900 param.remove(String8("test_cmd_policy_input"));
3901 mTestInput = valueInt;
3902 }
3903
3904 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3905 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003906 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003907 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003908 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003909 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003910 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003911 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003912 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003913 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003914 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003915 if (target == "Manager") {
3916 mTestFormat = format;
3917 } else if (mTestOutputs[mCurOutput] != 0) {
3918 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003919 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003920 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3921 }
3922 }
3923 }
3924 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3925 param.remove(String8("test_cmd_policy_channels"));
3926 int channels = 0;
3927
3928 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003929 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003930 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003931 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003932 }
3933 if (channels != 0) {
3934 if (target == "Manager") {
3935 mTestChannels = channels;
3936 } else if (mTestOutputs[mCurOutput] != 0) {
3937 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003938 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003939 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3940 }
3941 }
3942 }
3943 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3944 param.remove(String8("test_cmd_policy_sampleRate"));
3945 if (valueInt >= 0 && valueInt <= 96000) {
3946 int samplingRate = valueInt;
3947 if (target == "Manager") {
3948 mTestSamplingRate = samplingRate;
3949 } else if (mTestOutputs[mCurOutput] != 0) {
3950 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003951 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003952 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3953 }
3954 }
3955 }
3956
3957 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3958 param.remove(String8("test_cmd_policy_reopen"));
3959
Eric Laurentc75307b2015-03-17 15:29:32 -07003960 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003961
Eric Laurentc75307b2015-03-17 15:29:32 -07003962 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003963
Eric Laurentc75307b2015-03-17 15:29:32 -07003964 removeOutput(mPrimaryOutput->mIoHandle);
3965 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3966 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003967 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003968 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3969 config.sample_rate = outputDesc->mSamplingRate;
3970 config.channel_mask = outputDesc->mChannelMask;
3971 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003972 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003973 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003974 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003975 &config,
3976 &outputDesc->mDevice,
3977 String8(""),
3978 &outputDesc->mLatency,
3979 outputDesc->mFlags);
3980 if (status != NO_ERROR) {
3981 ALOGE("Failed to reopen hardware output stream, "
3982 "samplingRate: %d, format %d, channels %d",
3983 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003984 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003985 outputDesc->mSamplingRate = config.sample_rate;
3986 outputDesc->mChannelMask = config.channel_mask;
3987 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003988 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003989 AudioParameter outputCmd = AudioParameter();
3990 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003991 mpClientInterface->setParameters(handle, outputCmd.toString());
3992 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003993 }
3994 }
3995
3996
3997 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3998 }
3999 }
4000 return false;
4001}
4002
Eric Laurente0720872014-03-11 09:30:41 -07004003void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07004004{
4005 {
4006 AutoMutex _l(mLock);
4007 requestExit();
4008 mWaitWorkCV.signal();
4009 }
4010 requestExitAndWait();
4011}
4012
Eric Laurente0720872014-03-11 09:30:41 -07004013int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004014{
4015 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
4016 if (output == mTestOutputs[i]) return i;
4017 }
4018 return 0;
4019}
4020#endif //AUDIO_POLICY_TEST
4021
4022// ---
4023
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004024void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004025{
François Gaffie98cc1912015-03-18 17:52:40 +01004026 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07004027 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08004028 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004029 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004030 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004031}
4032
François Gaffie53615e22015-03-19 09:24:12 +01004033void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4034{
4035 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004036 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004037}
4038
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004039void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004040{
François Gaffie98cc1912015-03-18 17:52:40 +01004041 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004042 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004043 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004044}
Eric Laurente552edb2014-03-10 17:42:56 -07004045
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004046void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004047 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004048 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004049 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004050 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004051 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004052 if (devDesc != 0) {
4053 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4054 desc->mIoHandle, address.string());
4055 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004056 }
4057}
4058
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004059status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004060 audio_policy_dev_state_t state,
4061 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004062 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004063{
François Gaffie53615e22015-03-19 09:24:12 +01004064 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004065 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004066
4067 if (audio_device_is_digital(device)) {
4068 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004069 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004070 }
Eric Laurente552edb2014-03-10 17:42:56 -07004071
Eric Laurent3b73df72014-03-11 09:06:29 -07004072 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004073 // first list already open outputs that can be routed to this device
4074 for (size_t i = 0; i < mOutputs.size(); i++) {
4075 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004076 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004077 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004078 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4079 outputs.add(mOutputs.keyAt(i));
4080 } else {
4081 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004082 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004083 }
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
4085 }
4086 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004087 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07004088 for (size_t i = 0; i < mHwModules.size(); i++)
4089 {
4090 if (mHwModules[i]->mHandle == 0) {
4091 continue;
4092 }
4093 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4094 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004095 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004096 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004097 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004098 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004099 profiles.add(profile);
4100 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
4101 }
Eric Laurente552edb2014-03-10 17:42:56 -07004102 }
4103 }
4104 }
4105
Eric Laurent7b279bb2015-12-14 10:18:23 -08004106 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004107
Eric Laurente552edb2014-03-10 17:42:56 -07004108 if (profiles.isEmpty() && outputs.isEmpty()) {
4109 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4110 return BAD_VALUE;
4111 }
4112
4113 // open outputs for matching profiles if needed. Direct outputs are also opened to
4114 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4115 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004116 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004117
4118 // nothing to do if one output is already opened for this profile
4119 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004120 for (j = 0; j < outputs.size(); j++) {
4121 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004122 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004123 // matching profile: save the sample rates, format and channel masks supported
4124 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004125 if (audio_device_is_digital(device)) {
4126 devDesc->importAudioPort(profile);
4127 }
Eric Laurente552edb2014-03-10 17:42:56 -07004128 break;
4129 }
4130 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004131 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004132 continue;
4133 }
4134
Eric Laurent83efe1c2017-07-09 16:51:08 -07004135 ALOGV("opening output for device %08x with params %s profile %p name %s",
4136 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004137 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07004138 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004139 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4140 config.sample_rate = desc->mSamplingRate;
4141 config.channel_mask = desc->mChannelMask;
4142 config.format = desc->mFormat;
4143 config.offload_info.sample_rate = desc->mSamplingRate;
4144 config.offload_info.channel_mask = desc->mChannelMask;
4145 config.offload_info.format = desc->mFormat;
4146 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004147 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004148 &output,
4149 &config,
4150 &desc->mDevice,
4151 address,
4152 &desc->mLatency,
4153 desc->mFlags);
4154 if (status == NO_ERROR) {
4155 desc->mSamplingRate = config.sample_rate;
4156 desc->mChannelMask = config.channel_mask;
4157 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07004158
Eric Laurentd4692962014-05-05 18:13:44 -07004159 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004160 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004161 char *param = audio_device_address_to_parameter(device, address);
4162 mpClientInterface->setParameters(output, String8(param));
4163 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004164 }
Phil Burk00eeb322016-03-31 12:41:00 -07004165 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004166 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004167 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07004168 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004169 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004170 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004171 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08004172 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004173 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004174 config.offload_info.sample_rate = config.sample_rate;
4175 config.offload_info.channel_mask = config.channel_mask;
4176 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07004177 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004178 &output,
4179 &config,
4180 &desc->mDevice,
4181 address,
4182 &desc->mLatency,
4183 desc->mFlags);
4184 if (status == NO_ERROR) {
4185 desc->mSamplingRate = config.sample_rate;
4186 desc->mChannelMask = config.channel_mask;
4187 desc->mFormat = config.format;
4188 } else {
4189 output = AUDIO_IO_HANDLE_NONE;
4190 }
Eric Laurentd4692962014-05-05 18:13:44 -07004191 }
4192
Eric Laurentcf2c0212014-07-25 16:20:43 -07004193 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004194 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004195 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004196 sp<AudioPolicyMix> policyMix;
4197 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004198 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4199 address.string());
4200 }
François Gaffie036e1e92015-03-19 10:16:24 +01004201 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004202 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004203
Eric Laurent87ffa392015-05-22 10:32:38 -07004204 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4205 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004206 // no duplicated output for direct outputs and
4207 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004208 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004209
Eric Laurentd4692962014-05-05 18:13:44 -07004210 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07004211 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07004212
Eric Laurentd4692962014-05-05 18:13:44 -07004213 //TODO: configure audio effect output stage here
4214
4215 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07004216 duplicatedOutput =
4217 mpClientInterface->openDuplicateOutput(output,
4218 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004219 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004220 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07004221 sp<SwAudioOutputDescriptor> dupOutputDesc =
4222 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4223 dupOutputDesc->mOutput1 = mPrimaryOutput;
4224 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07004225 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4226 dupOutputDesc->mFormat = desc->mFormat;
4227 dupOutputDesc->mChannelMask = desc->mChannelMask;
4228 dupOutputDesc->mLatency = desc->mLatency;
4229 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004230 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004231 } else {
4232 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004233 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004234 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004235 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004236 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004237 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004238 }
Eric Laurente552edb2014-03-10 17:42:56 -07004239 }
4240 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004241 } else {
4242 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004243 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004244 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004245 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004246 profiles.removeAt(profile_index);
4247 profile_index--;
4248 } else {
4249 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004250 // Load digital format info only for digital devices
4251 if (audio_device_is_digital(device)) {
4252 devDesc->importAudioPort(profile);
4253 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004254
François Gaffie53615e22015-03-19 09:24:12 +01004255 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004256 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4257 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004258 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004259 NULL/*patch handle*/, address.string());
4260 }
Eric Laurente552edb2014-03-10 17:42:56 -07004261 ALOGV("checkOutputsForDevice(): adding output %d", output);
4262 }
4263 }
4264
4265 if (profiles.isEmpty()) {
4266 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4267 return BAD_VALUE;
4268 }
Eric Laurentd4692962014-05-05 18:13:44 -07004269 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004270 // check if one opened output is not needed any more after disconnecting one device
4271 for (size_t i = 0; i < mOutputs.size(); i++) {
4272 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004273 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004274 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004275 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004276 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004277 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004278 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004279 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4280 mOutputs.keyAt(i));
4281 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004282 }
Eric Laurente552edb2014-03-10 17:42:56 -07004283 }
4284 }
Eric Laurentd4692962014-05-05 18:13:44 -07004285 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004286 for (size_t i = 0; i < mHwModules.size(); i++)
4287 {
4288 if (mHwModules[i]->mHandle == 0) {
4289 continue;
4290 }
4291 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4292 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004293 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004294 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004295 ALOGV("checkOutputsForDevice(): "
4296 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004297 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004298 }
4299 }
4300 }
4301 }
4302 return NO_ERROR;
4303}
4304
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004305status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004306 audio_policy_dev_state_t state,
4307 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004308 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004309{
Paul McLean9080a4c2015-06-18 08:24:02 -07004310 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004311 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004312
4313 if (audio_device_is_digital(device)) {
4314 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004315 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004316 }
4317
Eric Laurentd4692962014-05-05 18:13:44 -07004318 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4319 // first list already open inputs that can be routed to this device
4320 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4321 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004322 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004323 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4324 inputs.add(mInputs.keyAt(input_index));
4325 }
4326 }
4327
4328 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004329 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004330 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4331 {
4332 if (mHwModules[module_idx]->mHandle == 0) {
4333 continue;
4334 }
4335 for (size_t profile_index = 0;
4336 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4337 profile_index++)
4338 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004339 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4340
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004341 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004342 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004343 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004344 profiles.add(profile);
4345 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4346 profile_index, module_idx);
4347 }
Eric Laurentd4692962014-05-05 18:13:44 -07004348 }
4349 }
4350 }
4351
4352 if (profiles.isEmpty() && inputs.isEmpty()) {
4353 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4354 return BAD_VALUE;
4355 }
4356
4357 // open inputs for matching profiles if needed. Direct inputs are also opened to
4358 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4359 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4360
Eric Laurent1c333e22014-05-20 10:48:17 -07004361 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004362 // nothing to do if one input is already opened for this profile
4363 size_t input_index;
4364 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4365 desc = mInputs.valueAt(input_index);
4366 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004367 if (audio_device_is_digital(device)) {
4368 devDesc->importAudioPort(profile);
4369 }
Eric Laurentd4692962014-05-05 18:13:44 -07004370 break;
4371 }
4372 }
4373 if (input_index != mInputs.size()) {
4374 continue;
4375 }
4376
4377 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4378 desc = new AudioInputDescriptor(profile);
4379 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004380 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4381 config.sample_rate = desc->mSamplingRate;
4382 config.channel_mask = desc->mChannelMask;
4383 config.format = desc->mFormat;
4384 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004385
4386 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4387 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4388
Eric Laurent322b4d22015-04-03 15:57:54 -07004389 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004390 &input,
4391 &config,
4392 &desc->mDevice,
4393 address,
4394 AUDIO_SOURCE_MIC,
4395 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004396
Eric Laurentcf2c0212014-07-25 16:20:43 -07004397 if (status == NO_ERROR) {
4398 desc->mSamplingRate = config.sample_rate;
4399 desc->mChannelMask = config.channel_mask;
4400 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004401
Eric Laurentd4692962014-05-05 18:13:44 -07004402 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004403 char *param = audio_device_address_to_parameter(device, address);
4404 mpClientInterface->setParameters(input, String8(param));
4405 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004406 }
Phil Burk00eeb322016-03-31 12:41:00 -07004407 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004408 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004409 ALOGW("checkInputsForDevice() direct input missing param");
4410 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004411 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004412 }
4413
4414 if (input != 0) {
4415 addInput(input, desc);
4416 }
4417 } // endif input != 0
4418
Eric Laurentcf2c0212014-07-25 16:20:43 -07004419 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004420 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004421 profiles.removeAt(profile_index);
4422 profile_index--;
4423 } else {
4424 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004425 if (audio_device_is_digital(device)) {
4426 devDesc->importAudioPort(profile);
4427 }
Eric Laurentd4692962014-05-05 18:13:44 -07004428 ALOGV("checkInputsForDevice(): adding input %d", input);
4429 }
4430 } // end scan profiles
4431
4432 if (profiles.isEmpty()) {
4433 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4434 return BAD_VALUE;
4435 }
4436 } else {
4437 // Disconnect
4438 // check if one opened input is not needed any more after disconnecting one device
4439 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4440 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004441 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004442 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4443 mInputs.keyAt(input_index));
4444 inputs.add(mInputs.keyAt(input_index));
4445 }
4446 }
4447 // Clear any profiles associated with the disconnected device.
4448 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4449 if (mHwModules[module_index]->mHandle == 0) {
4450 continue;
4451 }
4452 for (size_t profile_index = 0;
4453 profile_index < mHwModules[module_index]->mInputProfiles.size();
4454 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004455 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004456 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004457 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004458 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004459 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004460 }
4461 }
4462 }
4463 } // end disconnect
4464
4465 return NO_ERROR;
4466}
4467
4468
Eric Laurente0720872014-03-11 09:30:41 -07004469void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004470{
4471 ALOGV("closeOutput(%d)", output);
4472
Eric Laurentc75307b2015-03-17 15:29:32 -07004473 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004474 if (outputDesc == NULL) {
4475 ALOGW("closeOutput() unknown output %d", output);
4476 return;
4477 }
François Gaffie036e1e92015-03-19 10:16:24 +01004478 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004479
Eric Laurente552edb2014-03-10 17:42:56 -07004480 // look for duplicated outputs connected to the output being removed.
4481 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004482 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004483 if (dupOutputDesc->isDuplicated() &&
4484 (dupOutputDesc->mOutput1 == outputDesc ||
4485 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004486 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004487 if (dupOutputDesc->mOutput1 == outputDesc) {
4488 outputDesc2 = dupOutputDesc->mOutput2;
4489 } else {
4490 outputDesc2 = dupOutputDesc->mOutput1;
4491 }
4492 // As all active tracks on duplicated output will be deleted,
4493 // and as they were also referenced on the other output, the reference
4494 // count for their stream type must be adjusted accordingly on
4495 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004496 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004497 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004498 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004499 }
4500 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4501 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4502
4503 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004504 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004505 }
4506 }
4507
Eric Laurent05b90f82014-08-27 15:32:29 -07004508 nextAudioPortGeneration();
4509
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004510 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004511 if (index >= 0) {
4512 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004513 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004514 mAudioPatches.removeItemsAt(index);
4515 mpClientInterface->onAudioPatchListUpdate();
4516 }
4517
Eric Laurente552edb2014-03-10 17:42:56 -07004518 AudioParameter param;
4519 param.add(String8("closing"), String8("true"));
4520 mpClientInterface->setParameters(output, param.toString());
4521
4522 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004523 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004524 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004525}
4526
4527void AudioPolicyManager::closeInput(audio_io_handle_t input)
4528{
4529 ALOGV("closeInput(%d)", input);
4530
4531 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4532 if (inputDesc == NULL) {
4533 ALOGW("closeInput() unknown input %d", input);
4534 return;
4535 }
4536
Eric Laurent6a94d692014-05-20 11:18:06 -07004537 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004538
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004539 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004540 if (index >= 0) {
4541 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004542 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004543 mAudioPatches.removeItemsAt(index);
4544 mpClientInterface->onAudioPatchListUpdate();
4545 }
4546
4547 mpClientInterface->closeInput(input);
4548 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004549}
4550
Eric Laurentc75307b2015-03-17 15:29:32 -07004551SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4552 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004553 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004554{
4555 SortedVector<audio_io_handle_t> outputs;
4556
4557 ALOGVV("getOutputsForDevice() device %04x", device);
4558 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004559 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004560 i, openOutputs.valueAt(i)->isDuplicated(),
4561 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004562 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4563 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4564 outputs.add(openOutputs.keyAt(i));
4565 }
4566 }
4567 return outputs;
4568}
4569
Eric Laurente0720872014-03-11 09:30:41 -07004570bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004571 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004572{
4573 if (outputs1.size() != outputs2.size()) {
4574 return false;
4575 }
4576 for (size_t i = 0; i < outputs1.size(); i++) {
4577 if (outputs1[i] != outputs2[i]) {
4578 return false;
4579 }
4580 }
4581 return true;
4582}
4583
Eric Laurente0720872014-03-11 09:30:41 -07004584void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004585{
4586 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4587 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4588 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4589 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4590
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004591 // also take into account external policy-related changes: add all outputs which are
4592 // associated with policies in the "before" and "after" output vectors
4593 ALOGVV("checkOutputForStrategy(): policy related outputs");
4594 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004595 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004596 if (desc != 0 && desc->mPolicyMix != NULL) {
4597 srcOutputs.add(desc->mIoHandle);
4598 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4599 }
4600 }
4601 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004602 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004603 if (desc != 0 && desc->mPolicyMix != NULL) {
4604 dstOutputs.add(desc->mIoHandle);
4605 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4606 }
4607 }
4608
Eric Laurente552edb2014-03-10 17:42:56 -07004609 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4610 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4611 strategy, srcOutputs[0], dstOutputs[0]);
4612 // mute strategy while moving tracks from one output to another
4613 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004614 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004615 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004616 setStrategyMute(strategy, true, desc);
4617 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004618 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004619 sp<AudioSourceDescriptor> source =
4620 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4621 if (source != 0){
4622 connectAudioSource(source);
4623 }
Eric Laurente552edb2014-03-10 17:42:56 -07004624 }
4625
4626 // Move effects associated to this strategy from previous output to new output
4627 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004628 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004629 }
4630 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004631 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004632 if (getStrategy((audio_stream_type_t)i) == strategy) {
4633 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004634 }
4635 }
4636 }
4637}
4638
Eric Laurente0720872014-03-11 09:30:41 -07004639void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004640{
François Gaffie2110e042015-03-24 08:41:51 +01004641 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004642 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004643 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004644 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004645 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004646 checkOutputForStrategy(STRATEGY_SONIFICATION);
4647 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004648 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004649 checkOutputForStrategy(STRATEGY_MEDIA);
4650 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004651 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004652}
4653
Eric Laurente0720872014-03-11 09:30:41 -07004654void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004655{
François Gaffie53615e22015-03-19 09:24:12 +01004656 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004657 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004658 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004659 return;
4660 }
4661
Eric Laurent3a4311c2014-03-17 12:00:47 -07004662 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004663 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4664 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4665 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004666
4667 // if suspended, restore A2DP output if:
4668 // ((SCO device is NOT connected) ||
4669 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4670 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004671 //
Eric Laurentf732e072016-08-03 19:30:28 -07004672 // if not suspended, suspend A2DP output if:
4673 // (SCO device is connected) &&
4674 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4675 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004676 //
4677 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004678 if (!isScoConnected ||
4679 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4680 AUDIO_POLICY_FORCE_BT_SCO) &&
4681 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4682 AUDIO_POLICY_FORCE_BT_SCO) &&
4683 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004684 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004685
4686 mpClientInterface->restoreOutput(a2dpOutput);
4687 mA2dpSuspended = false;
4688 }
4689 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004690 if (isScoConnected &&
4691 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4692 AUDIO_POLICY_FORCE_BT_SCO) ||
4693 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4694 AUDIO_POLICY_FORCE_BT_SCO) ||
4695 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004696 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004697
4698 mpClientInterface->suspendOutput(a2dpOutput);
4699 mA2dpSuspended = true;
4700 }
4701 }
4702}
4703
Eric Laurentc75307b2015-03-17 15:29:32 -07004704audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4705 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004706{
4707 audio_devices_t device = AUDIO_DEVICE_NONE;
4708
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004709 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 if (index >= 0) {
4711 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4712 if (patchDesc->mUid != mUidCached) {
4713 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004714 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004715 return outputDesc->device();
4716 }
4717 }
4718
Eric Laurente552edb2014-03-10 17:42:56 -07004719 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004720 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004721 // use device for strategy enforced audible
4722 // 2: we are in call or the strategy phone is active on the output:
4723 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004724 // 3: the strategy for enforced audible is active but not enforced on the output:
4725 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004726 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004727 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004728 // 5: the strategy accessibility is active on the output:
4729 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004730 // 6: the strategy "respectful" sonification is active on the output:
4731 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004732 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004733 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004734 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004735 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004736 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004737 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004738 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004739 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004740 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4741 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004742 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004743 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004744 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004745 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004746 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004747 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004748 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4749 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004750 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004751 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004752 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004753 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004754 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004755 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004756 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004757 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004758 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004759 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004760 }
4761
Eric Laurent1c333e22014-05-20 10:48:17 -07004762 ALOGV("getNewOutputDevice() selected device %x", device);
4763 return device;
4764}
4765
Eric Laurentfb66dd92016-01-28 18:32:03 -08004766audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004767{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004768 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004769
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004770 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004771 if (index >= 0) {
4772 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4773 if (patchDesc->mUid != mUidCached) {
4774 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004775 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 return inputDesc->mDevice;
4777 }
4778 }
4779
Eric Laurentfb66dd92016-01-28 18:32:03 -08004780 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4781 if (isInCall()) {
4782 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4783 } else if (source != AUDIO_SOURCE_DEFAULT) {
4784 device = getDeviceAndMixForInputSource(source);
4785 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004786
Eric Laurente552edb2014-03-10 17:42:56 -07004787 return device;
4788}
4789
Eric Laurent794fde22016-03-11 09:50:45 -08004790bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4791 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004792 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004793}
4794
Eric Laurente0720872014-03-11 09:30:41 -07004795uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004796 return (uint32_t)getStrategy(stream);
4797}
4798
Eric Laurente0720872014-03-11 09:30:41 -07004799audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004800 // By checking the range of stream before calling getStrategy, we avoid
4801 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4802 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004803 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 return AUDIO_DEVICE_NONE;
4805 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004806 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004807 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4808 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004809 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004810 }
Eric Laurent794fde22016-03-11 09:50:45 -08004811 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004812 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004813 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004814 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4815 for (size_t i = 0; i < outputs.size(); i++) {
4816 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004817 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004818 curDevices |= outputDesc->device();
4819 }
4820 }
4821 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004822 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004823
4824 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4825 and doesn't really need to.*/
4826 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4827 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4828 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4829 }
Eric Laurente552edb2014-03-10 17:42:56 -07004830 return devices;
4831}
4832
François Gaffie2110e042015-03-24 08:41:51 +01004833routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4834{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004835 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004836 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004837}
4838
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004839uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4840 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004841 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4842 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4843 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004844 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4845 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4846 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004847 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004848 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004849}
4850
Eric Laurente0720872014-03-11 09:30:41 -07004851void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004852 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004853 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004854 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4855 updateDevicesAndOutputs();
4856 break;
4857 default:
4858 break;
4859 }
4860}
4861
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004862uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004863
4864 // skip beacon mute management if a dedicated TTS output is available
4865 if (mTtsOutputAvailable) {
4866 return 0;
4867 }
4868
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004869 switch(event) {
4870 case STARTING_OUTPUT:
4871 mBeaconMuteRefCount++;
4872 break;
4873 case STOPPING_OUTPUT:
4874 if (mBeaconMuteRefCount > 0) {
4875 mBeaconMuteRefCount--;
4876 }
4877 break;
4878 case STARTING_BEACON:
4879 mBeaconPlayingRefCount++;
4880 break;
4881 case STOPPING_BEACON:
4882 if (mBeaconPlayingRefCount > 0) {
4883 mBeaconPlayingRefCount--;
4884 }
4885 break;
4886 }
4887
4888 if (mBeaconMuteRefCount > 0) {
4889 // any playback causes beacon to be muted
4890 return setBeaconMute(true);
4891 } else {
4892 // no other playback: unmute when beacon starts playing, mute when it stops
4893 return setBeaconMute(mBeaconPlayingRefCount == 0);
4894 }
4895}
4896
4897uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4898 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4899 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4900 // keep track of muted state to avoid repeating mute/unmute operations
4901 if (mBeaconMuted != mute) {
4902 // mute/unmute AUDIO_STREAM_TTS on all outputs
4903 ALOGV("\t muting %d", mute);
4904 uint32_t maxLatency = 0;
4905 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004906 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004907 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004908 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004909 0 /*delay*/, AUDIO_DEVICE_NONE);
4910 const uint32_t latency = desc->latency() * 2;
4911 if (latency > maxLatency) {
4912 maxLatency = latency;
4913 }
4914 }
4915 mBeaconMuted = mute;
4916 return maxLatency;
4917 }
4918 return 0;
4919}
4920
Eric Laurente0720872014-03-11 09:30:41 -07004921audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004922 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004923{
Paul McLeanaa981192015-03-21 09:55:15 -07004924 // Routing
4925 // see if we have an explicit route
4926 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4927 // (getStrategy(stream)).
4928 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4929 // and activity count is non-zero
4930 // the device = the device from the descriptor in the RouteMap, and exit.
4931 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4932 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004933 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4934 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004935 return route->mDeviceDescriptor->type();
4936 }
4937 }
4938
Eric Laurente552edb2014-03-10 17:42:56 -07004939 if (fromCache) {
4940 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4941 strategy, mDeviceForStrategy[strategy]);
4942 return mDeviceForStrategy[strategy];
4943 }
François Gaffie2110e042015-03-24 08:41:51 +01004944 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004945}
4946
Eric Laurente0720872014-03-11 09:30:41 -07004947void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004948{
4949 for (int i = 0; i < NUM_STRATEGIES; i++) {
4950 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4951 }
4952 mPreviousOutputs = mOutputs;
4953}
4954
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004955uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004956 audio_devices_t prevDevice,
4957 uint32_t delayMs)
4958{
4959 // mute/unmute strategies using an incompatible device combination
4960 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4961 // if unmuting, unmute only after the specified delay
4962 if (outputDesc->isDuplicated()) {
4963 return 0;
4964 }
4965
4966 uint32_t muteWaitMs = 0;
4967 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004968 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004969
4970 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4971 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004972 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004973 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4974 bool doMute = false;
4975
4976 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4977 doMute = true;
4978 outputDesc->mStrategyMutedByDevice[i] = true;
4979 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4980 doMute = true;
4981 outputDesc->mStrategyMutedByDevice[i] = false;
4982 }
Eric Laurent99401132014-05-07 19:48:15 -07004983 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004984 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004985 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004986 // skip output if it does not share any device with current output
4987 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4988 == AUDIO_DEVICE_NONE) {
4989 continue;
4990 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004991 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004992 mute ? "muting" : "unmuting", i, curDevice);
4993 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004994 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004995 if (mute) {
4996 // FIXME: should not need to double latency if volume could be applied
4997 // immediately by the audioflinger mixer. We must account for the delay
4998 // between now and the next time the audioflinger thread for this output
4999 // will process a buffer (which corresponds to one buffer size,
5000 // usually 1/2 or 1/4 of the latency).
5001 if (muteWaitMs < desc->latency() * 2) {
5002 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005003 }
5004 }
5005 }
5006 }
5007 }
5008 }
5009
Eric Laurent99401132014-05-07 19:48:15 -07005010 // temporary mute output if device selection changes to avoid volume bursts due to
5011 // different per device volumes
5012 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005013 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5014 // temporary mute duration is conservatively set to 4 times the reported latency
5015 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5016 if (muteWaitMs < tempMuteWaitMs) {
5017 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005018 }
Eric Laurentdc462862016-07-19 12:29:53 -07005019
Eric Laurent99401132014-05-07 19:48:15 -07005020 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005021 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005022 // make sure that we do not start the temporary mute period too early in case of
5023 // delayed device change
5024 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005025 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005026 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005027 }
5028 }
5029 }
5030
Eric Laurente552edb2014-03-10 17:42:56 -07005031 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5032 if (muteWaitMs > delayMs) {
5033 muteWaitMs -= delayMs;
5034 usleep(muteWaitMs * 1000);
5035 return muteWaitMs;
5036 }
5037 return 0;
5038}
5039
Eric Laurentc75307b2015-03-17 15:29:32 -07005040uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005041 audio_devices_t device,
5042 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005044 audio_patch_handle_t *patchHandle,
5045 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07005046{
Eric Laurentc75307b2015-03-17 15:29:32 -07005047 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005048 AudioParameter param;
5049 uint32_t muteWaitMs;
5050
5051 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005052 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
5053 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005054 return muteWaitMs;
5055 }
5056 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5057 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005058 if ((device != AUDIO_DEVICE_NONE) &&
5059 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005060 return 0;
5061 }
5062
5063 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005064 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005065
5066 audio_devices_t prevDevice = outputDesc->mDevice;
5067
Paul McLeanaa981192015-03-21 09:55:15 -07005068 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005069
5070 if (device != AUDIO_DEVICE_NONE) {
5071 outputDesc->mDevice = device;
5072 }
5073 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5074
5075 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005076 // the requested device is AUDIO_DEVICE_NONE
5077 // OR the requested device is the same as current device
5078 // AND force is not specified
5079 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005080 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005081 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5082 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005083 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005084 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005085 return muteWaitMs;
5086 }
5087
5088 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005089
Eric Laurente552edb2014-03-10 17:42:56 -07005090 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005091 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005092 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005093 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005094 DeviceVector deviceList;
5095 if ((address == NULL) || (strlen(address) == 0)) {
5096 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5097 } else {
5098 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5099 }
5100
Eric Laurent1c333e22014-05-20 10:48:17 -07005101 if (!deviceList.isEmpty()) {
5102 struct audio_patch patch;
5103 outputDesc->toAudioPortConfig(&patch.sources[0]);
5104 patch.num_sources = 1;
5105 patch.num_sinks = 0;
5106 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5107 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005108 patch.num_sinks++;
5109 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 ssize_t index;
5111 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5112 index = mAudioPatches.indexOfKey(*patchHandle);
5113 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005114 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005115 }
5116 sp< AudioPatch> patchDesc;
5117 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5118 if (index >= 0) {
5119 patchDesc = mAudioPatches.valueAt(index);
5120 afPatchHandle = patchDesc->mAfPatchHandle;
5121 }
5122
Eric Laurent1c333e22014-05-20 10:48:17 -07005123 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 &afPatchHandle,
5125 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005126 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5127 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005128 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005129 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005130 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005131 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 addAudioPatch(patchDesc->mHandle, patchDesc);
5133 } else {
5134 patchDesc->mPatch = patch;
5135 }
5136 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005137 if (patchHandle) {
5138 *patchHandle = patchDesc->mHandle;
5139 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005140 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005141 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005142 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005143 }
5144 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005145
5146 // inform all input as well
5147 for (size_t i = 0; i < mInputs.size(); i++) {
5148 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005149 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005150 AudioParameter inputCmd = AudioParameter();
5151 ALOGV("%s: inform input %d of device:%d", __func__,
5152 inputDescriptor->mIoHandle, device);
5153 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5154 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5155 inputCmd.toString(),
5156 delayMs);
5157 }
5158 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005159 }
Eric Laurente552edb2014-03-10 17:42:56 -07005160
5161 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005162 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005163
5164 return muteWaitMs;
5165}
5166
Eric Laurentc75307b2015-03-17 15:29:32 -07005167status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005168 int delayMs,
5169 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005170{
Eric Laurent6a94d692014-05-20 11:18:06 -07005171 ssize_t index;
5172 if (patchHandle) {
5173 index = mAudioPatches.indexOfKey(*patchHandle);
5174 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005175 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 }
5177 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005178 return INVALID_OPERATION;
5179 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5181 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005182 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005183 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 removeAudioPatch(patchDesc->mHandle);
5185 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005186 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005187 return status;
5188}
5189
5190status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5191 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005192 bool force,
5193 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005194{
5195 status_t status = NO_ERROR;
5196
Eric Laurent1f2f2232014-06-02 12:01:23 -07005197 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005198 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5199 inputDesc->mDevice = device;
5200
5201 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5202 if (!deviceList.isEmpty()) {
5203 struct audio_patch patch;
5204 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005205 // AUDIO_SOURCE_HOTWORD is for internal use only:
5206 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005207 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005208 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005209 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5210 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005211 patch.num_sinks = 1;
5212 //only one input device for now
5213 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005214 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 ssize_t index;
5216 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5217 index = mAudioPatches.indexOfKey(*patchHandle);
5218 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005219 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 }
5221 sp< AudioPatch> patchDesc;
5222 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5223 if (index >= 0) {
5224 patchDesc = mAudioPatches.valueAt(index);
5225 afPatchHandle = patchDesc->mAfPatchHandle;
5226 }
5227
Eric Laurent1c333e22014-05-20 10:48:17 -07005228 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005230 0);
5231 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005232 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005235 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 addAudioPatch(patchDesc->mHandle, patchDesc);
5237 } else {
5238 patchDesc->mPatch = patch;
5239 }
5240 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005241 if (patchHandle) {
5242 *patchHandle = patchDesc->mHandle;
5243 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005244 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005246 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005247 }
5248 }
5249 }
5250 return status;
5251}
5252
Eric Laurent6a94d692014-05-20 11:18:06 -07005253status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5254 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005255{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005256 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 ssize_t index;
5258 if (patchHandle) {
5259 index = mAudioPatches.indexOfKey(*patchHandle);
5260 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005261 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 }
5263 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 return INVALID_OPERATION;
5265 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5267 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005268 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005269 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 removeAudioPatch(patchDesc->mHandle);
5271 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005272 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005273 return status;
5274}
5275
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005276sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005277 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005278 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005279 audio_format_t& format,
5280 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005281 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
5283 // Choose an input profile based on the requested capture parameters: select the first available
5284 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005285 //
5286 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5287 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005288
5289 for (size_t i = 0; i < mHwModules.size(); i++)
5290 {
5291 if (mHwModules[i]->mHandle == 0) {
5292 continue;
5293 }
5294 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5295 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005296 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005297 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005298 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005299 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005300 format,
5301 &format /*updatedFormat*/,
5302 channelMask,
5303 &channelMask /*updatedChannelMask*/,
5304 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005305
Eric Laurente552edb2014-03-10 17:42:56 -07005306 return profile;
5307 }
5308 }
5309 }
5310 return NULL;
5311}
5312
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005313
5314audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005315 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005316{
François Gaffie036e1e92015-03-19 10:16:24 +01005317 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5318 audio_devices_t selectedDeviceFromMix =
5319 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005320
François Gaffie036e1e92015-03-19 10:16:24 +01005321 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5322 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005323 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005324 return getDeviceForInputSource(inputSource);
5325}
5326
5327audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5328{
Paul McLean466dc8e2015-04-17 13:15:36 -06005329 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5330 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005331 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005332 return route->mDeviceDescriptor->type();
5333 }
5334 }
5335
5336 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005337}
5338
Eric Laurente0720872014-03-11 09:30:41 -07005339float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005340 int index,
5341 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005342{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005343 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005344
5345 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5346 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5347 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5348 // the ringtone volume
5349 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5350 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5351 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5352 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5353 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5354 }
5355
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005356 // in-call: always cap earpiece volume by voice volume + some low headroom
5357 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5358 switch (stream) {
5359 case AUDIO_STREAM_SYSTEM:
5360 case AUDIO_STREAM_RING:
5361 case AUDIO_STREAM_MUSIC:
5362 case AUDIO_STREAM_ALARM:
5363 case AUDIO_STREAM_NOTIFICATION:
5364 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5365 case AUDIO_STREAM_DTMF:
5366 case AUDIO_STREAM_ACCESSIBILITY: {
5367 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5368 + IN_CALL_EARPIECE_HEADROOM_DB;
5369 if (volumeDB > maxVoiceVolDb) {
5370 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5371 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5372 volumeDB = maxVoiceVolDb;
5373 }
5374 } break;
5375 default:
5376 break;
5377 }
5378 }
5379
Eric Laurente552edb2014-03-10 17:42:56 -07005380 // if a headset is connected, apply the following rules to ring tones and notifications
5381 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005382 // - always attenuate notifications volume by 6dB
5383 // - attenuate ring tones volume by 6dB unless music is not playing and
5384 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005385 // - if music is playing, always limit the volume to current music volume,
5386 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005387 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005388 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5389 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5390 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005391 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5392 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005393 ((stream_strategy == STRATEGY_SONIFICATION)
5394 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005395 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005396 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005397 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005398 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005399 // when the phone is ringing we must consider that music could have been paused just before
5400 // by the music application and behave as if music was active if the last music track was
5401 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005402 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005403 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005404 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005405 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005406 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005407 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5408 musicDevice),
5409 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005410 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5411 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005412 if (volumeDB > minVolDB) {
5413 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005414 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005415 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005416 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5417 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5418 // on A2DP, also ensure notification volume is not too low compared to media when
5419 // intended to be played
5420 if ((volumeDB > -96.0f) &&
5421 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5422 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5423 stream, device,
5424 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5425 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5426 }
5427 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005428 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5429 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005430 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005431 }
5432 }
5433
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005434 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005435}
5436
Eric Laurente0720872014-03-11 09:30:41 -07005437status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005438 int index,
5439 const sp<AudioOutputDescriptor>& outputDesc,
5440 audio_devices_t device,
5441 int delayMs,
5442 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005443{
Eric Laurente552edb2014-03-10 17:42:56 -07005444 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005445 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005446 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005447 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005448 return NO_ERROR;
5449 }
François Gaffie2110e042015-03-24 08:41:51 +01005450 audio_policy_forced_cfg_t forceUseForComm =
5451 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005452 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005453 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5454 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005455 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005456 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005457 return INVALID_OPERATION;
5458 }
5459
Eric Laurentc75307b2015-03-17 15:29:32 -07005460 if (device == AUDIO_DEVICE_NONE) {
5461 device = outputDesc->device();
5462 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005463
Eric Laurentffbc80f2015-03-18 18:30:19 -07005464 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005465 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005466 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005467 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005468
Eric Laurentffbc80f2015-03-18 18:30:19 -07005469 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005470
Eric Laurent3b73df72014-03-11 09:06:29 -07005471 if (stream == AUDIO_STREAM_VOICE_CALL ||
5472 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005473 float voiceVolume;
5474 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005475 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005476 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005477 } else {
5478 voiceVolume = 1.0;
5479 }
5480
Eric Laurent18fba842016-03-31 14:41:26 -07005481 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005482 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5483 mLastVoiceVolume = voiceVolume;
5484 }
5485 }
5486
5487 return NO_ERROR;
5488}
5489
Eric Laurentc75307b2015-03-17 15:29:32 -07005490void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5491 audio_devices_t device,
5492 int delayMs,
5493 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005494{
Eric Laurentc75307b2015-03-17 15:29:32 -07005495 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005496
Eric Laurent794fde22016-03-11 09:50:45 -08005497 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005498 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005499 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005500 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005501 device,
5502 delayMs,
5503 force);
5504 }
5505}
5506
Eric Laurente0720872014-03-11 09:30:41 -07005507void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005508 bool on,
5509 const sp<AudioOutputDescriptor>& outputDesc,
5510 int delayMs,
5511 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005512{
Eric Laurent72249d52015-06-08 11:12:15 -07005513 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5514 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005515 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005516 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005517 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005518 }
5519 }
5520}
5521
Eric Laurente0720872014-03-11 09:30:41 -07005522void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005523 bool on,
5524 const sp<AudioOutputDescriptor>& outputDesc,
5525 int delayMs,
5526 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005527{
Eric Laurente552edb2014-03-10 17:42:56 -07005528 if (device == AUDIO_DEVICE_NONE) {
5529 device = outputDesc->device();
5530 }
5531
Eric Laurentc75307b2015-03-17 15:29:32 -07005532 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5533 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005534
5535 if (on) {
5536 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005537 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005538 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005539 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005540 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005541 }
5542 }
5543 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5544 outputDesc->mMuteCount[stream]++;
5545 } else {
5546 if (outputDesc->mMuteCount[stream] == 0) {
5547 ALOGV("setStreamMute() unmuting non muted stream!");
5548 return;
5549 }
5550 if (--outputDesc->mMuteCount[stream] == 0) {
5551 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005552 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005553 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005554 device,
5555 delayMs);
5556 }
5557 }
5558}
5559
Eric Laurente0720872014-03-11 09:30:41 -07005560void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005561 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005562{
Eric Laurent87ffa392015-05-22 10:32:38 -07005563 if(!hasPrimaryOutput()) {
5564 return;
5565 }
5566
Eric Laurente552edb2014-03-10 17:42:56 -07005567 // if the stream pertains to sonification strategy and we are in call we must
5568 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5569 // in the device used for phone strategy and play the tone if the selected device does not
5570 // interfere with the device used for phone strategy
5571 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5572 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005573 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005574 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5575 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005576 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005577 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5578 stream, starting, outputDesc->mDevice, stateChange);
5579 if (outputDesc->mRefCount[stream]) {
5580 int muteCount = 1;
5581 if (stateChange) {
5582 muteCount = outputDesc->mRefCount[stream];
5583 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005584 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005585 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5586 for (int i = 0; i < muteCount; i++) {
5587 setStreamMute(stream, starting, mPrimaryOutput);
5588 }
5589 } else {
5590 ALOGV("handleIncallSonification() high visibility");
5591 if (outputDesc->device() &
5592 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5593 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5594 for (int i = 0; i < muteCount; i++) {
5595 setStreamMute(stream, starting, mPrimaryOutput);
5596 }
5597 }
5598 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5600 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005601 } else {
5602 mpClientInterface->stopTone();
5603 }
5604 }
5605 }
5606 }
5607}
5608
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005609audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5610{
5611 // flags to stream type mapping
5612 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5613 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5614 }
5615 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5616 return AUDIO_STREAM_BLUETOOTH_SCO;
5617 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005618 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5619 return AUDIO_STREAM_TTS;
5620 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005621
5622 // usage to stream type mapping
5623 switch (attr->usage) {
5624 case AUDIO_USAGE_MEDIA:
5625 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005626 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005627 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5628 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005629 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5630 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005631 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5632 return AUDIO_STREAM_SYSTEM;
5633 case AUDIO_USAGE_VOICE_COMMUNICATION:
5634 return AUDIO_STREAM_VOICE_CALL;
5635
5636 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5637 return AUDIO_STREAM_DTMF;
5638
5639 case AUDIO_USAGE_ALARM:
5640 return AUDIO_STREAM_ALARM;
5641 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5642 return AUDIO_STREAM_RING;
5643
5644 case AUDIO_USAGE_NOTIFICATION:
5645 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5646 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5647 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5648 case AUDIO_USAGE_NOTIFICATION_EVENT:
5649 return AUDIO_STREAM_NOTIFICATION;
5650
5651 case AUDIO_USAGE_UNKNOWN:
5652 default:
5653 return AUDIO_STREAM_MUSIC;
5654 }
5655}
Eric Laurente83b55d2014-11-14 10:06:21 -08005656
François Gaffie53615e22015-03-19 09:24:12 +01005657bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5658{
Eric Laurente83b55d2014-11-14 10:06:21 -08005659 // has flags that map to a strategy?
5660 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5661 return true;
5662 }
5663
5664 // has known usage?
5665 switch (paa->usage) {
5666 case AUDIO_USAGE_UNKNOWN:
5667 case AUDIO_USAGE_MEDIA:
5668 case AUDIO_USAGE_VOICE_COMMUNICATION:
5669 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5670 case AUDIO_USAGE_ALARM:
5671 case AUDIO_USAGE_NOTIFICATION:
5672 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5673 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5674 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5675 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5676 case AUDIO_USAGE_NOTIFICATION_EVENT:
5677 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5678 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5679 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5680 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005681 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005682 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005683 break;
5684 default:
5685 return false;
5686 }
5687 return true;
5688}
5689
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005690bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005691 routing_strategy strategy, uint32_t inPastMs,
5692 nsecs_t sysTime) const
5693{
5694 if ((sysTime == 0) && (inPastMs != 0)) {
5695 sysTime = systemTime();
5696 }
Eric Laurent794fde22016-03-11 09:50:45 -08005697 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005698 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5699 (NUM_STRATEGIES == strategy)) &&
5700 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5701 return true;
5702 }
5703 }
5704 return false;
5705}
5706
François Gaffie2110e042015-03-24 08:41:51 +01005707audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5708{
5709 return mEngine->getForceUse(usage);
5710}
5711
5712bool AudioPolicyManager::isInCall()
5713{
5714 return isStateInCall(mEngine->getPhoneState());
5715}
5716
5717bool AudioPolicyManager::isStateInCall(int state)
5718{
5719 return is_state_in_call(state);
5720}
5721
Eric Laurentd60560a2015-04-10 11:31:20 -07005722void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5723{
5724 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5725 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5726 if (sourceDesc->mDevice->equals(deviceDesc)) {
5727 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5728 stopAudioSource(sourceDesc->getHandle());
5729 }
5730 }
5731
5732 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5733 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5734 bool release = false;
5735 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5736 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5737 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5738 source->ext.device.type == deviceDesc->type()) {
5739 release = true;
5740 }
5741 }
5742 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5743 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5744 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5745 sink->ext.device.type == deviceDesc->type()) {
5746 release = true;
5747 }
5748 }
5749 if (release) {
5750 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5751 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5752 }
5753 }
5754}
5755
Phil Burk09bc4612016-02-24 15:58:15 -08005756// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005757void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5758 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005759 // TODO Set this based on Config properties.
5760 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005761
5762 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5763 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005764 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005765
5766 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005767 bool supportsAC3 = false;
5768 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005769 bool supportsIEC61937 = false;
5770 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5771 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005772 switch (format) {
5773 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005774 supportsAC3 = true;
5775 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005776 case AUDIO_FORMAT_E_AC3:
5777 case AUDIO_FORMAT_DTS:
5778 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005779 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005780 break;
5781 case AUDIO_FORMAT_IEC61937:
5782 supportsIEC61937 = true;
5783 break;
5784 default:
5785 break;
5786 }
5787 }
Phil Burk09bc4612016-02-24 15:58:15 -08005788
5789 // Modify formats based on surround preferences.
5790 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005791 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5792 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5793 // Remove surround sound related formats.
5794 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5795 audio_format_t format = formats[formatIndex];
5796 switch(format) {
5797 case AUDIO_FORMAT_AC3:
5798 case AUDIO_FORMAT_E_AC3:
5799 case AUDIO_FORMAT_DTS:
5800 case AUDIO_FORMAT_DTS_HD:
5801 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005802 formats.removeAt(formatIndex);
5803 break;
5804 default:
5805 formatIndex++; // keep it
5806 break;
5807 }
Phil Burk09bc4612016-02-24 15:58:15 -08005808 }
Phil Burk07ac1142016-03-25 13:39:29 -07005809 supportsAC3 = false;
5810 supportsOtherSurround = false;
5811 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005812 }
Phil Burk07ac1142016-03-25 13:39:29 -07005813 } else { // AUTO or ALWAYS
5814 // Most TVs support AC3 even if they do not report it in the EDID.
5815 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5816 && !supportsAC3) {
5817 formats.add(AUDIO_FORMAT_AC3);
5818 supportsAC3 = true;
5819 }
5820
5821 // If ALWAYS, add support for raw surround formats if all are missing.
5822 // This assumes that if any of these formats are reported by the HAL
5823 // then the report is valid and should not be modified.
5824 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5825 && !supportsOtherSurround) {
5826 formats.add(AUDIO_FORMAT_E_AC3);
5827 formats.add(AUDIO_FORMAT_DTS);
5828 formats.add(AUDIO_FORMAT_DTS_HD);
5829 supportsOtherSurround = true;
5830 }
5831
5832 // Add support for IEC61937 if any raw surround supported.
5833 // The HAL could do this but add it here, just in case.
5834 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5835 formats.add(AUDIO_FORMAT_IEC61937);
5836 supportsIEC61937 = true;
5837 }
Phil Burk09bc4612016-02-24 15:58:15 -08005838 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005839}
5840
5841// Modify the list of channel masks supported.
5842void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5843 ChannelsVector &channelMasks = *channelMasksPtr;
5844 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5845 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5846
5847 // If NEVER, then remove support for channelMasks > stereo.
5848 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5849 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5850 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5851 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5852 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5853 channelMasks.removeAt(maskIndex);
5854 } else {
5855 maskIndex++;
5856 }
5857 }
5858 // If ALWAYS, then make sure we at least support 5.1
5859 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5860 bool supports5dot1 = false;
5861 // Are there any channel masks that can be considered "surround"?
5862 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5863 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5864 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5865 supports5dot1 = true;
5866 break;
5867 }
5868 }
5869 // If not then add 5.1 support.
5870 if (!supports5dot1) {
5871 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5872 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5873 }
Phil Burk09bc4612016-02-24 15:58:15 -08005874 }
5875}
5876
Phil Burk00eeb322016-03-31 12:41:00 -07005877void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5878 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005879 AudioProfileVector &profiles)
5880{
5881 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005882
François Gaffie112b0af2015-11-19 16:13:25 +01005883 // Format MUST be checked first to update the list of AudioProfile
5884 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005885 reply = mpClientInterface->getParameters(
5886 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005887 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005888 AudioParameter repliedParameters(reply);
5889 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005890 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005891 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5892 return;
5893 }
Phil Burk09bc4612016-02-24 15:58:15 -08005894 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005895 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005896 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005897 }
Phil Burk09bc4612016-02-24 15:58:15 -08005898 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005899 }
5900 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5901
Eric Laurent20eb3a42016-01-26 18:39:17 -08005902 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005903 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005904 ChannelsVector channelMasks;
5905 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005906 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005907 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005908
5909 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005910 reply = mpClientInterface->getParameters(
5911 ioHandle,
5912 requestedParameters.toString() + ";" +
5913 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005914 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005915 AudioParameter repliedParameters(reply);
5916 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005917 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005918 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005919 }
5920 }
5921 if (profiles.hasDynamicChannelsFor(format)) {
5922 reply = mpClientInterface->getParameters(ioHandle,
5923 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005924 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005925 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005926 AudioParameter repliedParameters(reply);
5927 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005928 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005929 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005930 if (device == AUDIO_DEVICE_OUT_HDMI) {
5931 filterSurroundChannelMasks(&channelMasks);
5932 }
François Gaffie112b0af2015-11-19 16:13:25 +01005933 }
5934 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005935 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005936 }
5937}
Eric Laurentd60560a2015-04-10 11:31:20 -07005938
Eric Laurente552edb2014-03-10 17:42:56 -07005939}; // namespace android