blob: 737ca59297375d9cdb22778c196d12e8723bba6f [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,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001323 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001324 outputDesc,
1325 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
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001341 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1342 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1343 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1344 }
1345
Eric Laurente552edb2014-03-10 17:42:56 -07001346 return NO_ERROR;
1347}
1348
1349
Eric Laurente0720872014-03-11 09:30:41 -07001350status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001351 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001352 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001353{
1354 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1355 ssize_t index = mOutputs.indexOfKey(output);
1356 if (index < 0) {
1357 ALOGW("stopOutput() unknown output %d", output);
1358 return BAD_VALUE;
1359 }
1360
Eric Laurentc75307b2015-03-17 15:29:32 -07001361 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001362
Eric Laurentc75307b2015-03-17 15:29:32 -07001363 if (outputDesc->mRefCount[stream] == 1) {
1364 // Automatically disable the remote submix input when output is stopped on a
1365 // re routing mix of type MIX_TYPE_RECORDERS
1366 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1367 outputDesc->mPolicyMix != NULL &&
1368 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1369 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1370 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001371 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001372 "remote-submix");
1373 }
1374 }
1375
1376 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001377 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001378 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001379 int activityCount = mOutputRoutes.decRouteActivity(session);
1380 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1381
1382 if (forceDeviceUpdate) {
1383 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1384 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001385 }
1386
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001387 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001388}
1389
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001390status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001391 audio_stream_type_t stream,
1392 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001393{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001394 // always handle stream stop, check which stream type is stopping
1395 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1396
Eric Laurente552edb2014-03-10 17:42:56 -07001397 // handle special case for sonification while in call
1398 if (isInCall()) {
1399 handleIncallSonification(stream, false, false);
1400 }
1401
1402 if (outputDesc->mRefCount[stream] > 0) {
1403 // decrement usage count of this stream on the output
1404 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001405
Eric Laurente552edb2014-03-10 17:42:56 -07001406 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001407 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001408 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001409 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001410 // delay the device switch by twice the latency because stopOutput() is executed when
1411 // the track stop() command is received and at that time the audio track buffer can
1412 // still contain data that needs to be drained. The latency only covers the audio HAL
1413 // and kernel buffers. Also the latency does not always include additional delay in the
1414 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001415 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001416
1417 // force restoring the device selection on other active outputs if it differs from the
1418 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001419 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001420 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001421 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001422 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001423 desc->isActive() &&
1424 outputDesc->sharesHwModuleWith(desc) &&
1425 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001426 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1427 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001428 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001429 newDevice2,
1430 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001431 delayMs);
1432 // re-apply device specific volume if not done by setOutputDevice()
1433 if (!force) {
1434 applyStreamVolumes(desc, newDevice2, delayMs);
1435 }
Eric Laurente552edb2014-03-10 17:42:56 -07001436 }
1437 }
1438 // update the outputs if stopping one with a stream that can affect notification routing
1439 handleNotificationRoutingForStream(stream);
1440 }
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001441
1442 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1443 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1444 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1445 }
1446
Eric Laurent36829f92017-04-07 19:04:42 -07001447 if (stream == AUDIO_STREAM_MUSIC) {
1448 selectOutputForMusicEffects();
1449 }
Eric Laurente552edb2014-03-10 17:42:56 -07001450 return NO_ERROR;
1451 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001452 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001453 return INVALID_OPERATION;
1454 }
1455}
1456
Eric Laurente83b55d2014-11-14 10:06:21 -08001457void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001458 audio_stream_type_t stream __unused,
1459 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001460{
1461 ALOGV("releaseOutput() %d", output);
1462 ssize_t index = mOutputs.indexOfKey(output);
1463 if (index < 0) {
1464 ALOGW("releaseOutput() releasing unknown output %d", output);
1465 return;
1466 }
1467
1468#ifdef AUDIO_POLICY_TEST
1469 int testIndex = testOutputIndex(output);
1470 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001471 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001472 if (outputDesc->isActive()) {
1473 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001474 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001475 mTestOutputs[testIndex] = 0;
1476 }
1477 return;
1478 }
1479#endif //AUDIO_POLICY_TEST
1480
Paul McLeanaa981192015-03-21 09:55:15 -07001481 // Routing
1482 mOutputRoutes.removeRoute(session);
1483
Eric Laurentc75307b2015-03-17 15:29:32 -07001484 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001485 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001486 if (desc->mDirectOpenCount <= 0) {
1487 ALOGW("releaseOutput() invalid open count %d for output %d",
1488 desc->mDirectOpenCount, output);
1489 return;
1490 }
1491 if (--desc->mDirectOpenCount == 0) {
1492 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001493 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001494 }
1495 }
1496}
1497
1498
Eric Laurentcaf7f482014-11-25 17:50:47 -08001499status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1500 audio_io_handle_t *input,
1501 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001502 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001503 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001504 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001505 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001506 input_type_t *inputType,
1507 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001508{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001509 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1510 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001511 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001512
Eric Laurentcb4dae22017-07-01 19:39:32 -07001513 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1514 // possible
1515 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1516 *input != AUDIO_IO_HANDLE_NONE) {
1517 ssize_t index = mInputs.indexOfKey(*input);
1518 if (index < 0) {
1519 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1520 return BAD_VALUE;
1521 }
1522 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1523 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1524 if (audioSession == 0) {
1525 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1526 return BAD_VALUE;
1527 }
1528 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1529 // The second call is for the first active client and sets the UID. Any further call
1530 // corresponds to a new client and is only permitted from the same UId.
1531 if (audioSession->openCount() == 1) {
1532 audioSession->setUid(uid);
1533 } else if (audioSession->uid() != uid) {
1534 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1535 uid, session, audioSession->uid());
1536 return INVALID_OPERATION;
1537 }
1538 audioSession->changeOpenCount(1);
1539 *inputType = API_INPUT_LEGACY;
1540 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1541 *portId = AudioPort::getNextUniqueId();
1542 }
1543 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1544 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1545 : AUDIO_PORT_HANDLE_NONE;
1546 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1547 return NO_ERROR;
1548 }
1549
Eric Laurentcaf7f482014-11-25 17:50:47 -08001550 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001551 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001552
Eric Laurent275e8e92014-11-30 15:14:47 -08001553 audio_devices_t device;
1554 // handle legacy remote submix case where the address was not always specified
1555 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001556 audio_source_t inputSource = attr->source;
1557 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001558 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001559
Eric Laurentc447ded2015-01-06 08:47:05 -08001560 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1561 inputSource = AUDIO_SOURCE_MIC;
1562 }
1563 halInputSource = inputSource;
1564
Eric Laurent20b9ef02016-12-05 11:03:16 -08001565 // TODO: check for existing client for this port ID
1566 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1567 *portId = AudioPort::getNextUniqueId();
1568 }
1569
Paul McLean466dc8e2015-04-17 13:15:36 -06001570 // Explicit routing?
1571 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001572 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1573 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1574 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1575 deviceDesc = mAvailableInputDevices[i];
1576 break;
1577 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001578 }
1579 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001580 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001581
Eric Laurentc447ded2015-01-06 08:47:05 -08001582 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001583 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001584 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001585 if (ret != NO_ERROR) {
1586 return ret;
1587 }
1588 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001589 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1590 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001591 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001592 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001593 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001594 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001595 return BAD_VALUE;
1596 }
Eric Laurentc722f302014-12-10 11:21:49 -08001597 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001598 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001599 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1600 // there is an external policy, but this input is attached to a mix of recorders,
1601 // meaning it receives audio injected into the framework, so the recorder doesn't
1602 // know about it and is therefore considered "legacy"
1603 *inputType = API_INPUT_LEGACY;
1604 } else {
1605 // recording a mix of players defined by an external policy, we're rerouting for
1606 // an external policy
1607 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1608 }
Eric Laurentc722f302014-12-10 11:21:49 -08001609 } else if (audio_is_remote_submix_device(device)) {
1610 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001611 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001612 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1613 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001614 } else {
1615 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001616 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001617
Eric Laurent599c7582015-12-07 18:05:55 -08001618 }
1619
1620 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001621 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001622 policyMix);
1623 if (*input == AUDIO_IO_HANDLE_NONE) {
1624 mInputRoutes.removeRoute(session);
1625 return INVALID_OPERATION;
1626 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001627
Eric Laurent2ac76942017-06-22 17:17:09 -07001628 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1629 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1630 : AUDIO_PORT_HANDLE_NONE;
1631
1632 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1633 *input, *inputType, *selectedDeviceId);
1634
Eric Laurent599c7582015-12-07 18:05:55 -08001635 return NO_ERROR;
1636}
1637
1638
1639audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1640 String8 address,
1641 audio_session_t session,
1642 uid_t uid,
1643 audio_source_t inputSource,
1644 uint32_t samplingRate,
1645 audio_format_t format,
1646 audio_channel_mask_t channelMask,
1647 audio_input_flags_t flags,
1648 AudioMix *policyMix)
1649{
1650 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1651 audio_source_t halInputSource = inputSource;
1652 bool isSoundTrigger = false;
1653
1654 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1655 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1656 if (index >= 0) {
1657 input = mSoundTriggerSessions.valueFor(session);
1658 isSoundTrigger = true;
1659 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1660 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1661 } else {
1662 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001663 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001664 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001665 audio_is_linear_pcm(format)) {
1666 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001667 }
1668
Andy Hungf129b032015-04-07 13:45:50 -07001669 // find a compatible input profile (not necessarily identical in parameters)
1670 sp<IOProfile> profile;
1671 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001672 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001673 audio_format_t profileFormat = format;
1674 audio_channel_mask_t profileChannelMask = channelMask;
1675 audio_input_flags_t profileFlags = flags;
1676 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001677 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001678 profileSamplingRate, profileFormat, profileChannelMask,
1679 profileFlags);
1680 if (profile != 0) {
1681 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001682 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1683 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001684 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1685 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1686 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001687 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1688 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001689 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001690 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001691 }
Eric Laurente552edb2014-03-10 17:42:56 -07001692 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001693 // Pick input sampling rate if not specified by client
1694 if (samplingRate == 0) {
1695 samplingRate = profileSamplingRate;
1696 }
Eric Laurente552edb2014-03-10 17:42:56 -07001697
Eric Laurent322b4d22015-04-03 15:57:54 -07001698 if (profile->getModuleHandle() == 0) {
1699 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001700 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001701 }
1702
Eric Laurent599c7582015-12-07 18:05:55 -08001703 sp<AudioSession> audioSession = new AudioSession(session,
1704 inputSource,
1705 format,
1706 samplingRate,
1707 channelMask,
1708 flags,
1709 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001710 isSoundTrigger,
1711 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001712
Eric Laurent74708e72017-04-07 17:13:42 -07001713// FIXME: disable concurrent capture until UI is ready
1714#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001715 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001716 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001717 for (size_t i = 0; i < mInputs.size(); i++) {
1718 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001719 // reuse input if:
1720 // - it shares the same profile
1721 // AND
1722 // - it is not a reroute submix input
1723 // AND
1724 // - it is: not used for sound trigger
1725 // OR
1726 // used for sound trigger and all clients use the same session ID
1727 //
1728 if ((profile == desc->mProfile) &&
1729 (isSoundTrigger == desc->isSoundTrigger()) &&
1730 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001731
1732 sp<AudioSession> as = desc->getAudioSession(session);
1733 if (as != 0) {
1734 // do not allow unmatching properties on same session
1735 if (as->matches(audioSession)) {
1736 as->changeOpenCount(1);
1737 } else {
1738 ALOGW("getInputForDevice() record with different attributes"
1739 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001740 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001741 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001742 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001743 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001744 }
Eric Laurentbb948092017-01-23 18:33:30 -08001745
Eric Laurent555530a2017-02-07 18:17:24 -08001746 // Reuse the already opened input stream on this profile if:
1747 // - the new capture source is background OR
1748 // - the path requested configurations match OR
1749 // - the new source priority is less than the highest source priority on this input
1750 // If the input stream cannot be reused, close it before opening a new stream
1751 // on the same profile for the new client so that the requested path configuration
1752 // can be selected.
1753 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001754 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001755 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001756 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001757 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001758 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001759 reusedInputDesc = desc;
1760 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001761 } else {
1762 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001763 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1764 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001765 }
Eric Laurent599c7582015-12-07 18:05:55 -08001766 }
1767 }
Eric Laurent599c7582015-12-07 18:05:55 -08001768
Eric Laurent555530a2017-02-07 18:17:24 -08001769 if (reusedInputDesc != 0) {
1770 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1771 for (size_t j = 0; j < sessions.size(); j++) {
1772 audio_session_t currentSession = sessions.keyAt(j);
1773 stopInput(reusedInputDesc->mIoHandle, currentSession);
1774 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1775 }
1776 }
Eric Laurent74708e72017-04-07 17:13:42 -07001777#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001778
Eric Laurentcf2c0212014-07-25 16:20:43 -07001779 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001780 config.sample_rate = profileSamplingRate;
1781 config.channel_mask = profileChannelMask;
1782 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001783
Eric Laurente3014102017-05-03 11:15:43 -07001784 if (address == "") {
1785 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1786 // the inputs vector must be of size 1, but we don't want to crash here
1787 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1788 }
1789
Eric Laurent322b4d22015-04-03 15:57:54 -07001790 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001791 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001792 &config,
1793 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001794 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001795 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001796 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001797
1798 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001799 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001800 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001801 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001802 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001803 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1804 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001805 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001806 if (input != AUDIO_IO_HANDLE_NONE) {
1807 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001808 }
Eric Laurent599c7582015-12-07 18:05:55 -08001809 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001810 }
1811
Eric Laurent1f2f2232014-06-02 12:01:23 -07001812 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001813 inputDesc->mSamplingRate = profileSamplingRate;
1814 inputDesc->mFormat = profileFormat;
1815 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001816 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001817 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001818 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001819
Eric Laurent599c7582015-12-07 18:05:55 -08001820 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001821 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001822
Eric Laurent599c7582015-12-07 18:05:55 -08001823 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001824}
1825
Eric Laurentbb948092017-01-23 18:33:30 -08001826//static
1827bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1828{
1829 return (source == AUDIO_SOURCE_HOTWORD) ||
1830 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1831 (source == AUDIO_SOURCE_FM_TUNER);
1832}
1833
Eric Laurentfb66dd92016-01-28 18:32:03 -08001834bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1835 const sp<AudioSession>& audioSession)
1836{
1837 // Do not allow capture if an active voice call is using a software patch and
1838 // the call TX source device is on the same HW module.
1839 // FIXME: would be better to refine to only inputs whose profile connects to the
1840 // call TX device but this information is not in the audio patch
1841 if (mCallTxPatch != 0 &&
1842 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1843 return false;
1844 }
1845
1846 // starting concurrent capture is enabled if:
1847 // 1) capturing for re-routing
1848 // 2) capturing for HOTWORD source
1849 // 3) capturing for FM TUNER source
1850 // 3) All other active captures are either for re-routing or HOTWORD
1851
1852 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001853 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001854 return true;
1855 }
1856
1857 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1858 for (size_t i = 0; i < activeInputs.size(); i++) {
1859 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001860 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001861 !is_virtual_input_device(activeInput->mDevice)) {
1862 return false;
1863 }
1864 }
1865
1866 return true;
1867}
1868
Chris Thornton2b864642017-06-27 21:26:07 -07001869// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1870bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1871 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1872 bool soundTriggerSupportsConcurrentCapture = false;
1873 unsigned int numModules = 0;
1874 struct sound_trigger_module_descriptor* nModules = NULL;
1875
1876 status_t status = SoundTrigger::listModules(nModules, &numModules);
1877 if (status == NO_ERROR && numModules != 0) {
1878 nModules = (struct sound_trigger_module_descriptor*) calloc(
1879 numModules, sizeof(struct sound_trigger_module_descriptor));
1880 if (nModules == NULL) {
1881 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1882 // ram the next time this function is called.
1883 ALOGE("Failed to allocate buffer for module descriptors");
1884 return false;
1885 }
1886
1887 status = SoundTrigger::listModules(nModules, &numModules);
1888 if (status == NO_ERROR) {
1889 soundTriggerSupportsConcurrentCapture = true;
1890 for (size_t i = 0; i < numModules; ++i) {
1891 soundTriggerSupportsConcurrentCapture &=
1892 nModules[i].properties.concurrent_capture;
1893 }
1894 }
1895 free(nModules);
1896 }
1897 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1898 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1899 }
1900 return mSoundTriggerSupportsConcurrentCapture;
1901}
1902
Eric Laurentfb66dd92016-01-28 18:32:03 -08001903
Eric Laurent4dc68062014-07-28 17:26:49 -07001904status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001905 audio_session_t session,
1906 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001907{
1908 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001909 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001910 ssize_t index = mInputs.indexOfKey(input);
1911 if (index < 0) {
1912 ALOGW("startInput() unknown input %d", input);
1913 return BAD_VALUE;
1914 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001915 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001916
Eric Laurent599c7582015-12-07 18:05:55 -08001917 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1918 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001919 ALOGW("startInput() unknown session %d on input %d", session, input);
1920 return BAD_VALUE;
1921 }
1922
Eric Laurent74708e72017-04-07 17:13:42 -07001923// FIXME: disable concurrent capture until UI is ready
1924#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001925 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1926 ALOGW("startInput(%d) failed: other input already started", input);
1927 return INVALID_OPERATION;
1928 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001929
Eric Laurentfb66dd92016-01-28 18:32:03 -08001930 if (isInCall()) {
1931 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1932 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001933 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001934 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001935 }
Eric Laurent74708e72017-04-07 17:13:42 -07001936#else
1937 if (!is_virtual_input_device(inputDesc->mDevice)) {
1938 if (mCallTxPatch != 0 &&
1939 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1940 ALOGW("startInput(%d) failed: call in progress", input);
1941 return INVALID_OPERATION;
1942 }
1943
1944 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1945 for (size_t i = 0; i < activeInputs.size(); i++) {
1946 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1947
1948 if (is_virtual_input_device(activeDesc->mDevice)) {
1949 continue;
1950 }
1951
Eric Laurentcb4dae22017-07-01 19:39:32 -07001952 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1953 activeDesc->getId() == inputDesc->getId()) {
1954 continue;
1955 }
1956
Eric Laurent74708e72017-04-07 17:13:42 -07001957 audio_source_t activeSource = activeDesc->inputSource(true);
1958 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1959 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1960 if (activeDesc->hasPreemptedSession(session)) {
1961 ALOGW("startInput(%d) failed for HOTWORD: "
1962 "other input %d already started for HOTWORD",
1963 input, activeDesc->mIoHandle);
1964 return INVALID_OPERATION;
1965 }
1966 } else {
1967 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1968 input, activeDesc->mIoHandle);
1969 return INVALID_OPERATION;
1970 }
1971 } else {
1972 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1973 ALOGW("startInput(%d) failed: other input %d already started",
1974 input, activeDesc->mIoHandle);
1975 return INVALID_OPERATION;
1976 }
1977 }
1978 }
1979
Chris Thornton2b864642017-06-27 21:26:07 -07001980 // We only need to check if the sound trigger session supports concurrent capture if the
1981 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1982 // that's running.
1983 const bool allowConcurrentWithSoundTrigger =
1984 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1985
Eric Laurent74708e72017-04-07 17:13:42 -07001986 // if capture is allowed, preempt currently active HOTWORD captures
1987 for (size_t i = 0; i < activeInputs.size(); i++) {
1988 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1989
1990 if (is_virtual_input_device(activeDesc->mDevice)) {
1991 continue;
1992 }
1993
Chris Thornton2b864642017-06-27 21:26:07 -07001994 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1995 continue;
1996 }
1997
Eric Laurent74708e72017-04-07 17:13:42 -07001998 audio_source_t activeSource = activeDesc->inputSource(true);
1999 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2000 AudioSessionCollection activeSessions =
2001 activeDesc->getAudioSessions(true /*activeOnly*/);
2002 audio_session_t activeSession = activeSessions.keyAt(0);
2003 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2004 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2005 sessions.add(activeSession);
2006 inputDesc->setPreemptedSessions(sessions);
2007 stopInput(activeHandle, activeSession);
2008 releaseInput(activeHandle, activeSession);
2009 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2010 input, activeDesc->mIoHandle);
2011 }
2012 }
2013 }
2014#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002015
Eric Laurent313d1e72016-01-29 09:56:57 -08002016 // increment activity count before calling getNewInputDevice() below as only active sessions
2017 // are considered for device selection
2018 audioSession->changeActiveCount(1);
2019
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002020 // Routing?
2021 mInputRoutes.incRouteActivity(session);
2022
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002023 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002024 // indicate active capture to sound trigger service if starting capture from a mic on
2025 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002026 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002027 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002028
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002029 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2030 // if input maps to a dynamic policy with an activity listener, notify of state change
2031 if ((inputDesc->mPolicyMix != NULL)
2032 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2033 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2034 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002035 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002036
Eric Laurentf7c50102016-09-30 15:19:43 -07002037 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2038 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002039 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002040 SoundTrigger::setCaptureState(true);
2041 }
2042
2043 // automatically enable the remote submix output when input is started if not
2044 // used by a policy mix of type MIX_TYPE_RECORDERS
2045 // For remote submix (a virtual device), we open only one input per capture request.
2046 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2047 String8 address = String8("");
2048 if (inputDesc->mPolicyMix == NULL) {
2049 address = String8("0");
2050 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2051 address = inputDesc->mPolicyMix->mDeviceAddress;
2052 }
2053 if (address != "") {
2054 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2055 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2056 address, "remote-submix");
2057 }
Eric Laurentc722f302014-12-10 11:21:49 -08002058 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002059 }
Eric Laurente552edb2014-03-10 17:42:56 -07002060 }
2061
Eric Laurent599c7582015-12-07 18:05:55 -08002062 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002063
Eric Laurente552edb2014-03-10 17:42:56 -07002064 return NO_ERROR;
2065}
2066
Eric Laurent4dc68062014-07-28 17:26:49 -07002067status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2068 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002069{
2070 ALOGV("stopInput() input %d", input);
2071 ssize_t index = mInputs.indexOfKey(input);
2072 if (index < 0) {
2073 ALOGW("stopInput() unknown input %d", input);
2074 return BAD_VALUE;
2075 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002076 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002077
Eric Laurent599c7582015-12-07 18:05:55 -08002078 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002079 if (index < 0) {
2080 ALOGW("stopInput() unknown session %d on input %d", session, input);
2081 return BAD_VALUE;
2082 }
2083
Eric Laurent599c7582015-12-07 18:05:55 -08002084 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002085 ALOGW("stopInput() input %d already stopped", input);
2086 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002087 }
2088
Eric Laurent599c7582015-12-07 18:05:55 -08002089 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002090
2091 // Routing?
2092 mInputRoutes.decRouteActivity(session);
2093
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002094 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002095
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002096 if (inputDesc->isActive()) {
2097 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2098 } else {
2099 // if input maps to a dynamic policy with an activity listener, notify of state change
2100 if ((inputDesc->mPolicyMix != NULL)
2101 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2102 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2103 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002104 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002105
2106 // automatically disable the remote submix output when input is stopped if not
2107 // used by a policy mix of type MIX_TYPE_RECORDERS
2108 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2109 String8 address = String8("");
2110 if (inputDesc->mPolicyMix == NULL) {
2111 address = String8("0");
2112 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2113 address = inputDesc->mPolicyMix->mDeviceAddress;
2114 }
2115 if (address != "") {
2116 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2117 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2118 address, "remote-submix");
2119 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002120 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002121
Eric Laurentf7c50102016-09-30 15:19:43 -07002122 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002123 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002124
Eric Laurentf7c50102016-09-30 15:19:43 -07002125 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2126 // primary HW module
2127 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2128 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2129 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002130 SoundTrigger::setCaptureState(false);
2131 }
2132 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002133 }
Eric Laurente552edb2014-03-10 17:42:56 -07002134 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002135 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002136}
2137
Eric Laurent4dc68062014-07-28 17:26:49 -07002138void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2139 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002140{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002141
Eric Laurente552edb2014-03-10 17:42:56 -07002142 ALOGV("releaseInput() %d", input);
2143 ssize_t index = mInputs.indexOfKey(input);
2144 if (index < 0) {
2145 ALOGW("releaseInput() releasing unknown input %d", input);
2146 return;
2147 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002148
2149 // Routing
2150 mInputRoutes.removeRoute(session);
2151
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002152 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2153 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002154
Eric Laurent599c7582015-12-07 18:05:55 -08002155 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002156 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002157 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2158 return;
2159 }
Eric Laurent599c7582015-12-07 18:05:55 -08002160
2161 if (audioSession->openCount() == 0) {
2162 ALOGW("releaseInput() invalid open count %d on session %d",
2163 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002164 return;
2165 }
Eric Laurent599c7582015-12-07 18:05:55 -08002166
2167 if (audioSession->changeOpenCount(-1) == 0) {
2168 inputDesc->removeAudioSession(session);
2169 }
2170
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002171 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002172 ALOGV("releaseInput() exit > 0");
2173 return;
2174 }
2175
Eric Laurent05b90f82014-08-27 15:32:29 -07002176 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002177 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002178 ALOGV("releaseInput() exit");
2179}
2180
Eric Laurentd4692962014-05-05 18:13:44 -07002181void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002182 bool patchRemoved = false;
2183
Eric Laurentd4692962014-05-05 18:13:44 -07002184 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002185 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002186 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002187 if (patch_index >= 0) {
2188 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002189 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002190 mAudioPatches.removeItemsAt(patch_index);
2191 patchRemoved = true;
2192 }
Eric Laurentd4692962014-05-05 18:13:44 -07002193 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2194 }
2195 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002196 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002197 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002198
2199 if (patchRemoved) {
2200 mpClientInterface->onAudioPatchListUpdate();
2201 }
Eric Laurentd4692962014-05-05 18:13:44 -07002202}
2203
Eric Laurente0720872014-03-11 09:30:41 -07002204void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002205 int indexMin,
2206 int indexMax)
2207{
2208 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002209 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002210
2211 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002212 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2213 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002214 continue;
2215 }
2216 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002217 }
Eric Laurente552edb2014-03-10 17:42:56 -07002218}
2219
Eric Laurente0720872014-03-11 09:30:41 -07002220status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002221 int index,
2222 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002223{
2224
François Gaffied1ab2bd2015-12-02 18:20:06 +01002225 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2226 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002227 return BAD_VALUE;
2228 }
2229 if (!audio_is_output_device(device)) {
2230 return BAD_VALUE;
2231 }
2232
2233 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002234 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002235
Eric Laurent1fd372e2016-04-06 14:23:53 -07002236 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002237 stream, device, index);
2238
Eric Laurent28d09f02016-03-08 10:43:05 -08002239 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002240 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2241 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002242 continue;
2243 }
2244 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2245 }
Eric Laurente552edb2014-03-10 17:42:56 -07002246
Eric Laurent1fd372e2016-04-06 14:23:53 -07002247 // update volume on all outputs and streams matching the following:
2248 // - The requested stream (or a stream matching for volume control) is active on the output
2249 // - The device (or devices) selected by the strategy corresponding to this stream includes
2250 // the requested device
2251 // - For non default requested device, currently selected device on the output is either the
2252 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002253 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2254 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002255 status_t status = NO_ERROR;
2256 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002257 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2258 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002259 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2260 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002261 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002262 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002263 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2264 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002265 continue;
2266 }
Eric Laurent794fde22016-03-11 09:50:45 -08002267 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002268 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2269 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002270 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2271 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002272 continue;
2273 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002274 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002275 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002276 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002277 applyVolume = (curDevice & curStreamDevice) != 0;
2278 } else {
2279 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002280 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002281 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002282
Eric Laurente76f29c2016-09-14 17:17:53 -07002283 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002284 //FIXME: workaround for truncated touch sounds
2285 // delayed volume change for system stream to be removed when the problem is
2286 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002287 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002288 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2289 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002290 if (volStatus != NO_ERROR) {
2291 status = volStatus;
2292 }
2293 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002294 }
Eric Laurente552edb2014-03-10 17:42:56 -07002295 }
2296 return status;
2297}
2298
Eric Laurente0720872014-03-11 09:30:41 -07002299status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002300 int *index,
2301 audio_devices_t device)
2302{
2303 if (index == NULL) {
2304 return BAD_VALUE;
2305 }
2306 if (!audio_is_output_device(device)) {
2307 return BAD_VALUE;
2308 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002309 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002310 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002311 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002312 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2313 }
François Gaffiedfd74092015-03-19 12:10:59 +01002314 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002315
François Gaffied1ab2bd2015-12-02 18:20:06 +01002316 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002317 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2318 return NO_ERROR;
2319}
2320
Eric Laurent36829f92017-04-07 19:04:42 -07002321audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002322{
2323 // select one output among several suitable for global effects.
2324 // The priority is as follows:
2325 // 1: An offloaded output. If the effect ends up not being offloadable,
2326 // AudioFlinger will invalidate the track and the offloaded output
2327 // will be closed causing the effect to be moved to a PCM output.
2328 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002329 // 3: The primary output
2330 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002331
Eric Laurent3b73df72014-03-11 09:06:29 -07002332 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002333 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002334 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002335
Eric Laurent36829f92017-04-07 19:04:42 -07002336 if (outputs.size() == 0) {
2337 return AUDIO_IO_HANDLE_NONE;
2338 }
Eric Laurente552edb2014-03-10 17:42:56 -07002339
Eric Laurent36829f92017-04-07 19:04:42 -07002340 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2341 bool activeOnly = true;
2342
2343 while (output == AUDIO_IO_HANDLE_NONE) {
2344 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2345 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2346 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2347
2348 for (size_t i = 0; i < outputs.size(); i++) {
2349 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2350 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2351 continue;
2352 }
2353 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2354 activeOnly, i, desc->mFlags);
2355 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2356 outputOffloaded = outputs[i];
2357 }
2358 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2359 outputDeepBuffer = outputs[i];
2360 }
2361 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2362 outputPrimary = outputs[i];
2363 }
2364 }
2365 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2366 output = outputOffloaded;
2367 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2368 output = outputDeepBuffer;
2369 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2370 output = outputPrimary;
2371 } else {
2372 output = outputs[0];
2373 }
2374 activeOnly = false;
2375 }
2376
2377 if (output != mMusicEffectOutput) {
2378 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2379 mMusicEffectOutput = output;
2380 }
2381
2382 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002383 return output;
2384}
2385
Eric Laurent36829f92017-04-07 19:04:42 -07002386audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2387{
2388 return selectOutputForMusicEffects();
2389}
2390
Eric Laurente0720872014-03-11 09:30:41 -07002391status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002392 audio_io_handle_t io,
2393 uint32_t strategy,
2394 int session,
2395 int id)
2396{
2397 ssize_t index = mOutputs.indexOfKey(io);
2398 if (index < 0) {
2399 index = mInputs.indexOfKey(io);
2400 if (index < 0) {
2401 ALOGW("registerEffect() unknown io %d", io);
2402 return INVALID_OPERATION;
2403 }
2404 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002405 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002406}
2407
Eric Laurentc75307b2015-03-17 15:29:32 -07002408bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2409{
Eric Laurent28d09f02016-03-08 10:43:05 -08002410 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002411 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2412 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002413 continue;
2414 }
2415 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2416 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002417 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002418}
2419
2420bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2421{
2422 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2423}
2424
Eric Laurente0720872014-03-11 09:30:41 -07002425bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002426{
2427 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002428 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002429 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002430 return true;
2431 }
2432 }
2433 return false;
2434}
2435
Eric Laurent275e8e92014-11-30 15:14:47 -08002436// Register a list of custom mixes with their attributes and format.
2437// When a mix is registered, corresponding input and output profiles are
2438// added to the remote submix hw module. The profile contains only the
2439// parameters (sampling rate, format...) specified by the mix.
2440// The corresponding input remote submix device is also connected.
2441//
2442// When a remote submix device is connected, the address is checked to select the
2443// appropriate profile and the corresponding input or output stream is opened.
2444//
2445// When capture starts, getInputForAttr() will:
2446// - 1 look for a mix matching the address passed in attribtutes tags if any
2447// - 2 if none found, getDeviceForInputSource() will:
2448// - 2.1 look for a mix matching the attributes source
2449// - 2.2 if none found, default to device selection by policy rules
2450// At this time, the corresponding output remote submix device is also connected
2451// and active playback use cases can be transferred to this mix if needed when reconnecting
2452// after AudioTracks are invalidated
2453//
2454// When playback starts, getOutputForAttr() will:
2455// - 1 look for a mix matching the address passed in attribtutes tags if any
2456// - 2 if none found, look for a mix matching the attributes usage
2457// - 3 if none found, default to device and output selection by policy rules.
2458
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002459status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002460{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002461 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2462 status_t res = NO_ERROR;
2463
2464 sp<HwModule> rSubmixModule;
2465 // examine each mix's route type
2466 for (size_t i = 0; i < mixes.size(); i++) {
2467 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2468 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2469 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002470 break;
2471 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002472 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2473 // Loop back through "remote submix"
2474 if (rSubmixModule == 0) {
2475 for (size_t j = 0; i < mHwModules.size(); j++) {
2476 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2477 && mHwModules[j]->mHandle != 0) {
2478 rSubmixModule = mHwModules[j];
2479 break;
2480 }
2481 }
2482 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002483
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002484 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002485
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002486 if (rSubmixModule == 0) {
2487 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2488 res = INVALID_OPERATION;
2489 break;
2490 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002491
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002492 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002493
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002494 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002495 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002496 res = INVALID_OPERATION;
2497 break;
2498 }
2499 audio_config_t outputConfig = mixes[i].mFormat;
2500 audio_config_t inputConfig = mixes[i].mFormat;
2501 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2502 // stereo and let audio flinger do the channel conversion if needed.
2503 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2504 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2505 rSubmixModule->addOutputProfile(address, &outputConfig,
2506 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2507 rSubmixModule->addInputProfile(address, &inputConfig,
2508 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002509
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2511 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2512 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2513 address.string(), "remote-submix");
2514 } else {
2515 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2516 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2517 address.string(), "remote-submix");
2518 }
2519 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002520 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002522 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2523 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002524
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002525 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2527 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2528 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2529 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2530 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2531 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002532 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2533 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2535 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002536 } else {
2537 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002538 }
2539 break;
2540 }
2541 }
2542
2543 if (res != NO_ERROR) {
2544 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002545 i, device, address.string());
2546 res = INVALID_OPERATION;
2547 break;
2548 } else if (!foundOutput) {
2549 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2550 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 res = INVALID_OPERATION;
2552 break;
2553 }
Eric Laurentc722f302014-12-10 11:21:49 -08002554 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002555 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002556 if (res != NO_ERROR) {
2557 unregisterPolicyMixes(mixes);
2558 }
2559 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002560}
2561
2562status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2563{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002564 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002565 status_t res = NO_ERROR;
2566 sp<HwModule> rSubmixModule;
2567 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002568 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002569 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002570
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002571 if (rSubmixModule == 0) {
2572 for (size_t j = 0; i < mHwModules.size(); j++) {
2573 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2574 && mHwModules[j]->mHandle != 0) {
2575 rSubmixModule = mHwModules[j];
2576 break;
2577 }
2578 }
2579 }
2580 if (rSubmixModule == 0) {
2581 res = INVALID_OPERATION;
2582 continue;
2583 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002584
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002585 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002586
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002587 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2588 res = INVALID_OPERATION;
2589 continue;
2590 }
2591
2592 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2593 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2594 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2595 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2596 address.string(), "remote-submix");
2597 }
2598 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2599 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2600 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2601 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2602 address.string(), "remote-submix");
2603 }
2604 rSubmixModule->removeOutputProfile(address);
2605 rSubmixModule->removeInputProfile(address);
2606
2607 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2608 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2609 res = INVALID_OPERATION;
2610 continue;
2611 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002612 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002613 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002614 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002615}
2616
Eric Laurente552edb2014-03-10 17:42:56 -07002617
Eric Laurente0720872014-03-11 09:30:41 -07002618status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002619{
2620 const size_t SIZE = 256;
2621 char buffer[SIZE];
2622 String8 result;
2623
2624 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2625 result.append(buffer);
2626
Eric Laurent87ffa392015-05-22 10:32:38 -07002627 snprintf(buffer, SIZE, " Primary Output: %d\n",
2628 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002629 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002630 std::string stateLiteral;
2631 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2632 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002633 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002634 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002635 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002636 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002637 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002638 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002639 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002640 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002641 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002642 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002643 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002644 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002645 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002646 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002647 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002648 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2649 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2650 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002651 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2652 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002653 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2654 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002655
François Gaffie2110e042015-03-24 08:41:51 +01002656 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002657
François Gaffie112b0af2015-11-19 16:13:25 +01002658 mAvailableOutputDevices.dump(fd, String8("Available output"));
2659 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002660 mHwModules.dump(fd);
2661 mOutputs.dump(fd);
2662 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002663 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002664 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002665 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002666 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002667
2668 return NO_ERROR;
2669}
2670
2671// This function checks for the parameters which can be offloaded.
2672// This can be enhanced depending on the capability of the DSP and policy
2673// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002674bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002675{
2676 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002677 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002678 offloadInfo.sample_rate, offloadInfo.channel_mask,
2679 offloadInfo.format,
2680 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2681 offloadInfo.has_video);
2682
Andy Hung2ddee192015-12-18 17:34:44 -08002683 if (mMasterMono) {
2684 return false; // no offloading if mono is set.
2685 }
2686
Eric Laurente552edb2014-03-10 17:42:56 -07002687 // Check if offload has been disabled
2688 char propValue[PROPERTY_VALUE_MAX];
2689 if (property_get("audio.offload.disable", propValue, "0")) {
2690 if (atoi(propValue) != 0) {
2691 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2692 return false;
2693 }
2694 }
2695
2696 // Check if stream type is music, then only allow offload as of now.
2697 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2698 {
2699 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2700 return false;
2701 }
2702
2703 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002704 const bool allowOffloadWithVideo =
2705 property_get_bool("audio.offload.video", false /* default_value */);
2706 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002707 ALOGV("isOffloadSupported: has_video == true, returning false");
2708 return false;
2709 }
2710
2711 //If duration is less than minimum value defined in property, return false
2712 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2713 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2714 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2715 return false;
2716 }
2717 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2718 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2719 return false;
2720 }
2721
2722 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2723 // creating an offloaded track and tearing it down immediately after start when audioflinger
2724 // detects there is an active non offloadable effect.
2725 // FIXME: We should check the audio session here but we do not have it in this context.
2726 // This may prevent offloading in rare situations where effects are left active by apps
2727 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002728 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002729 return false;
2730 }
2731
2732 // See if there is a profile to support this.
2733 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002734 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002735 offloadInfo.sample_rate,
2736 offloadInfo.format,
2737 offloadInfo.channel_mask,
2738 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002739 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2740 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002741}
2742
Eric Laurent6a94d692014-05-20 11:18:06 -07002743status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2744 audio_port_type_t type,
2745 unsigned int *num_ports,
2746 struct audio_port *ports,
2747 unsigned int *generation)
2748{
2749 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2750 generation == NULL) {
2751 return BAD_VALUE;
2752 }
2753 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2754 if (ports == NULL) {
2755 *num_ports = 0;
2756 }
2757
2758 size_t portsWritten = 0;
2759 size_t portsMax = *num_ports;
2760 *num_ports = 0;
2761 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002762 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2763 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002764 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002765 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2766 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2767 continue;
2768 }
2769 if (portsWritten < portsMax) {
2770 mAvailableOutputDevices[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 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002776 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2777 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2778 continue;
2779 }
2780 if (portsWritten < portsMax) {
2781 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2782 }
2783 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002784 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002785 }
2786 }
2787 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2788 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2789 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2790 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2791 }
2792 *num_ports += mInputs.size();
2793 }
2794 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002795 size_t numOutputs = 0;
2796 for (size_t i = 0; i < mOutputs.size(); i++) {
2797 if (!mOutputs[i]->isDuplicated()) {
2798 numOutputs++;
2799 if (portsWritten < portsMax) {
2800 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2801 }
2802 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002803 }
Eric Laurent84c70242014-06-23 08:46:27 -07002804 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 }
2806 }
2807 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002808 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002809 return NO_ERROR;
2810}
2811
2812status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2813{
2814 return NO_ERROR;
2815}
2816
Eric Laurent6a94d692014-05-20 11:18:06 -07002817status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2818 audio_patch_handle_t *handle,
2819 uid_t uid)
2820{
2821 ALOGV("createAudioPatch()");
2822
2823 if (handle == NULL || patch == NULL) {
2824 return BAD_VALUE;
2825 }
2826 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2827
Eric Laurent874c42872014-08-08 15:13:39 -07002828 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2829 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2830 return BAD_VALUE;
2831 }
2832 // only one source per audio patch supported for now
2833 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 return INVALID_OPERATION;
2835 }
Eric Laurent874c42872014-08-08 15:13:39 -07002836
2837 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002838 return INVALID_OPERATION;
2839 }
Eric Laurent874c42872014-08-08 15:13:39 -07002840 for (size_t i = 0; i < patch->num_sinks; i++) {
2841 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2842 return INVALID_OPERATION;
2843 }
2844 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002845
2846 sp<AudioPatch> patchDesc;
2847 ssize_t index = mAudioPatches.indexOfKey(*handle);
2848
Eric Laurent6a94d692014-05-20 11:18:06 -07002849 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2850 patch->sources[0].role,
2851 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002852#if LOG_NDEBUG == 0
2853 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002854 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002855 patch->sinks[i].role,
2856 patch->sinks[i].type);
2857 }
2858#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002859
2860 if (index >= 0) {
2861 patchDesc = mAudioPatches.valueAt(index);
2862 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2863 mUidCached, patchDesc->mUid, uid);
2864 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2865 return INVALID_OPERATION;
2866 }
2867 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002868 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002869 }
2870
2871 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002872 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002873 if (outputDesc == NULL) {
2874 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2875 return BAD_VALUE;
2876 }
Eric Laurent84c70242014-06-23 08:46:27 -07002877 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2878 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002879 if (patchDesc != 0) {
2880 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2881 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2882 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2883 return BAD_VALUE;
2884 }
2885 }
Eric Laurent874c42872014-08-08 15:13:39 -07002886 DeviceVector devices;
2887 for (size_t i = 0; i < patch->num_sinks; i++) {
2888 // Only support mix to devices connection
2889 // TODO add support for mix to mix connection
2890 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2891 ALOGV("createAudioPatch() source mix but sink is not a device");
2892 return INVALID_OPERATION;
2893 }
2894 sp<DeviceDescriptor> devDesc =
2895 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2896 if (devDesc == 0) {
2897 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2898 return BAD_VALUE;
2899 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002900
François Gaffie53615e22015-03-19 09:24:12 +01002901 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002902 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002903 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002904 NULL, // updatedSamplingRate
2905 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002906 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002907 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002908 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002909 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002910 ALOGV("createAudioPatch() profile not supported for device %08x",
2911 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002912 return INVALID_OPERATION;
2913 }
2914 devices.add(devDesc);
2915 }
2916 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002917 return INVALID_OPERATION;
2918 }
Eric Laurent874c42872014-08-08 15:13:39 -07002919
Eric Laurent6a94d692014-05-20 11:18:06 -07002920 // TODO: reconfigure output format and channels here
2921 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002922 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002923 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002924 index = mAudioPatches.indexOfKey(*handle);
2925 if (index >= 0) {
2926 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2927 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2928 }
2929 patchDesc = mAudioPatches.valueAt(index);
2930 patchDesc->mUid = uid;
2931 ALOGV("createAudioPatch() success");
2932 } else {
2933 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2934 return INVALID_OPERATION;
2935 }
2936 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2937 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2938 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002939 // only one sink supported when connecting an input device to a mix
2940 if (patch->num_sinks > 1) {
2941 return INVALID_OPERATION;
2942 }
François Gaffie53615e22015-03-19 09:24:12 +01002943 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002944 if (inputDesc == NULL) {
2945 return BAD_VALUE;
2946 }
2947 if (patchDesc != 0) {
2948 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2949 return BAD_VALUE;
2950 }
2951 }
2952 sp<DeviceDescriptor> devDesc =
2953 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2954 if (devDesc == 0) {
2955 return BAD_VALUE;
2956 }
2957
François Gaffie53615e22015-03-19 09:24:12 +01002958 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002959 devDesc->mAddress,
2960 patch->sinks[0].sample_rate,
2961 NULL, /*updatedSampleRate*/
2962 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002963 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002964 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002965 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002966 // FIXME for the parameter type,
2967 // and the NONE
2968 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002969 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002970 return INVALID_OPERATION;
2971 }
2972 // TODO: reconfigure output format and channels here
2973 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002974 devDesc->type(), inputDesc->mIoHandle);
2975 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002976 index = mAudioPatches.indexOfKey(*handle);
2977 if (index >= 0) {
2978 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2979 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2980 }
2981 patchDesc = mAudioPatches.valueAt(index);
2982 patchDesc->mUid = uid;
2983 ALOGV("createAudioPatch() success");
2984 } else {
2985 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2986 return INVALID_OPERATION;
2987 }
2988 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2989 // device to device connection
2990 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002991 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002992 return BAD_VALUE;
2993 }
2994 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002995 sp<DeviceDescriptor> srcDeviceDesc =
2996 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002997 if (srcDeviceDesc == 0) {
2998 return BAD_VALUE;
2999 }
Eric Laurent874c42872014-08-08 15:13:39 -07003000
Eric Laurent6a94d692014-05-20 11:18:06 -07003001 //update source and sink with our own data as the data passed in the patch may
3002 // be incomplete.
3003 struct audio_patch newPatch = *patch;
3004 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003005
Eric Laurent874c42872014-08-08 15:13:39 -07003006 for (size_t i = 0; i < patch->num_sinks; i++) {
3007 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3008 ALOGV("createAudioPatch() source device but one sink is not a device");
3009 return INVALID_OPERATION;
3010 }
3011
3012 sp<DeviceDescriptor> sinkDeviceDesc =
3013 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3014 if (sinkDeviceDesc == 0) {
3015 return BAD_VALUE;
3016 }
3017 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3018
Eric Laurent3bcf8592015-04-03 12:13:24 -07003019 // create a software bridge in PatchPanel if:
3020 // - source and sink devices are on differnt HW modules OR
3021 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003022 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003023 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003024 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003025 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003026 return INVALID_OPERATION;
3027 }
Eric Laurent874c42872014-08-08 15:13:39 -07003028 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003029 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003030 // if the sink device is reachable via an opened output stream, request to go via
3031 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003032 audio_io_handle_t output = selectOutput(outputs,
3033 AUDIO_OUTPUT_FLAG_NONE,
3034 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003035 if (output != AUDIO_IO_HANDLE_NONE) {
3036 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3037 if (outputDesc->isDuplicated()) {
3038 return INVALID_OPERATION;
3039 }
3040 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003041 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003042 newPatch.num_sources = 2;
3043 }
Eric Laurent83b88082014-06-20 18:31:16 -07003044 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003045 }
3046 // TODO: check from routing capabilities in config file and other conflicting patches
3047
3048 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3049 if (index >= 0) {
3050 afPatchHandle = patchDesc->mAfPatchHandle;
3051 }
3052
3053 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3054 &afPatchHandle,
3055 0);
3056 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3057 status, afPatchHandle);
3058 if (status == NO_ERROR) {
3059 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003060 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003061 addAudioPatch(patchDesc->mHandle, patchDesc);
3062 } else {
3063 patchDesc->mPatch = newPatch;
3064 }
3065 patchDesc->mAfPatchHandle = afPatchHandle;
3066 *handle = patchDesc->mHandle;
3067 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003068 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003069 } else {
3070 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3071 status);
3072 return INVALID_OPERATION;
3073 }
3074 } else {
3075 return BAD_VALUE;
3076 }
3077 } else {
3078 return BAD_VALUE;
3079 }
3080 return NO_ERROR;
3081}
3082
3083status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3084 uid_t uid)
3085{
3086 ALOGV("releaseAudioPatch() patch %d", handle);
3087
3088 ssize_t index = mAudioPatches.indexOfKey(handle);
3089
3090 if (index < 0) {
3091 return BAD_VALUE;
3092 }
3093 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3094 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3095 mUidCached, patchDesc->mUid, uid);
3096 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3097 return INVALID_OPERATION;
3098 }
3099
3100 struct audio_patch *patch = &patchDesc->mPatch;
3101 patchDesc->mUid = mUidCached;
3102 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003103 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003104 if (outputDesc == NULL) {
3105 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3106 return BAD_VALUE;
3107 }
3108
Eric Laurentc75307b2015-03-17 15:29:32 -07003109 setOutputDevice(outputDesc,
3110 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003111 true,
3112 0,
3113 NULL);
3114 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3115 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003116 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 if (inputDesc == NULL) {
3118 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3119 return BAD_VALUE;
3120 }
3121 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003122 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003123 true,
3124 NULL);
3125 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003126 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3127 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3128 status, patchDesc->mAfPatchHandle);
3129 removeAudioPatch(patchDesc->mHandle);
3130 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003131 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003132 } else {
3133 return BAD_VALUE;
3134 }
3135 } else {
3136 return BAD_VALUE;
3137 }
3138 return NO_ERROR;
3139}
3140
3141status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3142 struct audio_patch *patches,
3143 unsigned int *generation)
3144{
François Gaffie53615e22015-03-19 09:24:12 +01003145 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003146 return BAD_VALUE;
3147 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003148 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003149 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003150}
3151
Eric Laurente1715a42014-05-20 11:30:42 -07003152status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003153{
Eric Laurente1715a42014-05-20 11:30:42 -07003154 ALOGV("setAudioPortConfig()");
3155
3156 if (config == NULL) {
3157 return BAD_VALUE;
3158 }
3159 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3160 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003161 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3162 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003163 }
3164
Eric Laurenta121f902014-06-03 13:32:54 -07003165 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003166 if (config->type == AUDIO_PORT_TYPE_MIX) {
3167 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003168 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003169 if (outputDesc == NULL) {
3170 return BAD_VALUE;
3171 }
Eric Laurent84c70242014-06-23 08:46:27 -07003172 ALOG_ASSERT(!outputDesc->isDuplicated(),
3173 "setAudioPortConfig() called on duplicated output %d",
3174 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003175 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003176 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003177 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003178 if (inputDesc == NULL) {
3179 return BAD_VALUE;
3180 }
Eric Laurenta121f902014-06-03 13:32:54 -07003181 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003182 } else {
3183 return BAD_VALUE;
3184 }
3185 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3186 sp<DeviceDescriptor> deviceDesc;
3187 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3188 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3189 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3190 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3191 } else {
3192 return BAD_VALUE;
3193 }
3194 if (deviceDesc == NULL) {
3195 return BAD_VALUE;
3196 }
Eric Laurenta121f902014-06-03 13:32:54 -07003197 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003198 } else {
3199 return BAD_VALUE;
3200 }
3201
Eric Laurenta121f902014-06-03 13:32:54 -07003202 struct audio_port_config backupConfig;
3203 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3204 if (status == NO_ERROR) {
3205 struct audio_port_config newConfig;
3206 audioPortConfig->toAudioPortConfig(&newConfig, config);
3207 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003208 }
Eric Laurenta121f902014-06-03 13:32:54 -07003209 if (status != NO_ERROR) {
3210 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003211 }
Eric Laurente1715a42014-05-20 11:30:42 -07003212
3213 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003214}
3215
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003216void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3217{
Eric Laurentd60560a2015-04-10 11:31:20 -07003218 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003219 clearAudioPatches(uid);
3220 clearSessionRoutes(uid);
3221}
3222
Eric Laurent6a94d692014-05-20 11:18:06 -07003223void AudioPolicyManager::clearAudioPatches(uid_t uid)
3224{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003225 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003226 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3227 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003228 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003229 }
3230 }
3231}
3232
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003233void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3234 audio_io_handle_t ouptutToSkip)
3235{
3236 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3237 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3238 for (size_t j = 0; j < mOutputs.size(); j++) {
3239 if (mOutputs.keyAt(j) == ouptutToSkip) {
3240 continue;
3241 }
3242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3243 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3244 continue;
3245 }
3246 // If the default device for this strategy is on another output mix,
3247 // invalidate all tracks in this strategy to force re connection.
3248 // Otherwise select new device on the output mix.
3249 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003250 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003251 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3252 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3253 }
3254 }
3255 } else {
3256 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3257 setOutputDevice(outputDesc, newDevice, false);
3258 }
3259 }
3260}
3261
3262void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3263{
3264 // remove output routes associated with this uid
3265 SortedVector<routing_strategy> affectedStrategies;
3266 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3267 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3268 if (route->mUid == uid) {
3269 mOutputRoutes.removeItemsAt(i);
3270 if (route->mDeviceDescriptor != 0) {
3271 affectedStrategies.add(getStrategy(route->mStreamType));
3272 }
3273 }
3274 }
3275 // reroute outputs if necessary
3276 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3277 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3278 }
3279
3280 // remove input routes associated with this uid
3281 SortedVector<audio_source_t> affectedSources;
3282 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3283 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3284 if (route->mUid == uid) {
3285 mInputRoutes.removeItemsAt(i);
3286 if (route->mDeviceDescriptor != 0) {
3287 affectedSources.add(route->mSource);
3288 }
3289 }
3290 }
3291 // reroute inputs if necessary
3292 SortedVector<audio_io_handle_t> inputsToClose;
3293 for (size_t i = 0; i < mInputs.size(); i++) {
3294 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003295 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003296 inputsToClose.add(inputDesc->mIoHandle);
3297 }
3298 }
3299 for (size_t i = 0; i < inputsToClose.size(); i++) {
3300 closeInput(inputsToClose[i]);
3301 }
3302}
3303
Eric Laurentd60560a2015-04-10 11:31:20 -07003304void AudioPolicyManager::clearAudioSources(uid_t uid)
3305{
3306 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3307 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3308 if (sourceDesc->mUid == uid) {
3309 stopAudioSource(mAudioSources.keyAt(i));
3310 }
3311 }
3312}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003313
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003314status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3315 audio_io_handle_t *ioHandle,
3316 audio_devices_t *device)
3317{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003318 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3319 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003320 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003321
François Gaffiedf372692015-03-19 10:43:27 +01003322 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003323}
3324
Eric Laurentd60560a2015-04-10 11:31:20 -07003325status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3326 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003327 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003328 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003329{
Eric Laurentd60560a2015-04-10 11:31:20 -07003330 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3331 if (source == NULL || attributes == NULL || handle == NULL) {
3332 return BAD_VALUE;
3333 }
3334
Glenn Kasten559d4392016-03-29 13:42:57 -07003335 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003336
3337 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3338 source->type != AUDIO_PORT_TYPE_DEVICE) {
3339 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3340 return INVALID_OPERATION;
3341 }
3342
3343 sp<DeviceDescriptor> srcDeviceDesc =
3344 mAvailableInputDevices.getDevice(source->ext.device.type,
3345 String8(source->ext.device.address));
3346 if (srcDeviceDesc == 0) {
3347 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3348 return BAD_VALUE;
3349 }
3350 sp<AudioSourceDescriptor> sourceDesc =
3351 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3352
3353 struct audio_patch dummyPatch;
3354 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3355 sourceDesc->mPatchDesc = patchDesc;
3356
3357 status_t status = connectAudioSource(sourceDesc);
3358 if (status == NO_ERROR) {
3359 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3360 *handle = sourceDesc->getHandle();
3361 }
3362 return status;
3363}
3364
3365status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3366{
3367 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3368
3369 // make sure we only have one patch per source.
3370 disconnectAudioSource(sourceDesc);
3371
3372 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003373 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003374 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3375
3376 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3377 sp<DeviceDescriptor> sinkDeviceDesc =
3378 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3379
3380 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3381 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3382
3383 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3384 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003385 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003386 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3387 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3388 // create patch between src device and output device
3389 // create Hwoutput and add to mHwOutputs
3390 } else {
3391 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3392 audio_io_handle_t output =
3393 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3394 if (output == AUDIO_IO_HANDLE_NONE) {
3395 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3396 return INVALID_OPERATION;
3397 }
3398 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3399 if (outputDesc->isDuplicated()) {
3400 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3401 return INVALID_OPERATION;
3402 }
3403 // create a special patch with no sink and two sources:
3404 // - the second source indicates to PatchPanel through which output mix this patch should
3405 // be connected as well as the stream type for volume control
3406 // - the sink is defined by whatever output device is currently selected for the output
3407 // though which this patch is routed.
3408 patch->num_sinks = 0;
3409 patch->num_sources = 2;
3410 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3411 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3412 patch->sources[1].ext.mix.usecase.stream = stream;
3413 status_t status = mpClientInterface->createAudioPatch(patch,
3414 &afPatchHandle,
3415 0);
3416 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3417 status, afPatchHandle);
3418 if (status != NO_ERROR) {
3419 ALOGW("%s patch panel could not connect device patch, error %d",
3420 __FUNCTION__, status);
3421 return INVALID_OPERATION;
3422 }
3423 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003424 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003425
3426 if (status != NO_ERROR) {
3427 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3428 return status;
3429 }
3430 sourceDesc->mSwOutput = outputDesc;
3431 if (delayMs != 0) {
3432 usleep(delayMs * 1000);
3433 }
3434 }
3435
3436 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3437 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3438
3439 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003440}
3441
Glenn Kasten559d4392016-03-29 13:42:57 -07003442status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003443{
Eric Laurentd60560a2015-04-10 11:31:20 -07003444 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3445 ALOGV("%s handle %d", __FUNCTION__, handle);
3446 if (sourceDesc == 0) {
3447 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3448 return BAD_VALUE;
3449 }
3450 status_t status = disconnectAudioSource(sourceDesc);
3451
3452 mAudioSources.removeItem(handle);
3453 return status;
3454}
3455
Andy Hung2ddee192015-12-18 17:34:44 -08003456status_t AudioPolicyManager::setMasterMono(bool mono)
3457{
3458 if (mMasterMono == mono) {
3459 return NO_ERROR;
3460 }
3461 mMasterMono = mono;
3462 // if enabling mono we close all offloaded devices, which will invalidate the
3463 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3464 // for recreating the new AudioTrack as non-offloaded PCM.
3465 //
3466 // If disabling mono, we leave all tracks as is: we don't know which clients
3467 // and tracks are able to be recreated as offloaded. The next "song" should
3468 // play back offloaded.
3469 if (mMasterMono) {
3470 Vector<audio_io_handle_t> offloaded;
3471 for (size_t i = 0; i < mOutputs.size(); ++i) {
3472 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3473 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3474 offloaded.push(desc->mIoHandle);
3475 }
3476 }
3477 for (size_t i = 0; i < offloaded.size(); ++i) {
3478 closeOutput(offloaded[i]);
3479 }
3480 }
3481 // update master mono for all remaining outputs
3482 for (size_t i = 0; i < mOutputs.size(); ++i) {
3483 updateMono(mOutputs.keyAt(i));
3484 }
3485 return NO_ERROR;
3486}
3487
3488status_t AudioPolicyManager::getMasterMono(bool *mono)
3489{
3490 *mono = mMasterMono;
3491 return NO_ERROR;
3492}
3493
Eric Laurentac9cef52017-06-09 15:46:26 -07003494float AudioPolicyManager::getStreamVolumeDB(
3495 audio_stream_type_t stream, int index, audio_devices_t device)
3496{
3497 return computeVolume(stream, index, device);
3498}
3499
Eric Laurentd60560a2015-04-10 11:31:20 -07003500status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3501{
3502 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3503
3504 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3505 if (patchDesc == 0) {
3506 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3507 sourceDesc->mPatchDesc->mHandle);
3508 return BAD_VALUE;
3509 }
3510 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3511
Eric Laurent28d09f02016-03-08 10:43:05 -08003512 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003513 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3514 if (swOutputDesc != 0) {
3515 stopSource(swOutputDesc, stream, false);
3516 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3517 } else {
3518 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3519 if (hwOutputDesc != 0) {
3520 // release patch between src device and output device
3521 // close Hwoutput and remove from mHwOutputs
3522 } else {
3523 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3524 }
3525 }
3526 return NO_ERROR;
3527}
3528
3529sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3530 audio_io_handle_t output, routing_strategy strategy)
3531{
3532 sp<AudioSourceDescriptor> source;
3533 for (size_t i = 0; i < mAudioSources.size(); i++) {
3534 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3535 routing_strategy sourceStrategy =
3536 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3537 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3538 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3539 source = sourceDesc;
3540 break;
3541 }
3542 }
3543 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003544}
3545
Eric Laurente552edb2014-03-10 17:42:56 -07003546// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003547// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003548// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003549uint32_t AudioPolicyManager::nextAudioPortGeneration()
3550{
3551 return android_atomic_inc(&mAudioPortGeneration);
3552}
3553
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003554#ifdef USE_XML_AUDIO_POLICY_CONF
3555// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3556static const char *kConfigLocationList[] =
3557 {"/odm/etc", "/vendor/etc", "/system/etc"};
3558static const int kConfigLocationListSize =
3559 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3560
3561static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3562 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3563 status_t ret;
3564
3565 for (int i = 0; i < kConfigLocationListSize; i++) {
3566 PolicySerializer serializer;
3567 snprintf(audioPolicyXmlConfigFile,
3568 sizeof(audioPolicyXmlConfigFile),
3569 "%s/%s",
3570 kConfigLocationList[i],
3571 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3572 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3573 if (ret == NO_ERROR) {
3574 break;
3575 }
3576 }
3577 return ret;
3578}
3579#endif
3580
Eric Laurente0720872014-03-11 09:30:41 -07003581AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003582 :
3583#ifdef AUDIO_POLICY_TEST
3584 Thread(false),
3585#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003586 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003587 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003588 mAudioPortGeneration(1),
3589 mBeaconMuteRefCount(0),
3590 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003591 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003592 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003593 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003594 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3595 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003596{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003597 mUidCached = getuid();
3598 mpClientInterface = clientInterface;
3599
3600 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3601 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3602 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3603 bool speakerDrcEnabled = false;
3604
3605#ifdef USE_XML_AUDIO_POLICY_CONF
3606 mVolumeCurves = new VolumeCurvesCollection();
3607 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3608 mDefaultOutputDevice, speakerDrcEnabled,
3609 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003610 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003611#else
3612 mVolumeCurves = new StreamDescriptorCollection();
3613 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3614 mDefaultOutputDevice, speakerDrcEnabled);
3615 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3616 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3617#endif
3618 ALOGE("could not load audio policy configuration file, setting defaults");
3619 config.setDefault();
3620 }
3621 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3622 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3623
3624 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003625 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3626 if (!engineInstance) {
3627 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3628 return;
3629 }
3630 // Retrieve the Policy Manager Interface
3631 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3632 if (mEngine == NULL) {
3633 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3634 return;
3635 }
3636 mEngine->setObserver(this);
3637 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003638 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003639 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3640
Eric Laurent3a4311c2014-03-17 12:00:47 -07003641 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003642 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003643 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3644 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003645 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003646 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003647 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003648 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003649 continue;
3650 }
3651 // open all output streams needed to access attached devices
3652 // except for direct output streams that are only opened when they are actually
3653 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003654 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003655 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3656 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003657 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003658
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003659 if (!outProfile->hasSupportedDevices()) {
3660 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003661 continue;
3662 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003663 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003664 mTtsOutputAvailable = true;
3665 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003666
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003667 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003668 continue;
3669 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003670 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003671 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3672 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003673 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003674 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003675 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003676 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003677 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003678 if ((profileType & outputDeviceTypes) == 0) {
3679 continue;
3680 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003681 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3682 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003683 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3684 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3685 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3686 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003687
3688 outputDesc->mDevice = profileType;
3689 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3690 config.sample_rate = outputDesc->mSamplingRate;
3691 config.channel_mask = outputDesc->mChannelMask;
3692 config.format = outputDesc->mFormat;
3693 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003694 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003695 &output,
3696 &config,
3697 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003698 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003699 &outputDesc->mLatency,
3700 outputDesc->mFlags);
3701
3702 if (status != NO_ERROR) {
3703 ALOGW("Cannot open output stream for device %08x on hw module %s",
3704 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003705 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003706 } else {
3707 outputDesc->mSamplingRate = config.sample_rate;
3708 outputDesc->mChannelMask = config.channel_mask;
3709 outputDesc->mFormat = config.format;
3710
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003711 for (size_t k = 0; k < supportedDevices.size(); k++) {
3712 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003713 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003714 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3715 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003716 }
3717 }
3718 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003719 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003720 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003721 }
3722 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003723 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003724 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003725 true,
3726 0,
3727 NULL,
3728 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003729 }
Eric Laurente552edb2014-03-10 17:42:56 -07003730 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003731 // open input streams needed to access attached devices to validate
3732 // mAvailableInputDevices list
3733 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3734 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003735 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003736
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003737 if (!inProfile->hasSupportedDevices()) {
3738 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003739 continue;
3740 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003741 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003742 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003743 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3744
Eric Laurentd78f1532014-09-16 16:38:20 -07003745 if ((profileType & inputDeviceTypes) == 0) {
3746 continue;
3747 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003748 sp<AudioInputDescriptor> inputDesc =
3749 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003750
Eric Laurentd78f1532014-09-16 16:38:20 -07003751 inputDesc->mDevice = profileType;
3752
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003753 // find the address
3754 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3755 // the inputs vector must be of size 1, but we don't want to crash here
3756 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3757 : String8("");
3758 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3759 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3760
Eric Laurentd78f1532014-09-16 16:38:20 -07003761 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3762 config.sample_rate = inputDesc->mSamplingRate;
3763 config.channel_mask = inputDesc->mChannelMask;
3764 config.format = inputDesc->mFormat;
3765 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003766 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003767 &input,
3768 &config,
3769 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003770 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003771 AUDIO_SOURCE_MIC,
3772 AUDIO_INPUT_FLAG_NONE);
3773
3774 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003775 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3776 for (size_t k = 0; k < supportedDevices.size(); k++) {
3777 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003778 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003779 if (index >= 0) {
3780 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3781 if (!devDesc->isAttached()) {
3782 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003783 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003784 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003785 }
3786 }
3787 mpClientInterface->closeInput(input);
3788 } else {
3789 ALOGW("Cannot open input stream for device %08x on hw module %s",
3790 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003791 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003792 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003793 }
3794 }
3795 // make sure all attached devices have been allocated a unique ID
3796 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003797 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003798 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003799 mAvailableOutputDevices.remove(mAvailableOutputDevices[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(mAvailableOutputDevices[i],
3804 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003805 i++;
3806 }
3807 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003808 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003809 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003810 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3811 continue;
3812 }
François Gaffie2110e042015-03-24 08:41:51 +01003813 // The device is now validated and can be appended to the available devices of the engine
3814 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3815 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003816 i++;
3817 }
3818 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003819 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003820 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003821 }
Eric Laurente552edb2014-03-10 17:42:56 -07003822
3823 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3824
3825 updateDevicesAndOutputs();
3826
3827#ifdef AUDIO_POLICY_TEST
3828 if (mPrimaryOutput != 0) {
3829 AudioParameter outputCmd = AudioParameter();
3830 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003831 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003832
3833 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3834 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003835 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3836 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003837 mTestLatencyMs = 0;
3838 mCurOutput = 0;
3839 mDirectOutput = false;
3840 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3841 mTestOutputs[i] = 0;
3842 }
3843
3844 const size_t SIZE = 256;
3845 char buffer[SIZE];
3846 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3847 run(buffer, ANDROID_PRIORITY_AUDIO);
3848 }
3849#endif //AUDIO_POLICY_TEST
3850}
3851
Eric Laurente0720872014-03-11 09:30:41 -07003852AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003853{
3854#ifdef AUDIO_POLICY_TEST
3855 exit();
3856#endif //AUDIO_POLICY_TEST
3857 for (size_t i = 0; i < mOutputs.size(); i++) {
3858 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003859 }
3860 for (size_t i = 0; i < mInputs.size(); i++) {
3861 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003862 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003863 mAvailableOutputDevices.clear();
3864 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003865 mOutputs.clear();
3866 mInputs.clear();
3867 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003868}
3869
Eric Laurente0720872014-03-11 09:30:41 -07003870status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003871{
Eric Laurent87ffa392015-05-22 10:32:38 -07003872 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003873}
3874
3875#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003876bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003877{
3878 ALOGV("entering threadLoop()");
3879 while (!exitPending())
3880 {
3881 String8 command;
3882 int valueInt;
3883 String8 value;
3884
3885 Mutex::Autolock _l(mLock);
3886 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3887
3888 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3889 AudioParameter param = AudioParameter(command);
3890
3891 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3892 valueInt != 0) {
3893 ALOGV("Test command %s received", command.string());
3894 String8 target;
3895 if (param.get(String8("target"), target) != NO_ERROR) {
3896 target = "Manager";
3897 }
3898 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3899 param.remove(String8("test_cmd_policy_output"));
3900 mCurOutput = valueInt;
3901 }
3902 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3903 param.remove(String8("test_cmd_policy_direct"));
3904 if (value == "false") {
3905 mDirectOutput = false;
3906 } else if (value == "true") {
3907 mDirectOutput = true;
3908 }
3909 }
3910 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3911 param.remove(String8("test_cmd_policy_input"));
3912 mTestInput = valueInt;
3913 }
3914
3915 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3916 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003917 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003918 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003919 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003920 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003921 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003922 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003923 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003924 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003925 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003926 if (target == "Manager") {
3927 mTestFormat = format;
3928 } else if (mTestOutputs[mCurOutput] != 0) {
3929 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003930 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003931 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3932 }
3933 }
3934 }
3935 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3936 param.remove(String8("test_cmd_policy_channels"));
3937 int channels = 0;
3938
3939 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003940 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003941 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003942 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003943 }
3944 if (channels != 0) {
3945 if (target == "Manager") {
3946 mTestChannels = channels;
3947 } else if (mTestOutputs[mCurOutput] != 0) {
3948 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003949 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003950 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3951 }
3952 }
3953 }
3954 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3955 param.remove(String8("test_cmd_policy_sampleRate"));
3956 if (valueInt >= 0 && valueInt <= 96000) {
3957 int samplingRate = valueInt;
3958 if (target == "Manager") {
3959 mTestSamplingRate = samplingRate;
3960 } else if (mTestOutputs[mCurOutput] != 0) {
3961 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003962 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003963 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3964 }
3965 }
3966 }
3967
3968 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3969 param.remove(String8("test_cmd_policy_reopen"));
3970
Eric Laurentc75307b2015-03-17 15:29:32 -07003971 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003972
Eric Laurentc75307b2015-03-17 15:29:32 -07003973 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003974
Eric Laurentc75307b2015-03-17 15:29:32 -07003975 removeOutput(mPrimaryOutput->mIoHandle);
3976 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3977 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003978 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003979 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3980 config.sample_rate = outputDesc->mSamplingRate;
3981 config.channel_mask = outputDesc->mChannelMask;
3982 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003983 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003984 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003985 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003986 &config,
3987 &outputDesc->mDevice,
3988 String8(""),
3989 &outputDesc->mLatency,
3990 outputDesc->mFlags);
3991 if (status != NO_ERROR) {
3992 ALOGE("Failed to reopen hardware output stream, "
3993 "samplingRate: %d, format %d, channels %d",
3994 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003995 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003996 outputDesc->mSamplingRate = config.sample_rate;
3997 outputDesc->mChannelMask = config.channel_mask;
3998 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003999 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07004000 AudioParameter outputCmd = AudioParameter();
4001 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07004002 mpClientInterface->setParameters(handle, outputCmd.toString());
4003 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07004004 }
4005 }
4006
4007
4008 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
4009 }
4010 }
4011 return false;
4012}
4013
Eric Laurente0720872014-03-11 09:30:41 -07004014void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07004015{
4016 {
4017 AutoMutex _l(mLock);
4018 requestExit();
4019 mWaitWorkCV.signal();
4020 }
4021 requestExitAndWait();
4022}
4023
Eric Laurente0720872014-03-11 09:30:41 -07004024int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004025{
4026 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
4027 if (output == mTestOutputs[i]) return i;
4028 }
4029 return 0;
4030}
4031#endif //AUDIO_POLICY_TEST
4032
4033// ---
4034
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004035void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004036{
François Gaffie98cc1912015-03-18 17:52:40 +01004037 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07004038 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08004039 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004040 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004041 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004042}
4043
François Gaffie53615e22015-03-19 09:24:12 +01004044void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4045{
4046 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004047 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004048}
4049
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004050void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004051{
François Gaffie98cc1912015-03-18 17:52:40 +01004052 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004053 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004054 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004055}
Eric Laurente552edb2014-03-10 17:42:56 -07004056
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004057void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004058 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004059 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004060 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004061 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004062 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004063 if (devDesc != 0) {
4064 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4065 desc->mIoHandle, address.string());
4066 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004067 }
4068}
4069
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004070status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004071 audio_policy_dev_state_t state,
4072 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004073 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004074{
François Gaffie53615e22015-03-19 09:24:12 +01004075 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004076 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004077
4078 if (audio_device_is_digital(device)) {
4079 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004080 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004081 }
Eric Laurente552edb2014-03-10 17:42:56 -07004082
Eric Laurent3b73df72014-03-11 09:06:29 -07004083 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004084 // first list already open outputs that can be routed to this device
4085 for (size_t i = 0; i < mOutputs.size(); i++) {
4086 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004087 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004088 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004089 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4090 outputs.add(mOutputs.keyAt(i));
4091 } else {
4092 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004093 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004094 }
Eric Laurente552edb2014-03-10 17:42:56 -07004095 }
4096 }
4097 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004098 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07004099 for (size_t i = 0; i < mHwModules.size(); i++)
4100 {
4101 if (mHwModules[i]->mHandle == 0) {
4102 continue;
4103 }
4104 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4105 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004106 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004107 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004108 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004109 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004110 profiles.add(profile);
4111 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
4112 }
Eric Laurente552edb2014-03-10 17:42:56 -07004113 }
4114 }
4115 }
4116
Eric Laurent7b279bb2015-12-14 10:18:23 -08004117 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004118
Eric Laurente552edb2014-03-10 17:42:56 -07004119 if (profiles.isEmpty() && outputs.isEmpty()) {
4120 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4121 return BAD_VALUE;
4122 }
4123
4124 // open outputs for matching profiles if needed. Direct outputs are also opened to
4125 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4126 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004127 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004128
4129 // nothing to do if one output is already opened for this profile
4130 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004131 for (j = 0; j < outputs.size(); j++) {
4132 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004133 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004134 // matching profile: save the sample rates, format and channel masks supported
4135 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004136 if (audio_device_is_digital(device)) {
4137 devDesc->importAudioPort(profile);
4138 }
Eric Laurente552edb2014-03-10 17:42:56 -07004139 break;
4140 }
4141 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004142 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004143 continue;
4144 }
4145
Eric Laurent83efe1c2017-07-09 16:51:08 -07004146 ALOGV("opening output for device %08x with params %s profile %p name %s",
4147 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004148 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07004149 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004150 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4151 config.sample_rate = desc->mSamplingRate;
4152 config.channel_mask = desc->mChannelMask;
4153 config.format = desc->mFormat;
4154 config.offload_info.sample_rate = desc->mSamplingRate;
4155 config.offload_info.channel_mask = desc->mChannelMask;
4156 config.offload_info.format = desc->mFormat;
4157 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004158 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004159 &output,
4160 &config,
4161 &desc->mDevice,
4162 address,
4163 &desc->mLatency,
4164 desc->mFlags);
4165 if (status == NO_ERROR) {
4166 desc->mSamplingRate = config.sample_rate;
4167 desc->mChannelMask = config.channel_mask;
4168 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07004169
Eric Laurentd4692962014-05-05 18:13:44 -07004170 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004171 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004172 char *param = audio_device_address_to_parameter(device, address);
4173 mpClientInterface->setParameters(output, String8(param));
4174 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004175 }
Phil Burk00eeb322016-03-31 12:41:00 -07004176 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004177 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004178 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07004179 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004180 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004181 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004182 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08004183 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004184 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004185 config.offload_info.sample_rate = config.sample_rate;
4186 config.offload_info.channel_mask = config.channel_mask;
4187 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07004188 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004189 &output,
4190 &config,
4191 &desc->mDevice,
4192 address,
4193 &desc->mLatency,
4194 desc->mFlags);
4195 if (status == NO_ERROR) {
4196 desc->mSamplingRate = config.sample_rate;
4197 desc->mChannelMask = config.channel_mask;
4198 desc->mFormat = config.format;
4199 } else {
4200 output = AUDIO_IO_HANDLE_NONE;
4201 }
Eric Laurentd4692962014-05-05 18:13:44 -07004202 }
4203
Eric Laurentcf2c0212014-07-25 16:20:43 -07004204 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004205 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004206 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004207 sp<AudioPolicyMix> policyMix;
4208 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004209 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4210 address.string());
4211 }
François Gaffie036e1e92015-03-19 10:16:24 +01004212 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004213 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004214
Eric Laurent87ffa392015-05-22 10:32:38 -07004215 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4216 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004217 // no duplicated output for direct outputs and
4218 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004219 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004220
Eric Laurentd4692962014-05-05 18:13:44 -07004221 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07004222 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07004223
Eric Laurentd4692962014-05-05 18:13:44 -07004224 //TODO: configure audio effect output stage here
4225
4226 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07004227 duplicatedOutput =
4228 mpClientInterface->openDuplicateOutput(output,
4229 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004230 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004231 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07004232 sp<SwAudioOutputDescriptor> dupOutputDesc =
4233 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4234 dupOutputDesc->mOutput1 = mPrimaryOutput;
4235 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07004236 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4237 dupOutputDesc->mFormat = desc->mFormat;
4238 dupOutputDesc->mChannelMask = desc->mChannelMask;
4239 dupOutputDesc->mLatency = desc->mLatency;
4240 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004241 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004242 } else {
4243 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004244 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004245 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004246 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004247 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004248 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004249 }
Eric Laurente552edb2014-03-10 17:42:56 -07004250 }
4251 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004252 } else {
4253 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004254 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004255 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004256 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004257 profiles.removeAt(profile_index);
4258 profile_index--;
4259 } else {
4260 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004261 // Load digital format info only for digital devices
4262 if (audio_device_is_digital(device)) {
4263 devDesc->importAudioPort(profile);
4264 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004265
François Gaffie53615e22015-03-19 09:24:12 +01004266 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004267 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4268 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004269 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004270 NULL/*patch handle*/, address.string());
4271 }
Eric Laurente552edb2014-03-10 17:42:56 -07004272 ALOGV("checkOutputsForDevice(): adding output %d", output);
4273 }
4274 }
4275
4276 if (profiles.isEmpty()) {
4277 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4278 return BAD_VALUE;
4279 }
Eric Laurentd4692962014-05-05 18:13:44 -07004280 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004281 // check if one opened output is not needed any more after disconnecting one device
4282 for (size_t i = 0; i < mOutputs.size(); i++) {
4283 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004284 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004285 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004286 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004287 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004288 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004289 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004290 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4291 mOutputs.keyAt(i));
4292 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004293 }
Eric Laurente552edb2014-03-10 17:42:56 -07004294 }
4295 }
Eric Laurentd4692962014-05-05 18:13:44 -07004296 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004297 for (size_t i = 0; i < mHwModules.size(); i++)
4298 {
4299 if (mHwModules[i]->mHandle == 0) {
4300 continue;
4301 }
4302 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4303 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004304 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004305 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004306 ALOGV("checkOutputsForDevice(): "
4307 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004308 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004309 }
4310 }
4311 }
4312 }
4313 return NO_ERROR;
4314}
4315
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004316status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004317 audio_policy_dev_state_t state,
4318 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004319 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004320{
Paul McLean9080a4c2015-06-18 08:24:02 -07004321 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004322 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004323
4324 if (audio_device_is_digital(device)) {
4325 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004326 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004327 }
4328
Eric Laurentd4692962014-05-05 18:13:44 -07004329 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4330 // first list already open inputs that can be routed to this device
4331 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4332 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004333 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004334 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4335 inputs.add(mInputs.keyAt(input_index));
4336 }
4337 }
4338
4339 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004340 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004341 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4342 {
4343 if (mHwModules[module_idx]->mHandle == 0) {
4344 continue;
4345 }
4346 for (size_t profile_index = 0;
4347 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4348 profile_index++)
4349 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004350 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4351
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004352 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004353 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004354 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004355 profiles.add(profile);
4356 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4357 profile_index, module_idx);
4358 }
Eric Laurentd4692962014-05-05 18:13:44 -07004359 }
4360 }
4361 }
4362
4363 if (profiles.isEmpty() && inputs.isEmpty()) {
4364 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4365 return BAD_VALUE;
4366 }
4367
4368 // open inputs for matching profiles if needed. Direct inputs are also opened to
4369 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4370 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4371
Eric Laurent1c333e22014-05-20 10:48:17 -07004372 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004373 // nothing to do if one input is already opened for this profile
4374 size_t input_index;
4375 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4376 desc = mInputs.valueAt(input_index);
4377 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004378 if (audio_device_is_digital(device)) {
4379 devDesc->importAudioPort(profile);
4380 }
Eric Laurentd4692962014-05-05 18:13:44 -07004381 break;
4382 }
4383 }
4384 if (input_index != mInputs.size()) {
4385 continue;
4386 }
4387
4388 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4389 desc = new AudioInputDescriptor(profile);
4390 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004391 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4392 config.sample_rate = desc->mSamplingRate;
4393 config.channel_mask = desc->mChannelMask;
4394 config.format = desc->mFormat;
4395 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004396
4397 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4398 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4399
Eric Laurent322b4d22015-04-03 15:57:54 -07004400 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004401 &input,
4402 &config,
4403 &desc->mDevice,
4404 address,
4405 AUDIO_SOURCE_MIC,
4406 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004407
Eric Laurentcf2c0212014-07-25 16:20:43 -07004408 if (status == NO_ERROR) {
4409 desc->mSamplingRate = config.sample_rate;
4410 desc->mChannelMask = config.channel_mask;
4411 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004412
Eric Laurentd4692962014-05-05 18:13:44 -07004413 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004414 char *param = audio_device_address_to_parameter(device, address);
4415 mpClientInterface->setParameters(input, String8(param));
4416 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004417 }
Phil Burk00eeb322016-03-31 12:41:00 -07004418 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004419 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004420 ALOGW("checkInputsForDevice() direct input missing param");
4421 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004422 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004423 }
4424
4425 if (input != 0) {
4426 addInput(input, desc);
4427 }
4428 } // endif input != 0
4429
Eric Laurentcf2c0212014-07-25 16:20:43 -07004430 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004431 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004432 profiles.removeAt(profile_index);
4433 profile_index--;
4434 } else {
4435 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004436 if (audio_device_is_digital(device)) {
4437 devDesc->importAudioPort(profile);
4438 }
Eric Laurentd4692962014-05-05 18:13:44 -07004439 ALOGV("checkInputsForDevice(): adding input %d", input);
4440 }
4441 } // end scan profiles
4442
4443 if (profiles.isEmpty()) {
4444 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4445 return BAD_VALUE;
4446 }
4447 } else {
4448 // Disconnect
4449 // check if one opened input is not needed any more after disconnecting one device
4450 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4451 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004452 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004453 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4454 mInputs.keyAt(input_index));
4455 inputs.add(mInputs.keyAt(input_index));
4456 }
4457 }
4458 // Clear any profiles associated with the disconnected device.
4459 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4460 if (mHwModules[module_index]->mHandle == 0) {
4461 continue;
4462 }
4463 for (size_t profile_index = 0;
4464 profile_index < mHwModules[module_index]->mInputProfiles.size();
4465 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004466 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004467 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004468 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004469 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004470 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004471 }
4472 }
4473 }
4474 } // end disconnect
4475
4476 return NO_ERROR;
4477}
4478
4479
Eric Laurente0720872014-03-11 09:30:41 -07004480void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004481{
4482 ALOGV("closeOutput(%d)", output);
4483
Eric Laurentc75307b2015-03-17 15:29:32 -07004484 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004485 if (outputDesc == NULL) {
4486 ALOGW("closeOutput() unknown output %d", output);
4487 return;
4488 }
François Gaffie036e1e92015-03-19 10:16:24 +01004489 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004490
Eric Laurente552edb2014-03-10 17:42:56 -07004491 // look for duplicated outputs connected to the output being removed.
4492 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004493 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004494 if (dupOutputDesc->isDuplicated() &&
4495 (dupOutputDesc->mOutput1 == outputDesc ||
4496 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004497 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004498 if (dupOutputDesc->mOutput1 == outputDesc) {
4499 outputDesc2 = dupOutputDesc->mOutput2;
4500 } else {
4501 outputDesc2 = dupOutputDesc->mOutput1;
4502 }
4503 // As all active tracks on duplicated output will be deleted,
4504 // and as they were also referenced on the other output, the reference
4505 // count for their stream type must be adjusted accordingly on
4506 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004507 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004508 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004509 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004510 }
4511 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4512 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4513
4514 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004515 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004516 }
4517 }
4518
Eric Laurent05b90f82014-08-27 15:32:29 -07004519 nextAudioPortGeneration();
4520
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004521 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004522 if (index >= 0) {
4523 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004524 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004525 mAudioPatches.removeItemsAt(index);
4526 mpClientInterface->onAudioPatchListUpdate();
4527 }
4528
Eric Laurente552edb2014-03-10 17:42:56 -07004529 AudioParameter param;
4530 param.add(String8("closing"), String8("true"));
4531 mpClientInterface->setParameters(output, param.toString());
4532
4533 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004534 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004535 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004536}
4537
4538void AudioPolicyManager::closeInput(audio_io_handle_t input)
4539{
4540 ALOGV("closeInput(%d)", input);
4541
4542 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4543 if (inputDesc == NULL) {
4544 ALOGW("closeInput() unknown input %d", input);
4545 return;
4546 }
4547
Eric Laurent6a94d692014-05-20 11:18:06 -07004548 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004549
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004550 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004551 if (index >= 0) {
4552 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004553 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004554 mAudioPatches.removeItemsAt(index);
4555 mpClientInterface->onAudioPatchListUpdate();
4556 }
4557
4558 mpClientInterface->closeInput(input);
4559 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004560}
4561
Eric Laurentc75307b2015-03-17 15:29:32 -07004562SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4563 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004564 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004565{
4566 SortedVector<audio_io_handle_t> outputs;
4567
4568 ALOGVV("getOutputsForDevice() device %04x", device);
4569 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004570 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004571 i, openOutputs.valueAt(i)->isDuplicated(),
4572 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004573 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4574 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4575 outputs.add(openOutputs.keyAt(i));
4576 }
4577 }
4578 return outputs;
4579}
4580
Eric Laurente0720872014-03-11 09:30:41 -07004581bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004582 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004583{
4584 if (outputs1.size() != outputs2.size()) {
4585 return false;
4586 }
4587 for (size_t i = 0; i < outputs1.size(); i++) {
4588 if (outputs1[i] != outputs2[i]) {
4589 return false;
4590 }
4591 }
4592 return true;
4593}
4594
Eric Laurente0720872014-03-11 09:30:41 -07004595void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004596{
4597 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4598 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4599 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4600 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4601
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004602 // also take into account external policy-related changes: add all outputs which are
4603 // associated with policies in the "before" and "after" output vectors
4604 ALOGVV("checkOutputForStrategy(): policy related outputs");
4605 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004606 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004607 if (desc != 0 && desc->mPolicyMix != NULL) {
4608 srcOutputs.add(desc->mIoHandle);
4609 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4610 }
4611 }
4612 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004613 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004614 if (desc != 0 && desc->mPolicyMix != NULL) {
4615 dstOutputs.add(desc->mIoHandle);
4616 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4617 }
4618 }
4619
Eric Laurente552edb2014-03-10 17:42:56 -07004620 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4621 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4622 strategy, srcOutputs[0], dstOutputs[0]);
4623 // mute strategy while moving tracks from one output to another
4624 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004625 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004626 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004627 setStrategyMute(strategy, true, desc);
4628 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004629 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004630 sp<AudioSourceDescriptor> source =
4631 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4632 if (source != 0){
4633 connectAudioSource(source);
4634 }
Eric Laurente552edb2014-03-10 17:42:56 -07004635 }
4636
4637 // Move effects associated to this strategy from previous output to new output
4638 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004639 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004640 }
4641 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004642 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004643 if (getStrategy((audio_stream_type_t)i) == strategy) {
4644 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004645 }
4646 }
4647 }
4648}
4649
Eric Laurente0720872014-03-11 09:30:41 -07004650void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004651{
François Gaffie2110e042015-03-24 08:41:51 +01004652 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004653 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004654 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004655 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004656 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004657 checkOutputForStrategy(STRATEGY_SONIFICATION);
4658 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004659 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004660 checkOutputForStrategy(STRATEGY_MEDIA);
4661 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004662 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004663}
4664
Eric Laurente0720872014-03-11 09:30:41 -07004665void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004666{
François Gaffie53615e22015-03-19 09:24:12 +01004667 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004668 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004669 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004670 return;
4671 }
4672
Eric Laurent3a4311c2014-03-17 12:00:47 -07004673 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004674 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4675 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4676 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004677
4678 // if suspended, restore A2DP output if:
4679 // ((SCO device is NOT connected) ||
4680 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4681 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004682 //
Eric Laurentf732e072016-08-03 19:30:28 -07004683 // if not suspended, suspend A2DP output if:
4684 // (SCO device is connected) &&
4685 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4686 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004687 //
4688 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004689 if (!isScoConnected ||
4690 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4691 AUDIO_POLICY_FORCE_BT_SCO) &&
4692 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4693 AUDIO_POLICY_FORCE_BT_SCO) &&
4694 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004695 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004696
4697 mpClientInterface->restoreOutput(a2dpOutput);
4698 mA2dpSuspended = false;
4699 }
4700 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004701 if (isScoConnected &&
4702 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4703 AUDIO_POLICY_FORCE_BT_SCO) ||
4704 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4705 AUDIO_POLICY_FORCE_BT_SCO) ||
4706 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004707 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004708
4709 mpClientInterface->suspendOutput(a2dpOutput);
4710 mA2dpSuspended = true;
4711 }
4712 }
4713}
4714
Eric Laurentc75307b2015-03-17 15:29:32 -07004715audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4716 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004717{
4718 audio_devices_t device = AUDIO_DEVICE_NONE;
4719
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004720 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004721 if (index >= 0) {
4722 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4723 if (patchDesc->mUid != mUidCached) {
4724 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004725 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 return outputDesc->device();
4727 }
4728 }
4729
Eric Laurente552edb2014-03-10 17:42:56 -07004730 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004731 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004732 // use device for strategy enforced audible
4733 // 2: we are in call or the strategy phone is active on the output:
4734 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004735 // 3: the strategy for enforced audible is active but not enforced on the output:
4736 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004737 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004738 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004739 // 5: the strategy accessibility is active on the output:
4740 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004741 // 6: the strategy "respectful" sonification is active on the output:
4742 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004743 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004744 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004745 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004746 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004747 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004748 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004749 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004750 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004751 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4752 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004753 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004754 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004755 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004756 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004757 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004758 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004759 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4760 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004761 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004762 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004763 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004764 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004765 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004766 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004767 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004768 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004769 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004770 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004771 }
4772
Eric Laurent1c333e22014-05-20 10:48:17 -07004773 ALOGV("getNewOutputDevice() selected device %x", device);
4774 return device;
4775}
4776
Eric Laurentfb66dd92016-01-28 18:32:03 -08004777audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004778{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004779 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004780
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004781 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004782 if (index >= 0) {
4783 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4784 if (patchDesc->mUid != mUidCached) {
4785 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004786 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 return inputDesc->mDevice;
4788 }
4789 }
4790
Eric Laurentfb66dd92016-01-28 18:32:03 -08004791 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4792 if (isInCall()) {
4793 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4794 } else if (source != AUDIO_SOURCE_DEFAULT) {
4795 device = getDeviceAndMixForInputSource(source);
4796 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004797
Eric Laurente552edb2014-03-10 17:42:56 -07004798 return device;
4799}
4800
Eric Laurent794fde22016-03-11 09:50:45 -08004801bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4802 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004803 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004804}
4805
Eric Laurente0720872014-03-11 09:30:41 -07004806uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004807 return (uint32_t)getStrategy(stream);
4808}
4809
Eric Laurente0720872014-03-11 09:30:41 -07004810audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004811 // By checking the range of stream before calling getStrategy, we avoid
4812 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4813 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004814 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 return AUDIO_DEVICE_NONE;
4816 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004817 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004818 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4819 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004820 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004821 }
Eric Laurent794fde22016-03-11 09:50:45 -08004822 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004823 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004824 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004825 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4826 for (size_t i = 0; i < outputs.size(); i++) {
4827 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004828 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004829 curDevices |= outputDesc->device();
4830 }
4831 }
4832 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004833 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004834
4835 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4836 and doesn't really need to.*/
4837 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4838 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4839 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4840 }
Eric Laurente552edb2014-03-10 17:42:56 -07004841 return devices;
4842}
4843
François Gaffie2110e042015-03-24 08:41:51 +01004844routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4845{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004846 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004847 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004848}
4849
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004850uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4851 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004852 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4853 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4854 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004855 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4856 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4857 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004858 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004859 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004860}
4861
Eric Laurente0720872014-03-11 09:30:41 -07004862void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004863 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004864 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004865 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4866 updateDevicesAndOutputs();
4867 break;
4868 default:
4869 break;
4870 }
4871}
4872
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004873uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004874
4875 // skip beacon mute management if a dedicated TTS output is available
4876 if (mTtsOutputAvailable) {
4877 return 0;
4878 }
4879
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004880 switch(event) {
4881 case STARTING_OUTPUT:
4882 mBeaconMuteRefCount++;
4883 break;
4884 case STOPPING_OUTPUT:
4885 if (mBeaconMuteRefCount > 0) {
4886 mBeaconMuteRefCount--;
4887 }
4888 break;
4889 case STARTING_BEACON:
4890 mBeaconPlayingRefCount++;
4891 break;
4892 case STOPPING_BEACON:
4893 if (mBeaconPlayingRefCount > 0) {
4894 mBeaconPlayingRefCount--;
4895 }
4896 break;
4897 }
4898
4899 if (mBeaconMuteRefCount > 0) {
4900 // any playback causes beacon to be muted
4901 return setBeaconMute(true);
4902 } else {
4903 // no other playback: unmute when beacon starts playing, mute when it stops
4904 return setBeaconMute(mBeaconPlayingRefCount == 0);
4905 }
4906}
4907
4908uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4909 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4910 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4911 // keep track of muted state to avoid repeating mute/unmute operations
4912 if (mBeaconMuted != mute) {
4913 // mute/unmute AUDIO_STREAM_TTS on all outputs
4914 ALOGV("\t muting %d", mute);
4915 uint32_t maxLatency = 0;
4916 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004918 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004919 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004920 0 /*delay*/, AUDIO_DEVICE_NONE);
4921 const uint32_t latency = desc->latency() * 2;
4922 if (latency > maxLatency) {
4923 maxLatency = latency;
4924 }
4925 }
4926 mBeaconMuted = mute;
4927 return maxLatency;
4928 }
4929 return 0;
4930}
4931
Eric Laurente0720872014-03-11 09:30:41 -07004932audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004933 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004934{
Paul McLeanaa981192015-03-21 09:55:15 -07004935 // Routing
4936 // see if we have an explicit route
4937 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4938 // (getStrategy(stream)).
4939 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4940 // and activity count is non-zero
4941 // the device = the device from the descriptor in the RouteMap, and exit.
4942 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4943 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004944 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4945 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004946 return route->mDeviceDescriptor->type();
4947 }
4948 }
4949
Eric Laurente552edb2014-03-10 17:42:56 -07004950 if (fromCache) {
4951 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4952 strategy, mDeviceForStrategy[strategy]);
4953 return mDeviceForStrategy[strategy];
4954 }
François Gaffie2110e042015-03-24 08:41:51 +01004955 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004956}
4957
Eric Laurente0720872014-03-11 09:30:41 -07004958void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004959{
4960 for (int i = 0; i < NUM_STRATEGIES; i++) {
4961 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4962 }
4963 mPreviousOutputs = mOutputs;
4964}
4965
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004966uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004967 audio_devices_t prevDevice,
4968 uint32_t delayMs)
4969{
4970 // mute/unmute strategies using an incompatible device combination
4971 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4972 // if unmuting, unmute only after the specified delay
4973 if (outputDesc->isDuplicated()) {
4974 return 0;
4975 }
4976
4977 uint32_t muteWaitMs = 0;
4978 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004979 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004980
4981 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4982 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004983 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004984 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4985 bool doMute = false;
4986
4987 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4988 doMute = true;
4989 outputDesc->mStrategyMutedByDevice[i] = true;
4990 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4991 doMute = true;
4992 outputDesc->mStrategyMutedByDevice[i] = false;
4993 }
Eric Laurent99401132014-05-07 19:48:15 -07004994 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004995 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004996 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004997 // skip output if it does not share any device with current output
4998 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4999 == AUDIO_DEVICE_NONE) {
5000 continue;
5001 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005002 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005003 mute ? "muting" : "unmuting", i, curDevice);
5004 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005005 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005006 if (mute) {
5007 // FIXME: should not need to double latency if volume could be applied
5008 // immediately by the audioflinger mixer. We must account for the delay
5009 // between now and the next time the audioflinger thread for this output
5010 // will process a buffer (which corresponds to one buffer size,
5011 // usually 1/2 or 1/4 of the latency).
5012 if (muteWaitMs < desc->latency() * 2) {
5013 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005014 }
5015 }
5016 }
5017 }
5018 }
5019 }
5020
Eric Laurent99401132014-05-07 19:48:15 -07005021 // temporary mute output if device selection changes to avoid volume bursts due to
5022 // different per device volumes
5023 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005024 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5025 // temporary mute duration is conservatively set to 4 times the reported latency
5026 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5027 if (muteWaitMs < tempMuteWaitMs) {
5028 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005029 }
Eric Laurentdc462862016-07-19 12:29:53 -07005030
Eric Laurent99401132014-05-07 19:48:15 -07005031 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005032 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005033 // make sure that we do not start the temporary mute period too early in case of
5034 // delayed device change
5035 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005036 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005037 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005038 }
5039 }
5040 }
5041
Eric Laurente552edb2014-03-10 17:42:56 -07005042 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5043 if (muteWaitMs > delayMs) {
5044 muteWaitMs -= delayMs;
5045 usleep(muteWaitMs * 1000);
5046 return muteWaitMs;
5047 }
5048 return 0;
5049}
5050
Eric Laurentc75307b2015-03-17 15:29:32 -07005051uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005052 audio_devices_t device,
5053 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005055 audio_patch_handle_t *patchHandle,
5056 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07005057{
Eric Laurentc75307b2015-03-17 15:29:32 -07005058 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005059 AudioParameter param;
5060 uint32_t muteWaitMs;
5061
5062 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005063 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
5064 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005065 return muteWaitMs;
5066 }
5067 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5068 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005069 if ((device != AUDIO_DEVICE_NONE) &&
5070 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005071 return 0;
5072 }
5073
5074 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005075 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005076
5077 audio_devices_t prevDevice = outputDesc->mDevice;
5078
Paul McLeanaa981192015-03-21 09:55:15 -07005079 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005080
5081 if (device != AUDIO_DEVICE_NONE) {
5082 outputDesc->mDevice = device;
5083 }
5084 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5085
5086 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005087 // the requested device is AUDIO_DEVICE_NONE
5088 // OR the requested device is the same as current device
5089 // AND force is not specified
5090 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005091 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005092 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5093 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005094 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005095 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005096 return muteWaitMs;
5097 }
5098
5099 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005100
Eric Laurente552edb2014-03-10 17:42:56 -07005101 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005102 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005103 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005104 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005105 DeviceVector deviceList;
5106 if ((address == NULL) || (strlen(address) == 0)) {
5107 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5108 } else {
5109 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5110 }
5111
Eric Laurent1c333e22014-05-20 10:48:17 -07005112 if (!deviceList.isEmpty()) {
5113 struct audio_patch patch;
5114 outputDesc->toAudioPortConfig(&patch.sources[0]);
5115 patch.num_sources = 1;
5116 patch.num_sinks = 0;
5117 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5118 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005119 patch.num_sinks++;
5120 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005121 ssize_t index;
5122 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5123 index = mAudioPatches.indexOfKey(*patchHandle);
5124 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005125 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005126 }
5127 sp< AudioPatch> patchDesc;
5128 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5129 if (index >= 0) {
5130 patchDesc = mAudioPatches.valueAt(index);
5131 afPatchHandle = patchDesc->mAfPatchHandle;
5132 }
5133
Eric Laurent1c333e22014-05-20 10:48:17 -07005134 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005135 &afPatchHandle,
5136 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005137 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5138 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005139 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005140 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005141 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005142 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 addAudioPatch(patchDesc->mHandle, patchDesc);
5144 } else {
5145 patchDesc->mPatch = patch;
5146 }
5147 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005148 if (patchHandle) {
5149 *patchHandle = patchDesc->mHandle;
5150 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005151 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005152 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005153 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005154 }
5155 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005156
5157 // inform all input as well
5158 for (size_t i = 0; i < mInputs.size(); i++) {
5159 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005160 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005161 AudioParameter inputCmd = AudioParameter();
5162 ALOGV("%s: inform input %d of device:%d", __func__,
5163 inputDescriptor->mIoHandle, device);
5164 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5165 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5166 inputCmd.toString(),
5167 delayMs);
5168 }
5169 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005170 }
Eric Laurente552edb2014-03-10 17:42:56 -07005171
5172 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005173 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005174
5175 return muteWaitMs;
5176}
5177
Eric Laurentc75307b2015-03-17 15:29:32 -07005178status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 int delayMs,
5180 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005181{
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 ssize_t index;
5183 if (patchHandle) {
5184 index = mAudioPatches.indexOfKey(*patchHandle);
5185 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005186 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 }
5188 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005189 return INVALID_OPERATION;
5190 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5192 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005193 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005194 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005195 removeAudioPatch(patchDesc->mHandle);
5196 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005197 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005198 return status;
5199}
5200
5201status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5202 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 bool force,
5204 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005205{
5206 status_t status = NO_ERROR;
5207
Eric Laurent1f2f2232014-06-02 12:01:23 -07005208 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005209 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5210 inputDesc->mDevice = device;
5211
5212 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5213 if (!deviceList.isEmpty()) {
5214 struct audio_patch patch;
5215 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005216 // AUDIO_SOURCE_HOTWORD is for internal use only:
5217 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005218 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005219 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005220 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5221 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005222 patch.num_sinks = 1;
5223 //only one input device for now
5224 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005225 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 ssize_t index;
5227 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5228 index = mAudioPatches.indexOfKey(*patchHandle);
5229 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005230 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 }
5232 sp< AudioPatch> patchDesc;
5233 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5234 if (index >= 0) {
5235 patchDesc = mAudioPatches.valueAt(index);
5236 afPatchHandle = patchDesc->mAfPatchHandle;
5237 }
5238
Eric Laurent1c333e22014-05-20 10:48:17 -07005239 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 0);
5242 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005244 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005246 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 addAudioPatch(patchDesc->mHandle, patchDesc);
5248 } else {
5249 patchDesc->mPatch = patch;
5250 }
5251 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005252 if (patchHandle) {
5253 *patchHandle = patchDesc->mHandle;
5254 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005255 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005256 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005257 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005258 }
5259 }
5260 }
5261 return status;
5262}
5263
Eric Laurent6a94d692014-05-20 11:18:06 -07005264status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5265 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005266{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005267 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 ssize_t index;
5269 if (patchHandle) {
5270 index = mAudioPatches.indexOfKey(*patchHandle);
5271 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005272 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 }
5274 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 return INVALID_OPERATION;
5276 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5278 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005279 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005280 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005281 removeAudioPatch(patchDesc->mHandle);
5282 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005283 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005284 return status;
5285}
5286
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005287sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005288 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005289 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005290 audio_format_t& format,
5291 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005292 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005293{
5294 // Choose an input profile based on the requested capture parameters: select the first available
5295 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005296 //
5297 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5298 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005299
5300 for (size_t i = 0; i < mHwModules.size(); i++)
5301 {
5302 if (mHwModules[i]->mHandle == 0) {
5303 continue;
5304 }
5305 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5306 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005307 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005308 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005309 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005310 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005311 format,
5312 &format /*updatedFormat*/,
5313 channelMask,
5314 &channelMask /*updatedChannelMask*/,
5315 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005316
Eric Laurente552edb2014-03-10 17:42:56 -07005317 return profile;
5318 }
5319 }
5320 }
5321 return NULL;
5322}
5323
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005324
5325audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005326 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005327{
François Gaffie036e1e92015-03-19 10:16:24 +01005328 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5329 audio_devices_t selectedDeviceFromMix =
5330 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005331
François Gaffie036e1e92015-03-19 10:16:24 +01005332 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5333 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005334 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005335 return getDeviceForInputSource(inputSource);
5336}
5337
5338audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5339{
Paul McLean466dc8e2015-04-17 13:15:36 -06005340 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5341 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005342 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005343 return route->mDeviceDescriptor->type();
5344 }
5345 }
5346
5347 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005348}
5349
Eric Laurente0720872014-03-11 09:30:41 -07005350float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005351 int index,
5352 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005353{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005354 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005355
5356 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5357 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5358 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5359 // the ringtone volume
5360 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5361 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5362 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5363 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5364 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5365 }
5366
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005367 // in-call: always cap earpiece volume by voice volume + some low headroom
5368 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5369 switch (stream) {
5370 case AUDIO_STREAM_SYSTEM:
5371 case AUDIO_STREAM_RING:
5372 case AUDIO_STREAM_MUSIC:
5373 case AUDIO_STREAM_ALARM:
5374 case AUDIO_STREAM_NOTIFICATION:
5375 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5376 case AUDIO_STREAM_DTMF:
5377 case AUDIO_STREAM_ACCESSIBILITY: {
5378 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5379 + IN_CALL_EARPIECE_HEADROOM_DB;
5380 if (volumeDB > maxVoiceVolDb) {
5381 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5382 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5383 volumeDB = maxVoiceVolDb;
5384 }
5385 } break;
5386 default:
5387 break;
5388 }
5389 }
5390
Eric Laurente552edb2014-03-10 17:42:56 -07005391 // if a headset is connected, apply the following rules to ring tones and notifications
5392 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005393 // - always attenuate notifications volume by 6dB
5394 // - attenuate ring tones volume by 6dB unless music is not playing and
5395 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005396 // - if music is playing, always limit the volume to current music volume,
5397 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005398 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005399 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5400 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5401 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005402 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5403 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005404 ((stream_strategy == STRATEGY_SONIFICATION)
5405 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005406 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005407 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005408 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005409 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005410 // when the phone is ringing we must consider that music could have been paused just before
5411 // by the music application and behave as if music was active if the last music track was
5412 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005413 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005414 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005415 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005416 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005417 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005418 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5419 musicDevice),
5420 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005421 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5422 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005423 if (volumeDB > minVolDB) {
5424 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005425 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005426 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005427 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5428 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5429 // on A2DP, also ensure notification volume is not too low compared to media when
5430 // intended to be played
5431 if ((volumeDB > -96.0f) &&
5432 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5433 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5434 stream, device,
5435 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5436 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5437 }
5438 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005439 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5440 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005441 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005442 }
5443 }
5444
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005445 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005446}
5447
Eric Laurente0720872014-03-11 09:30:41 -07005448status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005449 int index,
5450 const sp<AudioOutputDescriptor>& outputDesc,
5451 audio_devices_t device,
5452 int delayMs,
5453 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005454{
Eric Laurente552edb2014-03-10 17:42:56 -07005455 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005456 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005457 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005458 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005459 return NO_ERROR;
5460 }
François Gaffie2110e042015-03-24 08:41:51 +01005461 audio_policy_forced_cfg_t forceUseForComm =
5462 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005463 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005464 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5465 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005466 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005467 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005468 return INVALID_OPERATION;
5469 }
5470
Eric Laurentc75307b2015-03-17 15:29:32 -07005471 if (device == AUDIO_DEVICE_NONE) {
5472 device = outputDesc->device();
5473 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005474
Eric Laurentffbc80f2015-03-18 18:30:19 -07005475 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005476 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005477 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005478 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005479
Eric Laurentffbc80f2015-03-18 18:30:19 -07005480 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005481
Eric Laurent3b73df72014-03-11 09:06:29 -07005482 if (stream == AUDIO_STREAM_VOICE_CALL ||
5483 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005484 float voiceVolume;
5485 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005486 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005487 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005488 } else {
5489 voiceVolume = 1.0;
5490 }
5491
Eric Laurent18fba842016-03-31 14:41:26 -07005492 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005493 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5494 mLastVoiceVolume = voiceVolume;
5495 }
5496 }
5497
5498 return NO_ERROR;
5499}
5500
Eric Laurentc75307b2015-03-17 15:29:32 -07005501void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5502 audio_devices_t device,
5503 int delayMs,
5504 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005505{
Eric Laurentc75307b2015-03-17 15:29:32 -07005506 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005507
Eric Laurent794fde22016-03-11 09:50:45 -08005508 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005509 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005510 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005511 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005512 device,
5513 delayMs,
5514 force);
5515 }
5516}
5517
Eric Laurente0720872014-03-11 09:30:41 -07005518void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005519 bool on,
5520 const sp<AudioOutputDescriptor>& outputDesc,
5521 int delayMs,
5522 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005523{
Eric Laurent72249d52015-06-08 11:12:15 -07005524 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5525 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005526 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005527 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005528 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005529 }
5530 }
5531}
5532
Eric Laurente0720872014-03-11 09:30:41 -07005533void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005534 bool on,
5535 const sp<AudioOutputDescriptor>& outputDesc,
5536 int delayMs,
5537 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005538{
Eric Laurente552edb2014-03-10 17:42:56 -07005539 if (device == AUDIO_DEVICE_NONE) {
5540 device = outputDesc->device();
5541 }
5542
Eric Laurentc75307b2015-03-17 15:29:32 -07005543 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5544 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005545
5546 if (on) {
5547 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005548 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005549 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005550 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005551 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005552 }
5553 }
5554 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5555 outputDesc->mMuteCount[stream]++;
5556 } else {
5557 if (outputDesc->mMuteCount[stream] == 0) {
5558 ALOGV("setStreamMute() unmuting non muted stream!");
5559 return;
5560 }
5561 if (--outputDesc->mMuteCount[stream] == 0) {
5562 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005563 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005564 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005565 device,
5566 delayMs);
5567 }
5568 }
5569}
5570
Eric Laurente0720872014-03-11 09:30:41 -07005571void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005572 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005573{
Eric Laurent87ffa392015-05-22 10:32:38 -07005574 if(!hasPrimaryOutput()) {
5575 return;
5576 }
5577
Eric Laurente552edb2014-03-10 17:42:56 -07005578 // if the stream pertains to sonification strategy and we are in call we must
5579 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5580 // in the device used for phone strategy and play the tone if the selected device does not
5581 // interfere with the device used for phone strategy
5582 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5583 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005584 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005585 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5586 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005587 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005588 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5589 stream, starting, outputDesc->mDevice, stateChange);
5590 if (outputDesc->mRefCount[stream]) {
5591 int muteCount = 1;
5592 if (stateChange) {
5593 muteCount = outputDesc->mRefCount[stream];
5594 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005595 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005596 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5597 for (int i = 0; i < muteCount; i++) {
5598 setStreamMute(stream, starting, mPrimaryOutput);
5599 }
5600 } else {
5601 ALOGV("handleIncallSonification() high visibility");
5602 if (outputDesc->device() &
5603 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5604 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5605 for (int i = 0; i < muteCount; i++) {
5606 setStreamMute(stream, starting, mPrimaryOutput);
5607 }
5608 }
5609 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005610 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5611 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005612 } else {
5613 mpClientInterface->stopTone();
5614 }
5615 }
5616 }
5617 }
5618}
5619
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005620audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5621{
5622 // flags to stream type mapping
5623 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5624 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5625 }
5626 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5627 return AUDIO_STREAM_BLUETOOTH_SCO;
5628 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005629 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5630 return AUDIO_STREAM_TTS;
5631 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005632
5633 // usage to stream type mapping
5634 switch (attr->usage) {
5635 case AUDIO_USAGE_MEDIA:
5636 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005637 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005638 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5639 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005640 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5641 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005642 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5643 return AUDIO_STREAM_SYSTEM;
5644 case AUDIO_USAGE_VOICE_COMMUNICATION:
5645 return AUDIO_STREAM_VOICE_CALL;
5646
5647 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5648 return AUDIO_STREAM_DTMF;
5649
5650 case AUDIO_USAGE_ALARM:
5651 return AUDIO_STREAM_ALARM;
5652 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5653 return AUDIO_STREAM_RING;
5654
5655 case AUDIO_USAGE_NOTIFICATION:
5656 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5657 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5658 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5659 case AUDIO_USAGE_NOTIFICATION_EVENT:
5660 return AUDIO_STREAM_NOTIFICATION;
5661
5662 case AUDIO_USAGE_UNKNOWN:
5663 default:
5664 return AUDIO_STREAM_MUSIC;
5665 }
5666}
Eric Laurente83b55d2014-11-14 10:06:21 -08005667
François Gaffie53615e22015-03-19 09:24:12 +01005668bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5669{
Eric Laurente83b55d2014-11-14 10:06:21 -08005670 // has flags that map to a strategy?
5671 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5672 return true;
5673 }
5674
5675 // has known usage?
5676 switch (paa->usage) {
5677 case AUDIO_USAGE_UNKNOWN:
5678 case AUDIO_USAGE_MEDIA:
5679 case AUDIO_USAGE_VOICE_COMMUNICATION:
5680 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5681 case AUDIO_USAGE_ALARM:
5682 case AUDIO_USAGE_NOTIFICATION:
5683 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5684 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5685 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5686 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5687 case AUDIO_USAGE_NOTIFICATION_EVENT:
5688 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5689 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5690 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5691 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005692 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005693 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005694 break;
5695 default:
5696 return false;
5697 }
5698 return true;
5699}
5700
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005701bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005702 routing_strategy strategy, uint32_t inPastMs,
5703 nsecs_t sysTime) const
5704{
5705 if ((sysTime == 0) && (inPastMs != 0)) {
5706 sysTime = systemTime();
5707 }
Eric Laurent794fde22016-03-11 09:50:45 -08005708 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005709 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5710 (NUM_STRATEGIES == strategy)) &&
5711 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5712 return true;
5713 }
5714 }
5715 return false;
5716}
5717
François Gaffie2110e042015-03-24 08:41:51 +01005718audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5719{
5720 return mEngine->getForceUse(usage);
5721}
5722
5723bool AudioPolicyManager::isInCall()
5724{
5725 return isStateInCall(mEngine->getPhoneState());
5726}
5727
5728bool AudioPolicyManager::isStateInCall(int state)
5729{
5730 return is_state_in_call(state);
5731}
5732
Eric Laurentd60560a2015-04-10 11:31:20 -07005733void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5734{
5735 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5736 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5737 if (sourceDesc->mDevice->equals(deviceDesc)) {
5738 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5739 stopAudioSource(sourceDesc->getHandle());
5740 }
5741 }
5742
5743 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5744 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5745 bool release = false;
5746 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5747 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5748 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5749 source->ext.device.type == deviceDesc->type()) {
5750 release = true;
5751 }
5752 }
5753 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5754 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5755 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5756 sink->ext.device.type == deviceDesc->type()) {
5757 release = true;
5758 }
5759 }
5760 if (release) {
5761 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5762 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5763 }
5764 }
5765}
5766
Phil Burk09bc4612016-02-24 15:58:15 -08005767// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005768void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5769 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005770 // TODO Set this based on Config properties.
5771 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005772
5773 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5774 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005775 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005776
5777 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005778 bool supportsAC3 = false;
5779 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005780 bool supportsIEC61937 = false;
5781 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5782 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005783 switch (format) {
5784 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005785 supportsAC3 = true;
5786 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005787 case AUDIO_FORMAT_E_AC3:
5788 case AUDIO_FORMAT_DTS:
5789 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005790 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005791 break;
5792 case AUDIO_FORMAT_IEC61937:
5793 supportsIEC61937 = true;
5794 break;
5795 default:
5796 break;
5797 }
5798 }
Phil Burk09bc4612016-02-24 15:58:15 -08005799
5800 // Modify formats based on surround preferences.
5801 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005802 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5803 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5804 // Remove surround sound related formats.
5805 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5806 audio_format_t format = formats[formatIndex];
5807 switch(format) {
5808 case AUDIO_FORMAT_AC3:
5809 case AUDIO_FORMAT_E_AC3:
5810 case AUDIO_FORMAT_DTS:
5811 case AUDIO_FORMAT_DTS_HD:
5812 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005813 formats.removeAt(formatIndex);
5814 break;
5815 default:
5816 formatIndex++; // keep it
5817 break;
5818 }
Phil Burk09bc4612016-02-24 15:58:15 -08005819 }
Phil Burk07ac1142016-03-25 13:39:29 -07005820 supportsAC3 = false;
5821 supportsOtherSurround = false;
5822 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005823 }
Phil Burk07ac1142016-03-25 13:39:29 -07005824 } else { // AUTO or ALWAYS
5825 // Most TVs support AC3 even if they do not report it in the EDID.
5826 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5827 && !supportsAC3) {
5828 formats.add(AUDIO_FORMAT_AC3);
5829 supportsAC3 = true;
5830 }
5831
5832 // If ALWAYS, add support for raw surround formats if all are missing.
5833 // This assumes that if any of these formats are reported by the HAL
5834 // then the report is valid and should not be modified.
5835 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5836 && !supportsOtherSurround) {
5837 formats.add(AUDIO_FORMAT_E_AC3);
5838 formats.add(AUDIO_FORMAT_DTS);
5839 formats.add(AUDIO_FORMAT_DTS_HD);
5840 supportsOtherSurround = true;
5841 }
5842
5843 // Add support for IEC61937 if any raw surround supported.
5844 // The HAL could do this but add it here, just in case.
5845 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5846 formats.add(AUDIO_FORMAT_IEC61937);
5847 supportsIEC61937 = true;
5848 }
Phil Burk09bc4612016-02-24 15:58:15 -08005849 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005850}
5851
5852// Modify the list of channel masks supported.
5853void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5854 ChannelsVector &channelMasks = *channelMasksPtr;
5855 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5856 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5857
5858 // If NEVER, then remove support for channelMasks > stereo.
5859 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5860 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5861 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5862 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5863 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5864 channelMasks.removeAt(maskIndex);
5865 } else {
5866 maskIndex++;
5867 }
5868 }
5869 // If ALWAYS, then make sure we at least support 5.1
5870 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5871 bool supports5dot1 = false;
5872 // Are there any channel masks that can be considered "surround"?
5873 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5874 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5875 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5876 supports5dot1 = true;
5877 break;
5878 }
5879 }
5880 // If not then add 5.1 support.
5881 if (!supports5dot1) {
5882 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5883 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5884 }
Phil Burk09bc4612016-02-24 15:58:15 -08005885 }
5886}
5887
Phil Burk00eeb322016-03-31 12:41:00 -07005888void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5889 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005890 AudioProfileVector &profiles)
5891{
5892 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005893
François Gaffie112b0af2015-11-19 16:13:25 +01005894 // Format MUST be checked first to update the list of AudioProfile
5895 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005896 reply = mpClientInterface->getParameters(
5897 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005898 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005899 AudioParameter repliedParameters(reply);
5900 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005901 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005902 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5903 return;
5904 }
Phil Burk09bc4612016-02-24 15:58:15 -08005905 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005906 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005907 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005908 }
Phil Burk09bc4612016-02-24 15:58:15 -08005909 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005910 }
5911 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5912
Eric Laurent20eb3a42016-01-26 18:39:17 -08005913 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005914 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005915 ChannelsVector channelMasks;
5916 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005917 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005918 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005919
5920 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005921 reply = mpClientInterface->getParameters(
5922 ioHandle,
5923 requestedParameters.toString() + ";" +
5924 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005925 ALOGV("%s: supported sampling rates %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::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005929 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005930 }
5931 }
5932 if (profiles.hasDynamicChannelsFor(format)) {
5933 reply = mpClientInterface->getParameters(ioHandle,
5934 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005935 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005936 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005937 AudioParameter repliedParameters(reply);
5938 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005939 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005940 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005941 if (device == AUDIO_DEVICE_OUT_HDMI) {
5942 filterSurroundChannelMasks(&channelMasks);
5943 }
François Gaffie112b0af2015-11-19 16:13:25 +01005944 }
5945 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005946 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005947 }
5948}
Eric Laurentd60560a2015-04-10 11:31:20 -07005949
Eric Laurente552edb2014-03-10 17:42:56 -07005950}; // namespace android