blob: edbff1b7fcdc4b458e4fb0aac12e653f6ca0d75d [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
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070036#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080037#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070038#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070039#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070040#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurentdc462862016-07-19 12:29:53 -070052//FIXME: workaround for truncated touch sounds
53// to be removed when the problem is handled by system UI
54#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070055// ----------------------------------------------------------------------------
56// AudioPolicyInterface implementation
57// ----------------------------------------------------------------------------
58
Eric Laurente0720872014-03-11 09:30:41 -070059status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080060 audio_policy_dev_state_t state,
61 const char *device_address,
62 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070063{
Paul McLeane743a472015-01-28 11:07:31 -080064 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080065}
66
François Gaffie44481e72016-04-20 07:49:57 +020067void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
68 audio_policy_dev_state_t state,
69 const String8 &device_address)
70{
71 AudioParameter param(device_address);
72 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070073 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020074 param.addInt(key, device);
75 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
76}
77
Eric Laurentc73ca6e2014-12-12 14:34:22 -080078status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080079 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080080 const char *device_address,
81 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080082{
Paul McLeane743a472015-01-28 11:07:31 -080083 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
84- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070085
86 // connect/disconnect only 1 device at a time
87 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
88
François Gaffie53615e22015-03-19 09:24:12 +010089 sp<DeviceDescriptor> devDesc =
90 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080091
Eric Laurente552edb2014-03-10 17:42:56 -070092 // handle output devices
93 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070094 SortedVector <audio_io_handle_t> outputs;
95
Eric Laurent3a4311c2014-03-17 12:00:47 -070096 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
97
Eric Laurente552edb2014-03-10 17:42:56 -070098 // save a copy of the opened output descriptors before any output is opened or closed
99 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
100 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700101 switch (state)
102 {
103 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800104 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700105 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700106 ALOGW("setDeviceConnectionState() device already connected: %x", device);
107 return INVALID_OPERATION;
108 }
109 ALOGV("setDeviceConnectionState() connecting device %x", device);
110
Eric Laurente552edb2014-03-10 17:42:56 -0700111 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 index = mAvailableOutputDevices.add(devDesc);
113 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100114 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700115 if (module == 0) {
116 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
117 device);
118 mAvailableOutputDevices.remove(devDesc);
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122 } else {
123 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 }
125
François Gaffie44481e72016-04-20 07:49:57 +0200126 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
127 // parameters on newly connected devices (instead of opening the outputs...)
128 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
129
Eric Laurenta1d525f2015-01-29 13:36:45 -0800130 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700131 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200132
133 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
134 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700135 return INVALID_OPERATION;
136 }
François Gaffie2110e042015-03-24 08:41:51 +0100137 // Propagate device availability to Engine
138 mEngine->setDeviceConnectionState(devDesc, state);
139
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700140 // outputs should never be empty here
141 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
142 "checkOutputsForDevice() returned no outputs but status OK");
143 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
144 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800145
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700148 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700150 ALOGW("setDeviceConnectionState() device not connected: %x", device);
151 return INVALID_OPERATION;
152 }
153
Paul McLean5c477aa2014-08-20 16:47:57 -0700154 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
155
Paul McLeane743a472015-01-28 11:07:31 -0800156 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200157 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700158
Eric Laurente552edb2014-03-10 17:42:56 -0700159 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700160 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100163
164 // Propagate device availability to Engine
165 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700166 } break;
167
168 default:
169 ALOGE("setDeviceConnectionState() invalid state: %x", state);
170 return BAD_VALUE;
171 }
172
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
174 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700175 checkA2dpSuspend();
176 checkOutputForAllStrategies();
177 // outputs must be closed after checkOutputForAllStrategies() is executed
178 if (!outputs.isEmpty()) {
179 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // close unused outputs after device disconnection or direct outputs that have been
182 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700183 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700184 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
185 (desc->mDirectOpenCount == 0))) {
186 closeOutput(outputs[i]);
187 }
188 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189 // check again after closing A2DP output to reset mA2dpSuspended if needed
190 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700191 }
192
193 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700194 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700195 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
196 updateCallRouting(newDevice);
197 }
Eric Laurente552edb2014-03-10 17:42:56 -0700198 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
200 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
201 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 // do not force device change on duplicated output because if device is 0, it will
203 // also force a device 0 for the two outputs it is duplicated to which may override
204 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700205 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100206 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700207 // always force when disconnecting (a non-duplicated device)
208 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700209 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700210 }
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
Eric Laurentd60560a2015-04-10 11:31:20 -0700213 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
214 cleanUpForDevice(devDesc);
215 }
216
Eric Laurent72aa32f2014-05-30 18:51:48 -0700217 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700218 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700219 } // end if is output device
220
Eric Laurente552edb2014-03-10 17:42:56 -0700221 // handle input devices
222 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700223 SortedVector <audio_io_handle_t> inputs;
224
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700226 switch (state)
227 {
228 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700231 ALOGW("setDeviceConnectionState() device already connected: %d", device);
232 return INVALID_OPERATION;
233 }
François Gaffie53615e22015-03-19 09:24:12 +0100234 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700235 if (module == NULL) {
236 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
237 device);
238 return INVALID_OPERATION;
239 }
François Gaffie44481e72016-04-20 07:49:57 +0200240
241 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
242 // parameters on newly connected devices (instead of opening the inputs...)
243 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
244
Paul McLean9080a4c2015-06-18 08:24:02 -0700245 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200246 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
247 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700248 return INVALID_OPERATION;
249 }
250
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 index = mAvailableInputDevices.add(devDesc);
252 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800253 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 } else {
255 return NO_MEMORY;
256 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800257
François Gaffie2110e042015-03-24 08:41:51 +0100258 // Propagate device availability to Engine
259 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700260 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700261
262 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700263 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700265 ALOGW("setDeviceConnectionState() device not connected: %d", device);
266 return INVALID_OPERATION;
267 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700268
269 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
270
271 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200272 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700273
Paul McLean9080a4c2015-06-18 08:24:02 -0700274 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700276
François Gaffie2110e042015-03-24 08:41:51 +0100277 // Propagate device availability to Engine
278 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700279 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurentd4692962014-05-05 18:13:44 -0700286 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700287 // As the input device list can impact the output device selection, update
288 // getDeviceForStrategy() cache
289 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700290
Eric Laurent87ffa392015-05-22 10:32:38 -0700291 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700292 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
293 updateCallRouting(newDevice);
294 }
295
Eric Laurentd60560a2015-04-10 11:31:20 -0700296 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
297 cleanUpForDevice(devDesc);
298 }
299
Eric Laurentb52c1522014-05-20 11:27:36 -0700300 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700301 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 ALOGW("setDeviceConnectionState() invalid device: %x", device);
305 return BAD_VALUE;
306}
307
Eric Laurente0720872014-03-11 09:30:41 -0700308audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100309 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700310{
Eric Laurent634b7142016-04-20 13:48:02 -0700311 sp<DeviceDescriptor> devDesc =
312 mHwModules.getDeviceDescriptor(device, device_address, "",
313 (strlen(device_address) != 0)/*matchAddress*/);
314
315 if (devDesc == 0) {
316 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
317 device, device_address);
318 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
319 }
François Gaffie53615e22015-03-19 09:24:12 +0100320
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 DeviceVector *deviceVector;
322
Eric Laurente552edb2014-03-10 17:42:56 -0700323 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700325 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 deviceVector = &mAvailableInputDevices;
327 } else {
328 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
329 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700330 }
Eric Laurent634b7142016-04-20 13:48:02 -0700331
332 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
333 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800334}
335
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800336status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
337 const char *device_address,
338 const char *device_name)
339{
340 status_t status;
341
342 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
343 device, device_address, device_name);
344
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800345 // connect/disconnect only 1 device at a time
346 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
347
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800348 // Check if the device is currently connected
349 sp<DeviceDescriptor> devDesc =
350 mHwModules.getDeviceDescriptor(device, device_address, device_name);
351 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
352 if (index < 0) {
353 // Nothing to do: device is not connected
354 return NO_ERROR;
355 }
356
357 // Toggle the device state: UNAVAILABLE -> AVAILABLE
358 // This will force reading again the device configuration
359 status = setDeviceConnectionState(device,
360 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
361 device_address, device_name);
362 if (status != NO_ERROR) {
363 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
364 status);
365 return status;
366 }
367
368 status = setDeviceConnectionState(device,
369 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
370 device_address, device_name);
371 if (status != NO_ERROR) {
372 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
373 status);
374 return status;
375 }
376
377 return NO_ERROR;
378}
379
Eric Laurentdc462862016-07-19 12:29:53 -0700380uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700381{
382 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700383 status_t status;
384 audio_patch_handle_t afPatchHandle;
385 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700386 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700387
Andy Hunga76c7de2016-12-13 19:14:31 -0800388 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700389 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700390 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800391 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700392 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
393
394 // release existing RX patch if any
395 if (mCallRxPatch != 0) {
396 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
397 mCallRxPatch.clear();
398 }
399 // release TX patch if any
400 if (mCallTxPatch != 0) {
401 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
402 mCallTxPatch.clear();
403 }
404
405 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
406 // via setOutputDevice() on primary output.
407 // Otherwise, create two audio patches for TX and RX path.
408 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700409 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700410 // If the TX device is also on the primary HW module, setOutputDevice() will take care
411 // of it due to legacy implementation. If not, create a patch.
412 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
413 == AUDIO_DEVICE_NONE) {
414 createTxPatch = true;
415 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700416 } else { // create RX path audio patch
417 struct audio_patch patch;
418
419 patch.num_sources = 1;
420 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700421 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
422 ALOG_ASSERT(!deviceList.isEmpty(),
423 "updateCallRouting() selected device not in output device list");
424 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
425 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
426 ALOG_ASSERT(!deviceList.isEmpty(),
427 "updateCallRouting() no telephony RX device");
428 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
429
430 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
431 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
432
433 // request to reuse existing output stream if one is already opened to reach the RX device
434 SortedVector<audio_io_handle_t> outputs =
435 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700436 audio_io_handle_t output = selectOutput(outputs,
437 AUDIO_OUTPUT_FLAG_NONE,
438 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700439 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700440 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441 ALOG_ASSERT(!outputDesc->isDuplicated(),
442 "updateCallRouting() RX device output is duplicated");
443 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700444 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700445 patch.num_sources = 2;
446 }
447
448 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700449 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700450 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
451 status);
452 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100453 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454 mCallRxPatch->mAfPatchHandle = afPatchHandle;
455 mCallRxPatch->mUid = mUidCached;
456 }
457 createTxPatch = true;
458 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700459 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700461
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 patch.num_sources = 1;
463 patch.num_sinks = 1;
464 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
465 ALOG_ASSERT(!deviceList.isEmpty(),
466 "updateCallRouting() selected device not in input device list");
467 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
468 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
469 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
470 ALOG_ASSERT(!deviceList.isEmpty(),
471 "updateCallRouting() no telephony TX device");
472 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
473 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
474
475 SortedVector<audio_io_handle_t> outputs =
476 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700477 audio_io_handle_t output = selectOutput(outputs,
478 AUDIO_OUTPUT_FLAG_NONE,
479 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480 // request to reuse existing output stream if one is already opened to reach the TX
481 // path output device
482 if (output != AUDIO_IO_HANDLE_NONE) {
483 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
484 ALOG_ASSERT(!outputDesc->isDuplicated(),
485 "updateCallRouting() RX device output is duplicated");
486 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700487 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700488 patch.num_sources = 2;
489 }
490
Eric Laurentc0a889f2015-10-14 14:36:34 -0700491 // terminate active capture if on the same HW module as the call TX source device
492 // FIXME: would be better to refine to only inputs whose profile connects to the
493 // call TX device but this information is not in the audio patch and logic here must be
494 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800495 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
496 for (size_t i = 0; i < activeInputs.size(); i++) {
497 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
498 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
499 AudioSessionCollection activeSessions =
500 activeDesc->getAudioSessions(true /*activeOnly*/);
501 for (size_t j = 0; j < activeSessions.size(); j++) {
502 audio_session_t activeSession = activeSessions.keyAt(j);
503 stopInput(activeDesc->mIoHandle, activeSession);
504 releaseInput(activeDesc->mIoHandle, activeSession);
505 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700506 }
507 }
508
Eric Laurentc2730ba2014-07-20 15:47:07 -0700509 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700510 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700511 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
512 status);
513 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100514 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700515 mCallTxPatch->mAfPatchHandle = afPatchHandle;
516 mCallTxPatch->mUid = mUidCached;
517 }
518 }
Eric Laurentdc462862016-07-19 12:29:53 -0700519
520 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700521}
522
Eric Laurente0720872014-03-11 09:30:41 -0700523void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700524{
525 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100526 // store previous phone state for management of sonification strategy below
527 int oldState = mEngine->getPhoneState();
528
529 if (mEngine->setPhoneState(state) != NO_ERROR) {
530 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700531 return;
532 }
François Gaffie2110e042015-03-24 08:41:51 +0100533 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700534 // if leaving call state, handle special case of active streams
535 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700536 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700537 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800538 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700540 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800541
Eric Laurent63dea1d2015-07-02 17:10:28 -0700542 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800543 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700544 }
545
François Gaffie2110e042015-03-24 08:41:51 +0100546 /**
547 * Switching to or from incall state or switching between telephony and VoIP lead to force
548 * routing command.
549 */
550 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
551 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700552
553 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700554 checkA2dpSuspend();
555 checkOutputForAllStrategies();
556 updateDevicesAndOutputs();
557
Eric Laurente552edb2014-03-10 17:42:56 -0700558 int delayMs = 0;
559 if (isStateInCall(state)) {
560 nsecs_t sysTime = systemTime();
561 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700563 // mute media and sonification strategies and delay device switch by the largest
564 // latency of any output where either strategy is active.
565 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100566 if ((isStrategyActive(desc, STRATEGY_MEDIA,
567 SONIFICATION_HEADSET_MUSIC_DELAY,
568 sysTime) ||
569 isStrategyActive(desc, STRATEGY_SONIFICATION,
570 SONIFICATION_HEADSET_MUSIC_DELAY,
571 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 (delayMs < (int)desc->latency()*2)) {
573 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700574 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700575 setStrategyMute(STRATEGY_MEDIA, true, desc);
576 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700577 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700578 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
579 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700580 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
581 }
582 }
583
Eric Laurent87ffa392015-05-22 10:32:38 -0700584 if (hasPrimaryOutput()) {
585 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
586 // the device returned is not necessarily reachable via this output
587 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
588 // force routing command to audio hardware when ending call
589 // even if no device change is needed
590 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
591 rxDevice = mPrimaryOutput->device();
592 }
Eric Laurente552edb2014-03-10 17:42:56 -0700593
Eric Laurent87ffa392015-05-22 10:32:38 -0700594 if (state == AUDIO_MODE_IN_CALL) {
595 updateCallRouting(rxDevice, delayMs);
596 } else if (oldState == AUDIO_MODE_IN_CALL) {
597 if (mCallRxPatch != 0) {
598 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
599 mCallRxPatch.clear();
600 }
601 if (mCallTxPatch != 0) {
602 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
603 mCallTxPatch.clear();
604 }
605 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
606 } else {
607 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700608 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 }
Eric Laurente552edb2014-03-10 17:42:56 -0700610 // if entering in call state, handle special case of active streams
611 // pertaining to sonification strategy see handleIncallSonification()
612 if (isStateInCall(state)) {
613 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800614 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700615 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700616 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700617
618 // force reevaluating accessibility routing when call starts
619 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700620 }
621
622 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 if (state == AUDIO_MODE_RINGTONE &&
624 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700625 mLimitRingtoneVolume = true;
626 } else {
627 mLimitRingtoneVolume = false;
628 }
629}
630
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700631audio_mode_t AudioPolicyManager::getPhoneState() {
632 return mEngine->getPhoneState();
633}
634
Eric Laurente0720872014-03-11 09:30:41 -0700635void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700636 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700637{
François Gaffie2110e042015-03-24 08:41:51 +0100638 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700639
François Gaffie2110e042015-03-24 08:41:51 +0100640 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
641 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
642 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700643 }
François Gaffie2110e042015-03-24 08:41:51 +0100644 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
645 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
646 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700647
648 // check for device and output changes triggered by new force usage
649 checkA2dpSuspend();
650 checkOutputForAllStrategies();
651 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800652
Eric Laurentdc462862016-07-19 12:29:53 -0700653 //FIXME: workaround for truncated touch sounds
654 // to be removed when the problem is handled by system UI
655 uint32_t delayMs = 0;
656 uint32_t waitMs = 0;
657 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
658 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
659 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700660 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700661 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700662 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700663 }
Eric Laurente552edb2014-03-10 17:42:56 -0700664 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700665 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
666 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
667 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700668 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
669 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670 }
Eric Laurente552edb2014-03-10 17:42:56 -0700671 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700672 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700673 }
674 }
675
Eric Laurentfb66dd92016-01-28 18:32:03 -0800676 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
677 for (size_t i = 0; i < activeInputs.size(); i++) {
678 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
679 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700680 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800681 if (activeDesc->mProfile->getSupportedDevices().types() &
682 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
683 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700684 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800685 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688}
689
Eric Laurente0720872014-03-11 09:30:41 -0700690void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700691{
692 ALOGV("setSystemProperty() property %s, value %s", property, value);
693}
694
695// Find a direct output profile compatible with the parameters passed, even if the input flags do
696// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800697sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700698 audio_devices_t device,
699 uint32_t samplingRate,
700 audio_format_t format,
701 audio_channel_mask_t channelMask,
702 audio_output_flags_t flags)
703{
Eric Laurent861a6282015-05-18 15:40:16 -0700704 // only retain flags that will drive the direct output profile selection
705 // if explicitly requested
706 static const uint32_t kRelevantFlags =
707 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
708 flags =
709 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
710
711 sp<IOProfile> profile;
712
Eric Laurente552edb2014-03-10 17:42:56 -0700713 for (size_t i = 0; i < mHwModules.size(); i++) {
714 if (mHwModules[i]->mHandle == 0) {
715 continue;
716 }
717 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700718 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
719 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700720 samplingRate, NULL /*updatedSamplingRate*/,
721 format, NULL /*updatedFormat*/,
722 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700723 flags)) {
724 continue;
725 }
726 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100727 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700728 continue;
729 }
730 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100731 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700732 continue;
733 }
734 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100735 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700736 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700737 }
Eric Laurente552edb2014-03-10 17:42:56 -0700738 }
739 }
Eric Laurent861a6282015-05-18 15:40:16 -0700740 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700741}
742
Eric Laurente0720872014-03-11 09:30:41 -0700743audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100744 uint32_t samplingRate,
745 audio_format_t format,
746 audio_channel_mask_t channelMask,
747 audio_output_flags_t flags,
748 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700749{
Eric Laurent3b73df72014-03-11 09:06:29 -0700750 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700751 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
752 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
753 device, stream, samplingRate, format, channelMask, flags);
754
Kevin Rocard551061a2017-02-06 15:59:29 -0800755 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, uid_t{0} /*Invalid uid*/,
Eric Laurente83b55d2014-11-14 10:06:21 -0800756 stream, samplingRate,format, channelMask,
757 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700758}
759
Eric Laurente83b55d2014-11-14 10:06:21 -0800760status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
761 audio_io_handle_t *output,
762 audio_session_t session,
763 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700764 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800765 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800766 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700767 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800768 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700769{
Eric Laurente83b55d2014-11-14 10:06:21 -0800770 audio_attributes_t attributes;
771 if (attr != NULL) {
772 if (!isValidAttributes(attr)) {
773 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
774 attr->usage, attr->content_type, attr->flags,
775 attr->tags);
776 return BAD_VALUE;
777 }
778 attributes = *attr;
779 } else {
780 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
781 ALOGE("getOutputForAttr(): invalid stream type");
782 return BAD_VALUE;
783 }
784 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700785 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800786
787 // TODO: check for existing client for this port ID
788 if (*portId == AUDIO_PORT_HANDLE_NONE) {
789 *portId = AudioPort::getNextUniqueId();
790 }
791
Eric Laurentc75307b2015-03-17 15:29:32 -0700792 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800793 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100794 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800795 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100796 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800797 }
François Gaffie036e1e92015-03-19 10:16:24 +0100798 *stream = streamTypefromAttributesInt(&attributes);
799 *output = desc->mIoHandle;
800 ALOGV("getOutputForAttr() returns output %d", *output);
801 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800802 }
803 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
804 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
805 return BAD_VALUE;
806 }
807
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700808 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
809 " session %d selectedDeviceId %d",
810 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
811 session, selectedDeviceId);
812
813 *stream = streamTypefromAttributesInt(&attributes);
814
815 // Explicit routing?
816 sp<DeviceDescriptor> deviceDesc;
817 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
818 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
819 deviceDesc = mAvailableOutputDevices[i];
820 break;
821 }
822 }
823 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700824
Eric Laurente83b55d2014-11-14 10:06:21 -0800825 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700826 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700827
Eric Laurente83b55d2014-11-14 10:06:21 -0800828 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700829 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
830 }
831
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700832 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800833 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700834
Kevin Rocard551061a2017-02-06 15:59:29 -0800835 *output = getOutputForDevice(device, session, uid, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800836 config->sample_rate, config->format, config->channel_mask,
837 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800838 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700839 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800840 return INVALID_OPERATION;
841 }
Paul McLeanaa981192015-03-21 09:55:15 -0700842
Eric Laurente83b55d2014-11-14 10:06:21 -0800843 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700844}
845
846audio_io_handle_t AudioPolicyManager::getOutputForDevice(
847 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800848 audio_session_t session __unused,
Kevin Rocard551061a2017-02-06 15:59:29 -0800849 uid_t clientUid,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700850 audio_stream_type_t stream,
851 uint32_t samplingRate,
852 audio_format_t format,
853 audio_channel_mask_t channelMask,
854 audio_output_flags_t flags,
855 const audio_offload_info_t *offloadInfo)
856{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700857 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700858 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700859
Eric Laurente552edb2014-03-10 17:42:56 -0700860#ifdef AUDIO_POLICY_TEST
861 if (mCurOutput != 0) {
862 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
863 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
864
865 if (mTestOutputs[mCurOutput] == 0) {
866 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700867 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
868 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700869 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700870 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700871 outputDesc->mFlags =
872 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700873 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700874 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
875 config.sample_rate = mTestSamplingRate;
876 config.channel_mask = mTestChannels;
877 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700878 if (offloadInfo != NULL) {
879 config.offload_info = *offloadInfo;
880 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700881 status = mpClientInterface->openOutput(0,
882 &mTestOutputs[mCurOutput],
883 &config,
884 &outputDesc->mDevice,
885 String8(""),
886 &outputDesc->mLatency,
887 outputDesc->mFlags);
888 if (status == NO_ERROR) {
889 outputDesc->mSamplingRate = config.sample_rate;
890 outputDesc->mFormat = config.format;
891 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700892 AudioParameter outputCmd = AudioParameter();
893 outputCmd.addInt(String8("set_id"),mCurOutput);
894 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
895 addOutput(mTestOutputs[mCurOutput], outputDesc);
896 }
897 }
898 return mTestOutputs[mCurOutput];
899 }
900#endif //AUDIO_POLICY_TEST
901
902 // open a direct output if required by specified parameters
903 //force direct flag if offload flag is set: offloading implies a direct output stream
904 // and all common behaviors are driven by checking only the direct flag
905 // this should normally be set appropriately in the policy configuration file
906 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700907 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700908 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700909 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
910 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
911 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800912 // only allow deep buffering for music stream type
913 if (stream != AUDIO_STREAM_MUSIC) {
914 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700915 } else if (/* stream == AUDIO_STREAM_MUSIC && */
916 flags == AUDIO_OUTPUT_FLAG_NONE &&
917 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
918 // use DEEP_BUFFER as default output for music stream type
919 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800920 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700921 if (stream == AUDIO_STREAM_TTS) {
922 flags = AUDIO_OUTPUT_FLAG_TTS;
923 }
Eric Laurente552edb2014-03-10 17:42:56 -0700924
Eric Laurentb732cf52014-09-24 19:08:21 -0700925 sp<IOProfile> profile;
926
927 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700928 // and not explicitly requested
929 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800930 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700931 audio_channel_count_from_out_mask(channelMask) <= 2) {
932 goto non_direct_output;
933 }
934
Andy Hung2ddee192015-12-18 17:34:44 -0800935 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
936 // This prevents creating an offloaded track and tearing it down immediately after start
937 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700938 // FIXME: We should check the audio session here but we do not have it in this context.
939 // This may prevent offloading in rare situations where effects are left active by apps
940 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700941
Eric Laurente552edb2014-03-10 17:42:56 -0700942 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800943 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700944 profile = getProfileForDirectOutput(device,
945 samplingRate,
946 format,
947 channelMask,
948 (audio_output_flags_t)flags);
949 }
950
Eric Laurent1c333e22014-05-20 10:48:17 -0700951 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700952 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700953
954 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700955 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700956 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
957 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800958 // reuse direct output if currently open by the same client
959 // and configured with same parameters
Eric Laurente552edb2014-03-10 17:42:56 -0700960 if ((samplingRate == outputDesc->mSamplingRate) &&
Kevin Rocard551061a2017-02-06 15:59:29 -0800961 audio_formats_match(format, outputDesc->mFormat) &&
962 (channelMask == outputDesc->mChannelMask)) {
963 if (clientUid == outputDesc->mDirectClientUid) {
964 outputDesc->mDirectOpenCount++;
965 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
966 return mOutputs.keyAt(i);
967 } else {
968 ALOGV("getOutput() do not reuse direct output because current client (%ld) "
969 "is not the same as requesting client (%ld)",
970 (long)outputDesc->mDirectClientUid, (long)clientUid);
971 goto non_direct_output;
972 }
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
974 }
975 }
976 // close direct output if currently open and configured with different parameters
977 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700978 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
Eric Laurent861a6282015-05-18 15:40:16 -0700980
981 // if the selected profile is offloaded and no offload info was specified,
982 // create a default one
983 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100984 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700985 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
986 defaultOffloadInfo.sample_rate = samplingRate;
987 defaultOffloadInfo.channel_mask = channelMask;
988 defaultOffloadInfo.format = format;
989 defaultOffloadInfo.stream_type = stream;
990 defaultOffloadInfo.bit_rate = 0;
991 defaultOffloadInfo.duration_us = -1;
992 defaultOffloadInfo.has_video = true; // conservative
993 defaultOffloadInfo.is_streaming = true; // likely
994 offloadInfo = &defaultOffloadInfo;
995 }
996
Eric Laurentc75307b2015-03-17 15:29:32 -0700997 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700998 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700999 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -07001000 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001001 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1002 config.sample_rate = samplingRate;
1003 config.channel_mask = channelMask;
1004 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001005 if (offloadInfo != NULL) {
1006 config.offload_info = *offloadInfo;
1007 }
Eric Laurent322b4d22015-04-03 15:57:54 -07001008 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07001009 &output,
1010 &config,
1011 &outputDesc->mDevice,
1012 String8(""),
1013 &outputDesc->mLatency,
1014 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001015
1016 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001017 if (status != NO_ERROR ||
1018 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001019 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001020 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001021 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1022 "format %d %d, channelMask %04x %04x", output, samplingRate,
1023 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1024 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001025 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001026 mpClientInterface->closeOutput(output);
1027 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001028 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001029 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001030 goto non_direct_output;
1031 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001032 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001034 outputDesc->mSamplingRate = config.sample_rate;
1035 outputDesc->mChannelMask = config.channel_mask;
1036 outputDesc->mFormat = config.format;
1037 outputDesc->mRefCount[stream] = 0;
1038 outputDesc->mStopTime[stream] = 0;
1039 outputDesc->mDirectOpenCount = 1;
Kevin Rocard551061a2017-02-06 15:59:29 -08001040 outputDesc->mDirectClientUid = clientUid;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001041
Eric Laurente552edb2014-03-10 17:42:56 -07001042 audio_io_handle_t srcOutput = getOutputForEffect();
1043 addOutput(output, outputDesc);
1044 audio_io_handle_t dstOutput = getOutputForEffect();
1045 if (dstOutput == output) {
1046 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1047 }
1048 mPreviousOutputs = mOutputs;
1049 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001050 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001051 return output;
1052 }
1053
Eric Laurentb732cf52014-09-24 19:08:21 -07001054non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001055
1056 // A request for HW A/V sync cannot fallback to a mixed output because time
1057 // stamps are embedded in audio data
1058 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1059 return AUDIO_IO_HANDLE_NONE;
1060 }
1061
Eric Laurente552edb2014-03-10 17:42:56 -07001062 // ignoring channel mask due to downmix capability in mixer
1063
1064 // open a non direct output
1065
1066 // for non direct outputs, only PCM is supported
1067 if (audio_is_linear_pcm(format)) {
1068 // get which output is suitable for the specified stream. The actual
1069 // routing change will happen when startOutput() will be called
1070 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1071
Eric Laurent8838a382014-09-08 16:44:28 -07001072 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1073 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1074 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001075 }
1076 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1077 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1078
Paul McLeanaa981192015-03-21 09:55:15 -07001079 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001080
1081 return output;
1082}
1083
Eric Laurente0720872014-03-11 09:30:41 -07001084audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001085 audio_output_flags_t flags,
1086 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001087{
1088 // select one output among several that provide a path to a particular device or set of
1089 // devices (the list was previously build by getOutputsForDevice()).
1090 // The priority is as follows:
1091 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001092 // 2: the output with the bit depth the closest to the requested one
1093 // 3: the primary output
1094 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001095
1096 if (outputs.size() == 0) {
1097 return 0;
1098 }
1099 if (outputs.size() == 1) {
1100 return outputs[0];
1101 }
1102
1103 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001104 audio_io_handle_t outputForFlags = 0;
1105 audio_io_handle_t outputForPrimary = 0;
1106 audio_io_handle_t outputForFormat = 0;
1107 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1108 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001109
1110 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001111 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001112 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001113 // if a valid format is specified, skip output if not compatible
1114 if (format != AUDIO_FORMAT_INVALID) {
1115 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001116 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001117 continue;
1118 }
1119 } else if (!audio_is_linear_pcm(format)) {
1120 continue;
1121 }
Eric Laurente6930022016-02-11 10:20:40 -08001122 if (AudioPort::isBetterFormatMatch(
1123 outputDesc->mFormat, bestFormat, format)) {
1124 outputForFormat = outputs[i];
1125 bestFormat = outputDesc->mFormat;
1126 }
Eric Laurent8838a382014-09-08 16:44:28 -07001127 }
1128
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001129 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001130 if (commonFlags >= maxCommonFlags) {
1131 if (commonFlags == maxCommonFlags) {
1132 if (AudioPort::isBetterFormatMatch(
1133 outputDesc->mFormat, bestFormatForFlags, format)) {
1134 outputForFlags = outputs[i];
1135 bestFormatForFlags = outputDesc->mFormat;
1136 }
1137 } else {
1138 outputForFlags = outputs[i];
1139 maxCommonFlags = commonFlags;
1140 bestFormatForFlags = outputDesc->mFormat;
1141 }
Eric Laurente552edb2014-03-10 17:42:56 -07001142 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1143 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001144 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001145 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001146 }
1147 }
1148 }
1149
Eric Laurente6930022016-02-11 10:20:40 -08001150 if (outputForFlags != 0) {
1151 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001152 }
Eric Laurente6930022016-02-11 10:20:40 -08001153 if (outputForFormat != 0) {
1154 return outputForFormat;
1155 }
1156 if (outputForPrimary != 0) {
1157 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001158 }
1159
1160 return outputs[0];
1161}
1162
Eric Laurente0720872014-03-11 09:30:41 -07001163status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001164 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001165 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001166{
Paul McLeanaa981192015-03-21 09:55:15 -07001167 ALOGV("startOutput() output %d, stream %d, session %d",
1168 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001169 ssize_t index = mOutputs.indexOfKey(output);
1170 if (index < 0) {
1171 ALOGW("startOutput() unknown output %d", output);
1172 return BAD_VALUE;
1173 }
1174
Eric Laurentc75307b2015-03-17 15:29:32 -07001175 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1176
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001177 // Routing?
1178 mOutputRoutes.incRouteActivity(session);
1179
Eric Laurentc75307b2015-03-17 15:29:32 -07001180 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001181 AudioMix *policyMix = NULL;
1182 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001183 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001184 policyMix = outputDesc->mPolicyMix;
1185 address = policyMix->mDeviceAddress.string();
1186 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1187 newDevice = policyMix->mDeviceType;
1188 } else {
1189 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1190 }
Eric Laurent493404d2015-04-21 15:07:36 -07001191 } else if (mOutputRoutes.hasRouteChanged(session)) {
1192 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001193 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001194 } else {
1195 newDevice = AUDIO_DEVICE_NONE;
1196 }
1197
1198 uint32_t delayMs = 0;
1199
Eric Laurentc40d9692016-04-13 19:14:13 -07001200 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001201
1202 if (status != NO_ERROR) {
1203 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001204 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001205 }
1206 // Automatically enable the remote submix input when output is started on a re routing mix
1207 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001208 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1209 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001210 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1211 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001212 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001213 "remote-submix");
1214 }
1215
1216 if (delayMs != 0) {
1217 usleep(delayMs * 1000);
1218 }
1219
1220 return status;
1221}
1222
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001223status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001224 audio_stream_type_t stream,
1225 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001226 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001227 uint32_t *delayMs)
1228{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001229 // cannot start playback of STREAM_TTS if any other output is being used
1230 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001231
1232 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001233 if (stream == AUDIO_STREAM_TTS) {
1234 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001235 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001236 return INVALID_OPERATION;
1237 } else {
1238 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1239 }
1240 } else {
1241 // some playback other than beacon starts
1242 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1243 }
1244
Eric Laurent77305a62016-07-25 16:39:22 -07001245 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001246 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001247 bool force = !outputDesc->isActive() &&
1248 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001249
Eric Laurente552edb2014-03-10 17:42:56 -07001250 // increment usage count for this stream on the requested output:
1251 // NOTE that the usage count is the same for duplicated output and hardware output which is
1252 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1253 outputDesc->changeRefCount(stream, 1);
1254
Eric Laurent493404d2015-04-21 15:07:36 -07001255 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001256 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001257 if (device == AUDIO_DEVICE_NONE) {
1258 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001259 }
Eric Laurente552edb2014-03-10 17:42:56 -07001260 routing_strategy strategy = getStrategy(stream);
1261 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001262 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1263 (beaconMuteLatency > 0);
1264 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001265 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001266 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001267 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001268 // force a device change if any other output is:
1269 // - managed by the same hw module
1270 // - has a current device selection that differs from selected device.
1271 // - supports currently selected device
1272 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001273 // In this case, the audio HAL must receive the new device selection so that it can
1274 // change the device currently selected by the other active output.
1275 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001276 desc->device() != device &&
1277 desc->supportedDevices() & device &&
1278 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001279 force = true;
1280 }
1281 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001282 // a notification so that audio focus effect can propagate, or that a mute/unmute
1283 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001284 uint32_t latency = desc->latency();
1285 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1286 waitMs = latency;
1287 }
1288 }
1289 }
Eric Laurentdc462862016-07-19 12:29:53 -07001290 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001291
1292 // handle special case for sonification while in call
1293 if (isInCall()) {
1294 handleIncallSonification(stream, true, false);
1295 }
1296
1297 // apply volume rules for current stream and device if necessary
1298 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001299 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001300 outputDesc,
1301 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001302
1303 // update the outputs if starting an output with a stream that can affect notification
1304 // routing
1305 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001306
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001307 // force reevaluating accessibility routing when ringtone or alarm starts
1308 if (strategy == STRATEGY_SONIFICATION) {
1309 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1310 }
Eric Laurentdc462862016-07-19 12:29:53 -07001311
1312 if (waitMs > muteWaitMs) {
1313 *delayMs = waitMs - muteWaitMs;
1314 }
Eric Laurente552edb2014-03-10 17:42:56 -07001315 }
Eric Laurentdc462862016-07-19 12:29:53 -07001316
Eric Laurente552edb2014-03-10 17:42:56 -07001317 return NO_ERROR;
1318}
1319
1320
Eric Laurente0720872014-03-11 09:30:41 -07001321status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001322 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001323 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001324{
1325 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1326 ssize_t index = mOutputs.indexOfKey(output);
1327 if (index < 0) {
1328 ALOGW("stopOutput() unknown output %d", output);
1329 return BAD_VALUE;
1330 }
1331
Eric Laurentc75307b2015-03-17 15:29:32 -07001332 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001333
Eric Laurentc75307b2015-03-17 15:29:32 -07001334 if (outputDesc->mRefCount[stream] == 1) {
1335 // Automatically disable the remote submix input when output is stopped on a
1336 // re routing mix of type MIX_TYPE_RECORDERS
1337 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1338 outputDesc->mPolicyMix != NULL &&
1339 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1340 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1341 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001342 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001343 "remote-submix");
1344 }
1345 }
1346
1347 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001348 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001349 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001350 int activityCount = mOutputRoutes.decRouteActivity(session);
1351 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1352
1353 if (forceDeviceUpdate) {
1354 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1355 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001356 }
1357
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001358 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001359}
1360
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001361status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001362 audio_stream_type_t stream,
1363 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001364{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001365 // always handle stream stop, check which stream type is stopping
1366 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1367
Eric Laurente552edb2014-03-10 17:42:56 -07001368 // handle special case for sonification while in call
1369 if (isInCall()) {
1370 handleIncallSonification(stream, false, false);
1371 }
1372
1373 if (outputDesc->mRefCount[stream] > 0) {
1374 // decrement usage count of this stream on the output
1375 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001376
Eric Laurente552edb2014-03-10 17:42:56 -07001377 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001378 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001379 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001380 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001381 // delay the device switch by twice the latency because stopOutput() is executed when
1382 // the track stop() command is received and at that time the audio track buffer can
1383 // still contain data that needs to be drained. The latency only covers the audio HAL
1384 // and kernel buffers. Also the latency does not always include additional delay in the
1385 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001386 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001387
1388 // force restoring the device selection on other active outputs if it differs from the
1389 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001390 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001391 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001392 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001393 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001394 desc->isActive() &&
1395 outputDesc->sharesHwModuleWith(desc) &&
1396 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001397 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1398 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001399 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001400 newDevice2,
1401 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001402 delayMs);
1403 // re-apply device specific volume if not done by setOutputDevice()
1404 if (!force) {
1405 applyStreamVolumes(desc, newDevice2, delayMs);
1406 }
Eric Laurente552edb2014-03-10 17:42:56 -07001407 }
1408 }
1409 // update the outputs if stopping one with a stream that can affect notification routing
1410 handleNotificationRoutingForStream(stream);
1411 }
1412 return NO_ERROR;
1413 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001414 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001415 return INVALID_OPERATION;
1416 }
1417}
1418
Eric Laurente83b55d2014-11-14 10:06:21 -08001419void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001420 audio_stream_type_t stream __unused,
1421 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001422{
1423 ALOGV("releaseOutput() %d", output);
1424 ssize_t index = mOutputs.indexOfKey(output);
1425 if (index < 0) {
1426 ALOGW("releaseOutput() releasing unknown output %d", output);
1427 return;
1428 }
1429
1430#ifdef AUDIO_POLICY_TEST
1431 int testIndex = testOutputIndex(output);
1432 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001434 if (outputDesc->isActive()) {
1435 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001436 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001437 mTestOutputs[testIndex] = 0;
1438 }
1439 return;
1440 }
1441#endif //AUDIO_POLICY_TEST
1442
Paul McLeanaa981192015-03-21 09:55:15 -07001443 // Routing
1444 mOutputRoutes.removeRoute(session);
1445
Eric Laurentc75307b2015-03-17 15:29:32 -07001446 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001447 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001448 if (desc->mDirectOpenCount <= 0) {
1449 ALOGW("releaseOutput() invalid open count %d for output %d",
1450 desc->mDirectOpenCount, output);
1451 return;
1452 }
1453 if (--desc->mDirectOpenCount == 0) {
1454 closeOutput(output);
1455 // If effects where present on the output, audioflinger moved them to the primary
1456 // output by default: move them back to the appropriate output.
1457 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001458 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001459 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1460 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001461 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001462 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001463 }
1464 }
1465}
1466
1467
Eric Laurentcaf7f482014-11-25 17:50:47 -08001468status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1469 audio_io_handle_t *input,
1470 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001471 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001472 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001473 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001474 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001475 input_type_t *inputType,
1476 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001477{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001478 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1479 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001480 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001481
Eric Laurentcaf7f482014-11-25 17:50:47 -08001482 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001483 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001484
Eric Laurent275e8e92014-11-30 15:14:47 -08001485 audio_devices_t device;
1486 // handle legacy remote submix case where the address was not always specified
1487 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001488 audio_source_t inputSource = attr->source;
1489 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001490 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001491
Eric Laurentc447ded2015-01-06 08:47:05 -08001492 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1493 inputSource = AUDIO_SOURCE_MIC;
1494 }
1495 halInputSource = inputSource;
1496
Eric Laurent20b9ef02016-12-05 11:03:16 -08001497 // TODO: check for existing client for this port ID
1498 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1499 *portId = AudioPort::getNextUniqueId();
1500 }
1501
Paul McLean466dc8e2015-04-17 13:15:36 -06001502 // Explicit routing?
1503 sp<DeviceDescriptor> deviceDesc;
1504 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1505 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1506 deviceDesc = mAvailableInputDevices[i];
1507 break;
1508 }
1509 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001510 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001511
Eric Laurentc447ded2015-01-06 08:47:05 -08001512 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001513 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001514 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001515 if (ret != NO_ERROR) {
1516 return ret;
1517 }
1518 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001519 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1520 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001521 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001522 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001523 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001524 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001525 return BAD_VALUE;
1526 }
Eric Laurentc722f302014-12-10 11:21:49 -08001527 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001528 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001529 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1530 // there is an external policy, but this input is attached to a mix of recorders,
1531 // meaning it receives audio injected into the framework, so the recorder doesn't
1532 // know about it and is therefore considered "legacy"
1533 *inputType = API_INPUT_LEGACY;
1534 } else {
1535 // recording a mix of players defined by an external policy, we're rerouting for
1536 // an external policy
1537 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1538 }
Eric Laurentc722f302014-12-10 11:21:49 -08001539 } else if (audio_is_remote_submix_device(device)) {
1540 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001541 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001542 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1543 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001544 } else {
1545 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001546 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001547
Eric Laurent599c7582015-12-07 18:05:55 -08001548 }
1549
1550 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001551 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001552 policyMix);
1553 if (*input == AUDIO_IO_HANDLE_NONE) {
1554 mInputRoutes.removeRoute(session);
1555 return INVALID_OPERATION;
1556 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001557
Eric Laurent599c7582015-12-07 18:05:55 -08001558 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1559 return NO_ERROR;
1560}
1561
1562
1563audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1564 String8 address,
1565 audio_session_t session,
1566 uid_t uid,
1567 audio_source_t inputSource,
1568 uint32_t samplingRate,
1569 audio_format_t format,
1570 audio_channel_mask_t channelMask,
1571 audio_input_flags_t flags,
1572 AudioMix *policyMix)
1573{
1574 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1575 audio_source_t halInputSource = inputSource;
1576 bool isSoundTrigger = false;
1577
1578 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1579 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1580 if (index >= 0) {
1581 input = mSoundTriggerSessions.valueFor(session);
1582 isSoundTrigger = true;
1583 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1584 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1585 } else {
1586 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001587 }
1588 }
1589
Andy Hungf129b032015-04-07 13:45:50 -07001590 // find a compatible input profile (not necessarily identical in parameters)
1591 sp<IOProfile> profile;
1592 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001593 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001594 audio_format_t profileFormat = format;
1595 audio_channel_mask_t profileChannelMask = channelMask;
1596 audio_input_flags_t profileFlags = flags;
1597 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001598 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001599 profileSamplingRate, profileFormat, profileChannelMask,
1600 profileFlags);
1601 if (profile != 0) {
1602 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001603 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1604 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001605 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1606 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1607 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001608 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1609 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001610 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001611 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001612 }
Eric Laurente552edb2014-03-10 17:42:56 -07001613 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001614 // Pick input sampling rate if not specified by client
1615 if (samplingRate == 0) {
1616 samplingRate = profileSamplingRate;
1617 }
Eric Laurente552edb2014-03-10 17:42:56 -07001618
Eric Laurent322b4d22015-04-03 15:57:54 -07001619 if (profile->getModuleHandle() == 0) {
1620 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001621 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001622 }
1623
Eric Laurent599c7582015-12-07 18:05:55 -08001624 sp<AudioSession> audioSession = new AudioSession(session,
1625 inputSource,
1626 format,
1627 samplingRate,
1628 channelMask,
1629 flags,
1630 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001631 isSoundTrigger,
1632 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001633
Eric Laurent599c7582015-12-07 18:05:55 -08001634 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001635 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001636 for (size_t i = 0; i < mInputs.size(); i++) {
1637 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001638 // reuse input if:
1639 // - it shares the same profile
1640 // AND
1641 // - it is not a reroute submix input
1642 // AND
1643 // - it is: not used for sound trigger
1644 // OR
1645 // used for sound trigger and all clients use the same session ID
1646 //
1647 if ((profile == desc->mProfile) &&
1648 (isSoundTrigger == desc->isSoundTrigger()) &&
1649 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001650
1651 sp<AudioSession> as = desc->getAudioSession(session);
1652 if (as != 0) {
1653 // do not allow unmatching properties on same session
1654 if (as->matches(audioSession)) {
1655 as->changeOpenCount(1);
1656 } else {
1657 ALOGW("getInputForDevice() record with different attributes"
1658 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001659 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001660 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001661 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001662 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001663 }
Eric Laurentbb948092017-01-23 18:33:30 -08001664
Eric Laurent555530a2017-02-07 18:17:24 -08001665 // Reuse the already opened input stream on this profile if:
1666 // - the new capture source is background OR
1667 // - the path requested configurations match OR
1668 // - the new source priority is less than the highest source priority on this input
1669 // If the input stream cannot be reused, close it before opening a new stream
1670 // on the same profile for the new client so that the requested path configuration
1671 // can be selected.
1672 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001673 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001674 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001675 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001676 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001677 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001678 reusedInputDesc = desc;
1679 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001680 } else {
1681 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001682 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1683 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001684 }
Eric Laurent599c7582015-12-07 18:05:55 -08001685 }
1686 }
Eric Laurent599c7582015-12-07 18:05:55 -08001687
Eric Laurent555530a2017-02-07 18:17:24 -08001688 if (reusedInputDesc != 0) {
1689 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1690 for (size_t j = 0; j < sessions.size(); j++) {
1691 audio_session_t currentSession = sessions.keyAt(j);
1692 stopInput(reusedInputDesc->mIoHandle, currentSession);
1693 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1694 }
1695 }
1696
Eric Laurentcf2c0212014-07-25 16:20:43 -07001697 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001698 config.sample_rate = profileSamplingRate;
1699 config.channel_mask = profileChannelMask;
1700 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001701
Eric Laurent322b4d22015-04-03 15:57:54 -07001702 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001703 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001704 &config,
1705 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001706 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001707 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001708 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001709
1710 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001711 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001712 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001713 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001714 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001715 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1716 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001717 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001718 if (input != AUDIO_IO_HANDLE_NONE) {
1719 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001720 }
Eric Laurent599c7582015-12-07 18:05:55 -08001721 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001722 }
1723
Eric Laurent1f2f2232014-06-02 12:01:23 -07001724 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001725 inputDesc->mSamplingRate = profileSamplingRate;
1726 inputDesc->mFormat = profileFormat;
1727 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001728 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001729 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001730 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001731
Eric Laurent599c7582015-12-07 18:05:55 -08001732 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001733 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001734
Eric Laurent599c7582015-12-07 18:05:55 -08001735 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001736}
1737
Eric Laurentbb948092017-01-23 18:33:30 -08001738//static
1739bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1740{
1741 return (source == AUDIO_SOURCE_HOTWORD) ||
1742 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1743 (source == AUDIO_SOURCE_FM_TUNER);
1744}
1745
Eric Laurentfb66dd92016-01-28 18:32:03 -08001746bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1747 const sp<AudioSession>& audioSession)
1748{
1749 // Do not allow capture if an active voice call is using a software patch and
1750 // the call TX source device is on the same HW module.
1751 // FIXME: would be better to refine to only inputs whose profile connects to the
1752 // call TX device but this information is not in the audio patch
1753 if (mCallTxPatch != 0 &&
1754 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1755 return false;
1756 }
1757
1758 // starting concurrent capture is enabled if:
1759 // 1) capturing for re-routing
1760 // 2) capturing for HOTWORD source
1761 // 3) capturing for FM TUNER source
1762 // 3) All other active captures are either for re-routing or HOTWORD
1763
1764 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001765 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001766 return true;
1767 }
1768
1769 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1770 for (size_t i = 0; i < activeInputs.size(); i++) {
1771 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001772 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001773 !is_virtual_input_device(activeInput->mDevice)) {
1774 return false;
1775 }
1776 }
1777
1778 return true;
1779}
1780
1781
Eric Laurent4dc68062014-07-28 17:26:49 -07001782status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001783 audio_session_t session,
1784 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001785{
1786 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001787 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001788 ssize_t index = mInputs.indexOfKey(input);
1789 if (index < 0) {
1790 ALOGW("startInput() unknown input %d", input);
1791 return BAD_VALUE;
1792 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001793 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001794
Eric Laurent599c7582015-12-07 18:05:55 -08001795 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1796 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001797 ALOGW("startInput() unknown session %d on input %d", session, input);
1798 return BAD_VALUE;
1799 }
1800
Eric Laurentfb66dd92016-01-28 18:32:03 -08001801 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1802 ALOGW("startInput(%d) failed: other input already started", input);
1803 return INVALID_OPERATION;
1804 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001805
Eric Laurentfb66dd92016-01-28 18:32:03 -08001806 if (isInCall()) {
1807 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1808 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001809 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001810 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001811 }
1812
Eric Laurent313d1e72016-01-29 09:56:57 -08001813 // increment activity count before calling getNewInputDevice() below as only active sessions
1814 // are considered for device selection
1815 audioSession->changeActiveCount(1);
1816
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001817 // Routing?
1818 mInputRoutes.incRouteActivity(session);
1819
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001820 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001821 // indicate active capture to sound trigger service if starting capture from a mic on
1822 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001823 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001824 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001825
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001826 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1827 // if input maps to a dynamic policy with an activity listener, notify of state change
1828 if ((inputDesc->mPolicyMix != NULL)
1829 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1830 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1831 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001832 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001833
Eric Laurentf7c50102016-09-30 15:19:43 -07001834 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1835 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001836 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001837 SoundTrigger::setCaptureState(true);
1838 }
1839
1840 // automatically enable the remote submix output when input is started if not
1841 // used by a policy mix of type MIX_TYPE_RECORDERS
1842 // For remote submix (a virtual device), we open only one input per capture request.
1843 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1844 String8 address = String8("");
1845 if (inputDesc->mPolicyMix == NULL) {
1846 address = String8("0");
1847 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1848 address = inputDesc->mPolicyMix->mDeviceAddress;
1849 }
1850 if (address != "") {
1851 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1852 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1853 address, "remote-submix");
1854 }
Eric Laurentc722f302014-12-10 11:21:49 -08001855 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001856 }
Eric Laurente552edb2014-03-10 17:42:56 -07001857 }
1858
Eric Laurent599c7582015-12-07 18:05:55 -08001859 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001860
Eric Laurente552edb2014-03-10 17:42:56 -07001861 return NO_ERROR;
1862}
1863
Eric Laurent4dc68062014-07-28 17:26:49 -07001864status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1865 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001866{
1867 ALOGV("stopInput() input %d", input);
1868 ssize_t index = mInputs.indexOfKey(input);
1869 if (index < 0) {
1870 ALOGW("stopInput() unknown input %d", input);
1871 return BAD_VALUE;
1872 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001873 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001874
Eric Laurent599c7582015-12-07 18:05:55 -08001875 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001876 if (index < 0) {
1877 ALOGW("stopInput() unknown session %d on input %d", session, input);
1878 return BAD_VALUE;
1879 }
1880
Eric Laurent599c7582015-12-07 18:05:55 -08001881 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001882 ALOGW("stopInput() input %d already stopped", input);
1883 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001884 }
1885
Eric Laurent599c7582015-12-07 18:05:55 -08001886 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001887
1888 // Routing?
1889 mInputRoutes.decRouteActivity(session);
1890
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001891 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001892
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001893 if (inputDesc->isActive()) {
1894 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1895 } else {
1896 // if input maps to a dynamic policy with an activity listener, notify of state change
1897 if ((inputDesc->mPolicyMix != NULL)
1898 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1899 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1900 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001901 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001902
1903 // automatically disable the remote submix output when input is stopped if not
1904 // used by a policy mix of type MIX_TYPE_RECORDERS
1905 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1906 String8 address = String8("");
1907 if (inputDesc->mPolicyMix == NULL) {
1908 address = String8("0");
1909 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1910 address = inputDesc->mPolicyMix->mDeviceAddress;
1911 }
1912 if (address != "") {
1913 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1914 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1915 address, "remote-submix");
1916 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001917 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001918
Eric Laurentf7c50102016-09-30 15:19:43 -07001919 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001920 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001921
Eric Laurentf7c50102016-09-30 15:19:43 -07001922 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1923 // primary HW module
1924 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1925 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1926 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001927 SoundTrigger::setCaptureState(false);
1928 }
1929 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001930 }
Eric Laurente552edb2014-03-10 17:42:56 -07001931 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001932 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001933}
1934
Eric Laurent4dc68062014-07-28 17:26:49 -07001935void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1936 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001937{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001938
Eric Laurente552edb2014-03-10 17:42:56 -07001939 ALOGV("releaseInput() %d", input);
1940 ssize_t index = mInputs.indexOfKey(input);
1941 if (index < 0) {
1942 ALOGW("releaseInput() releasing unknown input %d", input);
1943 return;
1944 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001945
1946 // Routing
1947 mInputRoutes.removeRoute(session);
1948
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001949 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1950 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001951
Eric Laurent599c7582015-12-07 18:05:55 -08001952 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08001953 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001954 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1955 return;
1956 }
Eric Laurent599c7582015-12-07 18:05:55 -08001957
1958 if (audioSession->openCount() == 0) {
1959 ALOGW("releaseInput() invalid open count %d on session %d",
1960 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001961 return;
1962 }
Eric Laurent599c7582015-12-07 18:05:55 -08001963
1964 if (audioSession->changeOpenCount(-1) == 0) {
1965 inputDesc->removeAudioSession(session);
1966 }
1967
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001968 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001969 ALOGV("releaseInput() exit > 0");
1970 return;
1971 }
1972
Eric Laurent05b90f82014-08-27 15:32:29 -07001973 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001974 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001975 ALOGV("releaseInput() exit");
1976}
1977
Eric Laurentd4692962014-05-05 18:13:44 -07001978void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001979 bool patchRemoved = false;
1980
Eric Laurentd4692962014-05-05 18:13:44 -07001981 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001982 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001983 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001984 if (patch_index >= 0) {
1985 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001986 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001987 mAudioPatches.removeItemsAt(patch_index);
1988 patchRemoved = true;
1989 }
Eric Laurentd4692962014-05-05 18:13:44 -07001990 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1991 }
1992 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001993 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001994 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001995
1996 if (patchRemoved) {
1997 mpClientInterface->onAudioPatchListUpdate();
1998 }
Eric Laurentd4692962014-05-05 18:13:44 -07001999}
2000
Eric Laurente0720872014-03-11 09:30:41 -07002001void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002002 int indexMin,
2003 int indexMax)
2004{
2005 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002006 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002007
2008 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002009 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2010 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002011 continue;
2012 }
2013 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002014 }
Eric Laurente552edb2014-03-10 17:42:56 -07002015}
2016
Eric Laurente0720872014-03-11 09:30:41 -07002017status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002018 int index,
2019 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002020{
2021
François Gaffied1ab2bd2015-12-02 18:20:06 +01002022 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2023 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002024 return BAD_VALUE;
2025 }
2026 if (!audio_is_output_device(device)) {
2027 return BAD_VALUE;
2028 }
2029
2030 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002031 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002032
Eric Laurent1fd372e2016-04-06 14:23:53 -07002033 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002034 stream, device, index);
2035
Eric Laurent28d09f02016-03-08 10:43:05 -08002036 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002037 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2038 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002039 continue;
2040 }
2041 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2042 }
Eric Laurente552edb2014-03-10 17:42:56 -07002043
Eric Laurent1fd372e2016-04-06 14:23:53 -07002044 // update volume on all outputs and streams matching the following:
2045 // - The requested stream (or a stream matching for volume control) is active on the output
2046 // - The device (or devices) selected by the strategy corresponding to this stream includes
2047 // the requested device
2048 // - For non default requested device, currently selected device on the output is either the
2049 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002050 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2051 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002052 status_t status = NO_ERROR;
2053 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002054 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2055 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002056 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2057 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002058 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002059 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002060 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2061 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002062 continue;
2063 }
Eric Laurent794fde22016-03-11 09:50:45 -08002064 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002065 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
2066 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2067 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002068 continue;
2069 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002070 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002071 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002072 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002073 applyVolume = (curDevice & curStreamDevice) != 0;
2074 } else {
2075 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
2076 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07002077 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002078
Eric Laurente76f29c2016-09-14 17:17:53 -07002079 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002080 //FIXME: workaround for truncated touch sounds
2081 // delayed volume change for system stream to be removed when the problem is
2082 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002083 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002084 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2085 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002086 if (volStatus != NO_ERROR) {
2087 status = volStatus;
2088 }
2089 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002090 }
Eric Laurente552edb2014-03-10 17:42:56 -07002091 }
2092 return status;
2093}
2094
Eric Laurente0720872014-03-11 09:30:41 -07002095status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002096 int *index,
2097 audio_devices_t device)
2098{
2099 if (index == NULL) {
2100 return BAD_VALUE;
2101 }
2102 if (!audio_is_output_device(device)) {
2103 return BAD_VALUE;
2104 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002105 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002106 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002107 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002108 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2109 }
François Gaffiedfd74092015-03-19 12:10:59 +01002110 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002111
François Gaffied1ab2bd2015-12-02 18:20:06 +01002112 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002113 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2114 return NO_ERROR;
2115}
2116
Eric Laurente0720872014-03-11 09:30:41 -07002117audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002118 const SortedVector<audio_io_handle_t>& outputs)
2119{
2120 // select one output among several suitable for global effects.
2121 // The priority is as follows:
2122 // 1: An offloaded output. If the effect ends up not being offloadable,
2123 // AudioFlinger will invalidate the track and the offloaded output
2124 // will be closed causing the effect to be moved to a PCM output.
2125 // 2: A deep buffer output
2126 // 3: the first output in the list
2127
2128 if (outputs.size() == 0) {
2129 return 0;
2130 }
2131
2132 audio_io_handle_t outputOffloaded = 0;
2133 audio_io_handle_t outputDeepBuffer = 0;
2134
2135 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002136 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002137 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002138 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2139 outputOffloaded = outputs[i];
2140 }
2141 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2142 outputDeepBuffer = outputs[i];
2143 }
2144 }
2145
2146 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2147 outputOffloaded, outputDeepBuffer);
2148 if (outputOffloaded != 0) {
2149 return outputOffloaded;
2150 }
2151 if (outputDeepBuffer != 0) {
2152 return outputDeepBuffer;
2153 }
2154
2155 return outputs[0];
2156}
2157
Eric Laurente0720872014-03-11 09:30:41 -07002158audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002159{
2160 // apply simple rule where global effects are attached to the same output as MUSIC streams
2161
Eric Laurent3b73df72014-03-11 09:06:29 -07002162 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002163 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2164 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2165
2166 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2167 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2168 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2169
2170 return output;
2171}
2172
Eric Laurente0720872014-03-11 09:30:41 -07002173status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002174 audio_io_handle_t io,
2175 uint32_t strategy,
2176 int session,
2177 int id)
2178{
2179 ssize_t index = mOutputs.indexOfKey(io);
2180 if (index < 0) {
2181 index = mInputs.indexOfKey(io);
2182 if (index < 0) {
2183 ALOGW("registerEffect() unknown io %d", io);
2184 return INVALID_OPERATION;
2185 }
2186 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002187 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002188}
2189
Eric Laurentc75307b2015-03-17 15:29:32 -07002190bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2191{
Eric Laurent28d09f02016-03-08 10:43:05 -08002192 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002193 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2194 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002195 continue;
2196 }
2197 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2198 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002199 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002200}
2201
2202bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2203{
2204 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2205}
2206
Eric Laurente0720872014-03-11 09:30:41 -07002207bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002208{
2209 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002210 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002211 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002212 return true;
2213 }
2214 }
2215 return false;
2216}
2217
Eric Laurent275e8e92014-11-30 15:14:47 -08002218// Register a list of custom mixes with their attributes and format.
2219// When a mix is registered, corresponding input and output profiles are
2220// added to the remote submix hw module. The profile contains only the
2221// parameters (sampling rate, format...) specified by the mix.
2222// The corresponding input remote submix device is also connected.
2223//
2224// When a remote submix device is connected, the address is checked to select the
2225// appropriate profile and the corresponding input or output stream is opened.
2226//
2227// When capture starts, getInputForAttr() will:
2228// - 1 look for a mix matching the address passed in attribtutes tags if any
2229// - 2 if none found, getDeviceForInputSource() will:
2230// - 2.1 look for a mix matching the attributes source
2231// - 2.2 if none found, default to device selection by policy rules
2232// At this time, the corresponding output remote submix device is also connected
2233// and active playback use cases can be transferred to this mix if needed when reconnecting
2234// after AudioTracks are invalidated
2235//
2236// When playback starts, getOutputForAttr() will:
2237// - 1 look for a mix matching the address passed in attribtutes tags if any
2238// - 2 if none found, look for a mix matching the attributes usage
2239// - 3 if none found, default to device and output selection by policy rules.
2240
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002241status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002242{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002243 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2244 status_t res = NO_ERROR;
2245
2246 sp<HwModule> rSubmixModule;
2247 // examine each mix's route type
2248 for (size_t i = 0; i < mixes.size(); i++) {
2249 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2250 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2251 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002252 break;
2253 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002254 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2255 // Loop back through "remote submix"
2256 if (rSubmixModule == 0) {
2257 for (size_t j = 0; i < mHwModules.size(); j++) {
2258 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2259 && mHwModules[j]->mHandle != 0) {
2260 rSubmixModule = mHwModules[j];
2261 break;
2262 }
2263 }
2264 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002265
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002266 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002267
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002268 if (rSubmixModule == 0) {
2269 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2270 res = INVALID_OPERATION;
2271 break;
2272 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002273
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002274 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002275
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002276 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002277 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002278 res = INVALID_OPERATION;
2279 break;
2280 }
2281 audio_config_t outputConfig = mixes[i].mFormat;
2282 audio_config_t inputConfig = mixes[i].mFormat;
2283 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2284 // stereo and let audio flinger do the channel conversion if needed.
2285 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2286 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2287 rSubmixModule->addOutputProfile(address, &outputConfig,
2288 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2289 rSubmixModule->addInputProfile(address, &inputConfig,
2290 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002291
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002292 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2293 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2294 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2295 address.string(), "remote-submix");
2296 } else {
2297 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2298 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2299 address.string(), "remote-submix");
2300 }
2301 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002302 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002303 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002304 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2305 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002306
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002307 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002308 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2309 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2310 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2311 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2312 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2313 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002314 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2315 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002316 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2317 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002318 } else {
2319 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002320 }
2321 break;
2322 }
2323 }
2324
2325 if (res != NO_ERROR) {
2326 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002327 i, device, address.string());
2328 res = INVALID_OPERATION;
2329 break;
2330 } else if (!foundOutput) {
2331 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2332 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002333 res = INVALID_OPERATION;
2334 break;
2335 }
Eric Laurentc722f302014-12-10 11:21:49 -08002336 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002337 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002338 if (res != NO_ERROR) {
2339 unregisterPolicyMixes(mixes);
2340 }
2341 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002342}
2343
2344status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2345{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002346 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002347 status_t res = NO_ERROR;
2348 sp<HwModule> rSubmixModule;
2349 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002350 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002351 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002352
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002353 if (rSubmixModule == 0) {
2354 for (size_t j = 0; i < mHwModules.size(); j++) {
2355 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2356 && mHwModules[j]->mHandle != 0) {
2357 rSubmixModule = mHwModules[j];
2358 break;
2359 }
2360 }
2361 }
2362 if (rSubmixModule == 0) {
2363 res = INVALID_OPERATION;
2364 continue;
2365 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002366
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002367 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002368
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002369 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2370 res = INVALID_OPERATION;
2371 continue;
2372 }
2373
2374 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2375 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2376 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2377 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2378 address.string(), "remote-submix");
2379 }
2380 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2381 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2382 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2383 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2384 address.string(), "remote-submix");
2385 }
2386 rSubmixModule->removeOutputProfile(address);
2387 rSubmixModule->removeInputProfile(address);
2388
2389 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2390 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2391 res = INVALID_OPERATION;
2392 continue;
2393 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002394 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002395 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002396 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002397}
2398
Eric Laurente552edb2014-03-10 17:42:56 -07002399
Eric Laurente0720872014-03-11 09:30:41 -07002400status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002401{
2402 const size_t SIZE = 256;
2403 char buffer[SIZE];
2404 String8 result;
2405
2406 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2407 result.append(buffer);
2408
Eric Laurent87ffa392015-05-22 10:32:38 -07002409 snprintf(buffer, SIZE, " Primary Output: %d\n",
2410 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002411 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002412 std::string stateLiteral;
2413 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2414 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002415 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002416 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002417 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002418 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002419 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002420 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002421 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002422 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002423 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002424 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002425 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002426 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002427 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002428 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002429 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002430 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2431 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2432 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002433 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2434 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002435 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2436 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002437
François Gaffie2110e042015-03-24 08:41:51 +01002438 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002439
François Gaffie112b0af2015-11-19 16:13:25 +01002440 mAvailableOutputDevices.dump(fd, String8("Available output"));
2441 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002442 mHwModules.dump(fd);
2443 mOutputs.dump(fd);
2444 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002445 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002446 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002447 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002448 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002449
2450 return NO_ERROR;
2451}
2452
2453// This function checks for the parameters which can be offloaded.
2454// This can be enhanced depending on the capability of the DSP and policy
2455// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002456bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002457{
2458 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002459 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002460 offloadInfo.sample_rate, offloadInfo.channel_mask,
2461 offloadInfo.format,
2462 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2463 offloadInfo.has_video);
2464
Andy Hung2ddee192015-12-18 17:34:44 -08002465 if (mMasterMono) {
2466 return false; // no offloading if mono is set.
2467 }
2468
Eric Laurente552edb2014-03-10 17:42:56 -07002469 // Check if offload has been disabled
2470 char propValue[PROPERTY_VALUE_MAX];
2471 if (property_get("audio.offload.disable", propValue, "0")) {
2472 if (atoi(propValue) != 0) {
2473 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2474 return false;
2475 }
2476 }
2477
2478 // Check if stream type is music, then only allow offload as of now.
2479 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2480 {
2481 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2482 return false;
2483 }
2484
2485 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002486 const bool allowOffloadWithVideo =
2487 property_get_bool("audio.offload.video", false /* default_value */);
2488 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002489 ALOGV("isOffloadSupported: has_video == true, returning false");
2490 return false;
2491 }
2492
2493 //If duration is less than minimum value defined in property, return false
2494 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2495 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2496 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2497 return false;
2498 }
2499 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2500 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2501 return false;
2502 }
2503
2504 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2505 // creating an offloaded track and tearing it down immediately after start when audioflinger
2506 // detects there is an active non offloadable effect.
2507 // FIXME: We should check the audio session here but we do not have it in this context.
2508 // This may prevent offloading in rare situations where effects are left active by apps
2509 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002510 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002511 return false;
2512 }
2513
2514 // See if there is a profile to support this.
2515 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002516 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002517 offloadInfo.sample_rate,
2518 offloadInfo.format,
2519 offloadInfo.channel_mask,
2520 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002521 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2522 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002523}
2524
Eric Laurent6a94d692014-05-20 11:18:06 -07002525status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2526 audio_port_type_t type,
2527 unsigned int *num_ports,
2528 struct audio_port *ports,
2529 unsigned int *generation)
2530{
2531 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2532 generation == NULL) {
2533 return BAD_VALUE;
2534 }
2535 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2536 if (ports == NULL) {
2537 *num_ports = 0;
2538 }
2539
2540 size_t portsWritten = 0;
2541 size_t portsMax = *num_ports;
2542 *num_ports = 0;
2543 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002544 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2545 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002546 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002547 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2548 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2549 continue;
2550 }
2551 if (portsWritten < portsMax) {
2552 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2553 }
2554 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002555 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002556 }
2557 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002558 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2559 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2560 continue;
2561 }
2562 if (portsWritten < portsMax) {
2563 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2564 }
2565 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002566 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002567 }
2568 }
2569 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2570 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2571 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2572 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2573 }
2574 *num_ports += mInputs.size();
2575 }
2576 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002577 size_t numOutputs = 0;
2578 for (size_t i = 0; i < mOutputs.size(); i++) {
2579 if (!mOutputs[i]->isDuplicated()) {
2580 numOutputs++;
2581 if (portsWritten < portsMax) {
2582 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2583 }
2584 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002585 }
Eric Laurent84c70242014-06-23 08:46:27 -07002586 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002587 }
2588 }
2589 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002590 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002591 return NO_ERROR;
2592}
2593
2594status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2595{
2596 return NO_ERROR;
2597}
2598
Eric Laurent6a94d692014-05-20 11:18:06 -07002599status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2600 audio_patch_handle_t *handle,
2601 uid_t uid)
2602{
2603 ALOGV("createAudioPatch()");
2604
2605 if (handle == NULL || patch == NULL) {
2606 return BAD_VALUE;
2607 }
2608 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2609
Eric Laurent874c42872014-08-08 15:13:39 -07002610 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2611 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2612 return BAD_VALUE;
2613 }
2614 // only one source per audio patch supported for now
2615 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002616 return INVALID_OPERATION;
2617 }
Eric Laurent874c42872014-08-08 15:13:39 -07002618
2619 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002620 return INVALID_OPERATION;
2621 }
Eric Laurent874c42872014-08-08 15:13:39 -07002622 for (size_t i = 0; i < patch->num_sinks; i++) {
2623 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2624 return INVALID_OPERATION;
2625 }
2626 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002627
2628 sp<AudioPatch> patchDesc;
2629 ssize_t index = mAudioPatches.indexOfKey(*handle);
2630
Eric Laurent6a94d692014-05-20 11:18:06 -07002631 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2632 patch->sources[0].role,
2633 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002634#if LOG_NDEBUG == 0
2635 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002636 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002637 patch->sinks[i].role,
2638 patch->sinks[i].type);
2639 }
2640#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002641
2642 if (index >= 0) {
2643 patchDesc = mAudioPatches.valueAt(index);
2644 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2645 mUidCached, patchDesc->mUid, uid);
2646 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2647 return INVALID_OPERATION;
2648 }
2649 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002650 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002651 }
2652
2653 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002654 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002655 if (outputDesc == NULL) {
2656 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2657 return BAD_VALUE;
2658 }
Eric Laurent84c70242014-06-23 08:46:27 -07002659 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2660 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002661 if (patchDesc != 0) {
2662 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2663 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2664 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2665 return BAD_VALUE;
2666 }
2667 }
Eric Laurent874c42872014-08-08 15:13:39 -07002668 DeviceVector devices;
2669 for (size_t i = 0; i < patch->num_sinks; i++) {
2670 // Only support mix to devices connection
2671 // TODO add support for mix to mix connection
2672 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2673 ALOGV("createAudioPatch() source mix but sink is not a device");
2674 return INVALID_OPERATION;
2675 }
2676 sp<DeviceDescriptor> devDesc =
2677 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2678 if (devDesc == 0) {
2679 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2680 return BAD_VALUE;
2681 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002682
François Gaffie53615e22015-03-19 09:24:12 +01002683 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002684 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002685 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002686 NULL, // updatedSamplingRate
2687 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002688 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002689 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002690 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002691 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002692 ALOGV("createAudioPatch() profile not supported for device %08x",
2693 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002694 return INVALID_OPERATION;
2695 }
2696 devices.add(devDesc);
2697 }
2698 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002699 return INVALID_OPERATION;
2700 }
Eric Laurent874c42872014-08-08 15:13:39 -07002701
Eric Laurent6a94d692014-05-20 11:18:06 -07002702 // TODO: reconfigure output format and channels here
2703 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002704 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002705 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002706 index = mAudioPatches.indexOfKey(*handle);
2707 if (index >= 0) {
2708 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2709 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2710 }
2711 patchDesc = mAudioPatches.valueAt(index);
2712 patchDesc->mUid = uid;
2713 ALOGV("createAudioPatch() success");
2714 } else {
2715 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2716 return INVALID_OPERATION;
2717 }
2718 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2719 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2720 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002721 // only one sink supported when connecting an input device to a mix
2722 if (patch->num_sinks > 1) {
2723 return INVALID_OPERATION;
2724 }
François Gaffie53615e22015-03-19 09:24:12 +01002725 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002726 if (inputDesc == NULL) {
2727 return BAD_VALUE;
2728 }
2729 if (patchDesc != 0) {
2730 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2731 return BAD_VALUE;
2732 }
2733 }
2734 sp<DeviceDescriptor> devDesc =
2735 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2736 if (devDesc == 0) {
2737 return BAD_VALUE;
2738 }
2739
François Gaffie53615e22015-03-19 09:24:12 +01002740 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002741 devDesc->mAddress,
2742 patch->sinks[0].sample_rate,
2743 NULL, /*updatedSampleRate*/
2744 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002745 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002746 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002747 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002748 // FIXME for the parameter type,
2749 // and the NONE
2750 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002751 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002752 return INVALID_OPERATION;
2753 }
2754 // TODO: reconfigure output format and channels here
2755 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002756 devDesc->type(), inputDesc->mIoHandle);
2757 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002758 index = mAudioPatches.indexOfKey(*handle);
2759 if (index >= 0) {
2760 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2761 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2762 }
2763 patchDesc = mAudioPatches.valueAt(index);
2764 patchDesc->mUid = uid;
2765 ALOGV("createAudioPatch() success");
2766 } else {
2767 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2768 return INVALID_OPERATION;
2769 }
2770 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2771 // device to device connection
2772 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002773 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002774 return BAD_VALUE;
2775 }
2776 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002777 sp<DeviceDescriptor> srcDeviceDesc =
2778 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002779 if (srcDeviceDesc == 0) {
2780 return BAD_VALUE;
2781 }
Eric Laurent874c42872014-08-08 15:13:39 -07002782
Eric Laurent6a94d692014-05-20 11:18:06 -07002783 //update source and sink with our own data as the data passed in the patch may
2784 // be incomplete.
2785 struct audio_patch newPatch = *patch;
2786 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002787
Eric Laurent874c42872014-08-08 15:13:39 -07002788 for (size_t i = 0; i < patch->num_sinks; i++) {
2789 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2790 ALOGV("createAudioPatch() source device but one sink is not a device");
2791 return INVALID_OPERATION;
2792 }
2793
2794 sp<DeviceDescriptor> sinkDeviceDesc =
2795 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2796 if (sinkDeviceDesc == 0) {
2797 return BAD_VALUE;
2798 }
2799 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2800
Eric Laurent3bcf8592015-04-03 12:13:24 -07002801 // create a software bridge in PatchPanel if:
2802 // - source and sink devices are on differnt HW modules OR
2803 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002804 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002805 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002806 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002807 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002808 return INVALID_OPERATION;
2809 }
Eric Laurent874c42872014-08-08 15:13:39 -07002810 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002811 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002812 // if the sink device is reachable via an opened output stream, request to go via
2813 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002814 audio_io_handle_t output = selectOutput(outputs,
2815 AUDIO_OUTPUT_FLAG_NONE,
2816 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002817 if (output != AUDIO_IO_HANDLE_NONE) {
2818 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2819 if (outputDesc->isDuplicated()) {
2820 return INVALID_OPERATION;
2821 }
2822 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002823 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002824 newPatch.num_sources = 2;
2825 }
Eric Laurent83b88082014-06-20 18:31:16 -07002826 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 }
2828 // TODO: check from routing capabilities in config file and other conflicting patches
2829
2830 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2831 if (index >= 0) {
2832 afPatchHandle = patchDesc->mAfPatchHandle;
2833 }
2834
2835 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2836 &afPatchHandle,
2837 0);
2838 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2839 status, afPatchHandle);
2840 if (status == NO_ERROR) {
2841 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002842 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 addAudioPatch(patchDesc->mHandle, patchDesc);
2844 } else {
2845 patchDesc->mPatch = newPatch;
2846 }
2847 patchDesc->mAfPatchHandle = afPatchHandle;
2848 *handle = patchDesc->mHandle;
2849 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002850 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002851 } else {
2852 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2853 status);
2854 return INVALID_OPERATION;
2855 }
2856 } else {
2857 return BAD_VALUE;
2858 }
2859 } else {
2860 return BAD_VALUE;
2861 }
2862 return NO_ERROR;
2863}
2864
2865status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2866 uid_t uid)
2867{
2868 ALOGV("releaseAudioPatch() patch %d", handle);
2869
2870 ssize_t index = mAudioPatches.indexOfKey(handle);
2871
2872 if (index < 0) {
2873 return BAD_VALUE;
2874 }
2875 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2876 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2877 mUidCached, patchDesc->mUid, uid);
2878 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2879 return INVALID_OPERATION;
2880 }
2881
2882 struct audio_patch *patch = &patchDesc->mPatch;
2883 patchDesc->mUid = mUidCached;
2884 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002885 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002886 if (outputDesc == NULL) {
2887 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2888 return BAD_VALUE;
2889 }
2890
Eric Laurentc75307b2015-03-17 15:29:32 -07002891 setOutputDevice(outputDesc,
2892 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002893 true,
2894 0,
2895 NULL);
2896 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2897 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002898 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 if (inputDesc == NULL) {
2900 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2901 return BAD_VALUE;
2902 }
2903 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002904 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002905 true,
2906 NULL);
2907 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002908 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2909 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2910 status, patchDesc->mAfPatchHandle);
2911 removeAudioPatch(patchDesc->mHandle);
2912 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002913 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002914 } else {
2915 return BAD_VALUE;
2916 }
2917 } else {
2918 return BAD_VALUE;
2919 }
2920 return NO_ERROR;
2921}
2922
2923status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2924 struct audio_patch *patches,
2925 unsigned int *generation)
2926{
François Gaffie53615e22015-03-19 09:24:12 +01002927 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002928 return BAD_VALUE;
2929 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002931 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002932}
2933
Eric Laurente1715a42014-05-20 11:30:42 -07002934status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002935{
Eric Laurente1715a42014-05-20 11:30:42 -07002936 ALOGV("setAudioPortConfig()");
2937
2938 if (config == NULL) {
2939 return BAD_VALUE;
2940 }
2941 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2942 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002943 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2944 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002945 }
2946
Eric Laurenta121f902014-06-03 13:32:54 -07002947 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002948 if (config->type == AUDIO_PORT_TYPE_MIX) {
2949 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002950 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002951 if (outputDesc == NULL) {
2952 return BAD_VALUE;
2953 }
Eric Laurent84c70242014-06-23 08:46:27 -07002954 ALOG_ASSERT(!outputDesc->isDuplicated(),
2955 "setAudioPortConfig() called on duplicated output %d",
2956 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002957 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002958 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002959 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002960 if (inputDesc == NULL) {
2961 return BAD_VALUE;
2962 }
Eric Laurenta121f902014-06-03 13:32:54 -07002963 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002964 } else {
2965 return BAD_VALUE;
2966 }
2967 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2968 sp<DeviceDescriptor> deviceDesc;
2969 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2970 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2971 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2972 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2973 } else {
2974 return BAD_VALUE;
2975 }
2976 if (deviceDesc == NULL) {
2977 return BAD_VALUE;
2978 }
Eric Laurenta121f902014-06-03 13:32:54 -07002979 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002980 } else {
2981 return BAD_VALUE;
2982 }
2983
Eric Laurenta121f902014-06-03 13:32:54 -07002984 struct audio_port_config backupConfig;
2985 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2986 if (status == NO_ERROR) {
2987 struct audio_port_config newConfig;
2988 audioPortConfig->toAudioPortConfig(&newConfig, config);
2989 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002990 }
Eric Laurenta121f902014-06-03 13:32:54 -07002991 if (status != NO_ERROR) {
2992 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002993 }
Eric Laurente1715a42014-05-20 11:30:42 -07002994
2995 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002996}
2997
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002998void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2999{
Eric Laurentd60560a2015-04-10 11:31:20 -07003000 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003001 clearAudioPatches(uid);
3002 clearSessionRoutes(uid);
3003}
3004
Eric Laurent6a94d692014-05-20 11:18:06 -07003005void AudioPolicyManager::clearAudioPatches(uid_t uid)
3006{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003007 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003008 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3009 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003010 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003011 }
3012 }
3013}
3014
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003015void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3016 audio_io_handle_t ouptutToSkip)
3017{
3018 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3019 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3020 for (size_t j = 0; j < mOutputs.size(); j++) {
3021 if (mOutputs.keyAt(j) == ouptutToSkip) {
3022 continue;
3023 }
3024 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3025 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3026 continue;
3027 }
3028 // If the default device for this strategy is on another output mix,
3029 // invalidate all tracks in this strategy to force re connection.
3030 // Otherwise select new device on the output mix.
3031 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003032 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003033 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3034 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3035 }
3036 }
3037 } else {
3038 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3039 setOutputDevice(outputDesc, newDevice, false);
3040 }
3041 }
3042}
3043
3044void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3045{
3046 // remove output routes associated with this uid
3047 SortedVector<routing_strategy> affectedStrategies;
3048 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3049 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3050 if (route->mUid == uid) {
3051 mOutputRoutes.removeItemsAt(i);
3052 if (route->mDeviceDescriptor != 0) {
3053 affectedStrategies.add(getStrategy(route->mStreamType));
3054 }
3055 }
3056 }
3057 // reroute outputs if necessary
3058 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3059 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3060 }
3061
3062 // remove input routes associated with this uid
3063 SortedVector<audio_source_t> affectedSources;
3064 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3065 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3066 if (route->mUid == uid) {
3067 mInputRoutes.removeItemsAt(i);
3068 if (route->mDeviceDescriptor != 0) {
3069 affectedSources.add(route->mSource);
3070 }
3071 }
3072 }
3073 // reroute inputs if necessary
3074 SortedVector<audio_io_handle_t> inputsToClose;
3075 for (size_t i = 0; i < mInputs.size(); i++) {
3076 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003077 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003078 inputsToClose.add(inputDesc->mIoHandle);
3079 }
3080 }
3081 for (size_t i = 0; i < inputsToClose.size(); i++) {
3082 closeInput(inputsToClose[i]);
3083 }
3084}
3085
Eric Laurentd60560a2015-04-10 11:31:20 -07003086void AudioPolicyManager::clearAudioSources(uid_t uid)
3087{
3088 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3089 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3090 if (sourceDesc->mUid == uid) {
3091 stopAudioSource(mAudioSources.keyAt(i));
3092 }
3093 }
3094}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003095
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003096status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3097 audio_io_handle_t *ioHandle,
3098 audio_devices_t *device)
3099{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003100 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3101 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003102 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003103
François Gaffiedf372692015-03-19 10:43:27 +01003104 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003105}
3106
Eric Laurentd60560a2015-04-10 11:31:20 -07003107status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3108 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003109 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003110 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003111{
Eric Laurentd60560a2015-04-10 11:31:20 -07003112 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3113 if (source == NULL || attributes == NULL || handle == NULL) {
3114 return BAD_VALUE;
3115 }
3116
Glenn Kasten559d4392016-03-29 13:42:57 -07003117 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003118
3119 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3120 source->type != AUDIO_PORT_TYPE_DEVICE) {
3121 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3122 return INVALID_OPERATION;
3123 }
3124
3125 sp<DeviceDescriptor> srcDeviceDesc =
3126 mAvailableInputDevices.getDevice(source->ext.device.type,
3127 String8(source->ext.device.address));
3128 if (srcDeviceDesc == 0) {
3129 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3130 return BAD_VALUE;
3131 }
3132 sp<AudioSourceDescriptor> sourceDesc =
3133 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3134
3135 struct audio_patch dummyPatch;
3136 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3137 sourceDesc->mPatchDesc = patchDesc;
3138
3139 status_t status = connectAudioSource(sourceDesc);
3140 if (status == NO_ERROR) {
3141 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3142 *handle = sourceDesc->getHandle();
3143 }
3144 return status;
3145}
3146
3147status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3148{
3149 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3150
3151 // make sure we only have one patch per source.
3152 disconnectAudioSource(sourceDesc);
3153
3154 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003155 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003156 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3157
3158 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3159 sp<DeviceDescriptor> sinkDeviceDesc =
3160 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3161
3162 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3163 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3164
3165 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3166 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003167 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003168 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3169 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3170 // create patch between src device and output device
3171 // create Hwoutput and add to mHwOutputs
3172 } else {
3173 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3174 audio_io_handle_t output =
3175 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3176 if (output == AUDIO_IO_HANDLE_NONE) {
3177 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3178 return INVALID_OPERATION;
3179 }
3180 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3181 if (outputDesc->isDuplicated()) {
3182 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3183 return INVALID_OPERATION;
3184 }
3185 // create a special patch with no sink and two sources:
3186 // - the second source indicates to PatchPanel through which output mix this patch should
3187 // be connected as well as the stream type for volume control
3188 // - the sink is defined by whatever output device is currently selected for the output
3189 // though which this patch is routed.
3190 patch->num_sinks = 0;
3191 patch->num_sources = 2;
3192 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3193 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3194 patch->sources[1].ext.mix.usecase.stream = stream;
3195 status_t status = mpClientInterface->createAudioPatch(patch,
3196 &afPatchHandle,
3197 0);
3198 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3199 status, afPatchHandle);
3200 if (status != NO_ERROR) {
3201 ALOGW("%s patch panel could not connect device patch, error %d",
3202 __FUNCTION__, status);
3203 return INVALID_OPERATION;
3204 }
3205 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003206 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003207
3208 if (status != NO_ERROR) {
3209 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3210 return status;
3211 }
3212 sourceDesc->mSwOutput = outputDesc;
3213 if (delayMs != 0) {
3214 usleep(delayMs * 1000);
3215 }
3216 }
3217
3218 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3219 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3220
3221 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003222}
3223
Glenn Kasten559d4392016-03-29 13:42:57 -07003224status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003225{
Eric Laurentd60560a2015-04-10 11:31:20 -07003226 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3227 ALOGV("%s handle %d", __FUNCTION__, handle);
3228 if (sourceDesc == 0) {
3229 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3230 return BAD_VALUE;
3231 }
3232 status_t status = disconnectAudioSource(sourceDesc);
3233
3234 mAudioSources.removeItem(handle);
3235 return status;
3236}
3237
Andy Hung2ddee192015-12-18 17:34:44 -08003238status_t AudioPolicyManager::setMasterMono(bool mono)
3239{
3240 if (mMasterMono == mono) {
3241 return NO_ERROR;
3242 }
3243 mMasterMono = mono;
3244 // if enabling mono we close all offloaded devices, which will invalidate the
3245 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3246 // for recreating the new AudioTrack as non-offloaded PCM.
3247 //
3248 // If disabling mono, we leave all tracks as is: we don't know which clients
3249 // and tracks are able to be recreated as offloaded. The next "song" should
3250 // play back offloaded.
3251 if (mMasterMono) {
3252 Vector<audio_io_handle_t> offloaded;
3253 for (size_t i = 0; i < mOutputs.size(); ++i) {
3254 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3255 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3256 offloaded.push(desc->mIoHandle);
3257 }
3258 }
3259 for (size_t i = 0; i < offloaded.size(); ++i) {
3260 closeOutput(offloaded[i]);
3261 }
3262 }
3263 // update master mono for all remaining outputs
3264 for (size_t i = 0; i < mOutputs.size(); ++i) {
3265 updateMono(mOutputs.keyAt(i));
3266 }
3267 return NO_ERROR;
3268}
3269
3270status_t AudioPolicyManager::getMasterMono(bool *mono)
3271{
3272 *mono = mMasterMono;
3273 return NO_ERROR;
3274}
3275
Eric Laurentd60560a2015-04-10 11:31:20 -07003276status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3277{
3278 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3279
3280 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3281 if (patchDesc == 0) {
3282 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3283 sourceDesc->mPatchDesc->mHandle);
3284 return BAD_VALUE;
3285 }
3286 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3287
Eric Laurent28d09f02016-03-08 10:43:05 -08003288 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003289 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3290 if (swOutputDesc != 0) {
3291 stopSource(swOutputDesc, stream, false);
3292 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3293 } else {
3294 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3295 if (hwOutputDesc != 0) {
3296 // release patch between src device and output device
3297 // close Hwoutput and remove from mHwOutputs
3298 } else {
3299 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3300 }
3301 }
3302 return NO_ERROR;
3303}
3304
3305sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3306 audio_io_handle_t output, routing_strategy strategy)
3307{
3308 sp<AudioSourceDescriptor> source;
3309 for (size_t i = 0; i < mAudioSources.size(); i++) {
3310 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3311 routing_strategy sourceStrategy =
3312 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3313 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3314 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3315 source = sourceDesc;
3316 break;
3317 }
3318 }
3319 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003320}
3321
Eric Laurente552edb2014-03-10 17:42:56 -07003322// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003323// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003324// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003325uint32_t AudioPolicyManager::nextAudioPortGeneration()
3326{
3327 return android_atomic_inc(&mAudioPortGeneration);
3328}
3329
Eric Laurente0720872014-03-11 09:30:41 -07003330AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003331 :
3332#ifdef AUDIO_POLICY_TEST
3333 Thread(false),
3334#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003335 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003336 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003337 mAudioPortGeneration(1),
3338 mBeaconMuteRefCount(0),
3339 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003340 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003341 mTtsOutputAvailable(false),
3342 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003343{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003344 mUidCached = getuid();
3345 mpClientInterface = clientInterface;
3346
3347 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3348 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3349 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3350 bool speakerDrcEnabled = false;
3351
3352#ifdef USE_XML_AUDIO_POLICY_CONF
3353 mVolumeCurves = new VolumeCurvesCollection();
3354 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3355 mDefaultOutputDevice, speakerDrcEnabled,
3356 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3357 PolicySerializer serializer;
3358 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3359#else
3360 mVolumeCurves = new StreamDescriptorCollection();
3361 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3362 mDefaultOutputDevice, speakerDrcEnabled);
3363 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3364 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3365#endif
3366 ALOGE("could not load audio policy configuration file, setting defaults");
3367 config.setDefault();
3368 }
3369 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3370 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3371
3372 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003373 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3374 if (!engineInstance) {
3375 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3376 return;
3377 }
3378 // Retrieve the Policy Manager Interface
3379 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3380 if (mEngine == NULL) {
3381 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3382 return;
3383 }
3384 mEngine->setObserver(this);
3385 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003386 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003387 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3388
Eric Laurent3a4311c2014-03-17 12:00:47 -07003389 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003390 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003391 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3392 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003393 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003394 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003395 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003396 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003397 continue;
3398 }
3399 // open all output streams needed to access attached devices
3400 // except for direct output streams that are only opened when they are actually
3401 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003402 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003403 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3404 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003405 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003406
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003407 if (!outProfile->hasSupportedDevices()) {
3408 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003409 continue;
3410 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003411 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003412 mTtsOutputAvailable = true;
3413 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003414
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003415 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003416 continue;
3417 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003418 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003419 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3420 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003421 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003422 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003423 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003424 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003425 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003426 if ((profileType & outputDeviceTypes) == 0) {
3427 continue;
3428 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003429 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3430 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003431 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3432 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3433 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3434 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003435
3436 outputDesc->mDevice = profileType;
3437 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3438 config.sample_rate = outputDesc->mSamplingRate;
3439 config.channel_mask = outputDesc->mChannelMask;
3440 config.format = outputDesc->mFormat;
3441 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003442 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003443 &output,
3444 &config,
3445 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003446 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003447 &outputDesc->mLatency,
3448 outputDesc->mFlags);
3449
3450 if (status != NO_ERROR) {
3451 ALOGW("Cannot open output stream for device %08x on hw module %s",
3452 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003453 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003454 } else {
3455 outputDesc->mSamplingRate = config.sample_rate;
3456 outputDesc->mChannelMask = config.channel_mask;
3457 outputDesc->mFormat = config.format;
3458
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003459 for (size_t k = 0; k < supportedDevices.size(); k++) {
3460 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003461 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003462 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3463 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003464 }
3465 }
3466 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003467 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003468 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003469 }
3470 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003471 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003472 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003473 true,
3474 0,
3475 NULL,
3476 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003477 }
Eric Laurente552edb2014-03-10 17:42:56 -07003478 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003479 // open input streams needed to access attached devices to validate
3480 // mAvailableInputDevices list
3481 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3482 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003483 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003484
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003485 if (!inProfile->hasSupportedDevices()) {
3486 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003487 continue;
3488 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003489 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003490 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003491 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3492
Eric Laurentd78f1532014-09-16 16:38:20 -07003493 if ((profileType & inputDeviceTypes) == 0) {
3494 continue;
3495 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003496 sp<AudioInputDescriptor> inputDesc =
3497 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003498
Eric Laurentd78f1532014-09-16 16:38:20 -07003499 inputDesc->mDevice = profileType;
3500
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003501 // find the address
3502 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3503 // the inputs vector must be of size 1, but we don't want to crash here
3504 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3505 : String8("");
3506 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3507 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3508
Eric Laurentd78f1532014-09-16 16:38:20 -07003509 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3510 config.sample_rate = inputDesc->mSamplingRate;
3511 config.channel_mask = inputDesc->mChannelMask;
3512 config.format = inputDesc->mFormat;
3513 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003514 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003515 &input,
3516 &config,
3517 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003518 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003519 AUDIO_SOURCE_MIC,
3520 AUDIO_INPUT_FLAG_NONE);
3521
3522 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003523 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3524 for (size_t k = 0; k < supportedDevices.size(); k++) {
3525 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003526 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003527 if (index >= 0) {
3528 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3529 if (!devDesc->isAttached()) {
3530 devDesc->attach(mHwModules[i]);
3531 devDesc->importAudioPort(inProfile);
3532 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003533 }
3534 }
3535 mpClientInterface->closeInput(input);
3536 } else {
3537 ALOGW("Cannot open input stream for device %08x on hw module %s",
3538 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003539 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003540 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003541 }
3542 }
3543 // make sure all attached devices have been allocated a unique ID
3544 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003545 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003546 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003547 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3548 continue;
3549 }
François Gaffie2110e042015-03-24 08:41:51 +01003550 // The device is now validated and can be appended to the available devices of the engine
3551 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3552 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003553 i++;
3554 }
3555 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003556 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003557 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003558 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3559 continue;
3560 }
François Gaffie2110e042015-03-24 08:41:51 +01003561 // The device is now validated and can be appended to the available devices of the engine
3562 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3563 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003564 i++;
3565 }
3566 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003567 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003568 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003569 }
Eric Laurente552edb2014-03-10 17:42:56 -07003570
3571 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3572
3573 updateDevicesAndOutputs();
3574
3575#ifdef AUDIO_POLICY_TEST
3576 if (mPrimaryOutput != 0) {
3577 AudioParameter outputCmd = AudioParameter();
3578 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003579 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003580
3581 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3582 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003583 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3584 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003585 mTestLatencyMs = 0;
3586 mCurOutput = 0;
3587 mDirectOutput = false;
3588 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3589 mTestOutputs[i] = 0;
3590 }
3591
3592 const size_t SIZE = 256;
3593 char buffer[SIZE];
3594 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3595 run(buffer, ANDROID_PRIORITY_AUDIO);
3596 }
3597#endif //AUDIO_POLICY_TEST
3598}
3599
Eric Laurente0720872014-03-11 09:30:41 -07003600AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003601{
3602#ifdef AUDIO_POLICY_TEST
3603 exit();
3604#endif //AUDIO_POLICY_TEST
3605 for (size_t i = 0; i < mOutputs.size(); i++) {
3606 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003607 }
3608 for (size_t i = 0; i < mInputs.size(); i++) {
3609 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003610 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003611 mAvailableOutputDevices.clear();
3612 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003613 mOutputs.clear();
3614 mInputs.clear();
3615 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003616}
3617
Eric Laurente0720872014-03-11 09:30:41 -07003618status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003619{
Eric Laurent87ffa392015-05-22 10:32:38 -07003620 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003621}
3622
3623#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003624bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003625{
3626 ALOGV("entering threadLoop()");
3627 while (!exitPending())
3628 {
3629 String8 command;
3630 int valueInt;
3631 String8 value;
3632
3633 Mutex::Autolock _l(mLock);
3634 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3635
3636 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3637 AudioParameter param = AudioParameter(command);
3638
3639 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3640 valueInt != 0) {
3641 ALOGV("Test command %s received", command.string());
3642 String8 target;
3643 if (param.get(String8("target"), target) != NO_ERROR) {
3644 target = "Manager";
3645 }
3646 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3647 param.remove(String8("test_cmd_policy_output"));
3648 mCurOutput = valueInt;
3649 }
3650 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3651 param.remove(String8("test_cmd_policy_direct"));
3652 if (value == "false") {
3653 mDirectOutput = false;
3654 } else if (value == "true") {
3655 mDirectOutput = true;
3656 }
3657 }
3658 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3659 param.remove(String8("test_cmd_policy_input"));
3660 mTestInput = valueInt;
3661 }
3662
3663 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3664 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003665 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003666 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003667 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003668 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003669 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003670 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003671 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003672 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003673 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003674 if (target == "Manager") {
3675 mTestFormat = format;
3676 } else if (mTestOutputs[mCurOutput] != 0) {
3677 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003678 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003679 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3680 }
3681 }
3682 }
3683 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3684 param.remove(String8("test_cmd_policy_channels"));
3685 int channels = 0;
3686
3687 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003688 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003689 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003690 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003691 }
3692 if (channels != 0) {
3693 if (target == "Manager") {
3694 mTestChannels = channels;
3695 } else if (mTestOutputs[mCurOutput] != 0) {
3696 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003697 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003698 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3699 }
3700 }
3701 }
3702 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3703 param.remove(String8("test_cmd_policy_sampleRate"));
3704 if (valueInt >= 0 && valueInt <= 96000) {
3705 int samplingRate = valueInt;
3706 if (target == "Manager") {
3707 mTestSamplingRate = samplingRate;
3708 } else if (mTestOutputs[mCurOutput] != 0) {
3709 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003710 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003711 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3712 }
3713 }
3714 }
3715
3716 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3717 param.remove(String8("test_cmd_policy_reopen"));
3718
Eric Laurentc75307b2015-03-17 15:29:32 -07003719 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003720
Eric Laurentc75307b2015-03-17 15:29:32 -07003721 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003722
Eric Laurentc75307b2015-03-17 15:29:32 -07003723 removeOutput(mPrimaryOutput->mIoHandle);
3724 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3725 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003726 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003727 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3728 config.sample_rate = outputDesc->mSamplingRate;
3729 config.channel_mask = outputDesc->mChannelMask;
3730 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003731 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003732 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003733 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003734 &config,
3735 &outputDesc->mDevice,
3736 String8(""),
3737 &outputDesc->mLatency,
3738 outputDesc->mFlags);
3739 if (status != NO_ERROR) {
3740 ALOGE("Failed to reopen hardware output stream, "
3741 "samplingRate: %d, format %d, channels %d",
3742 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003743 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003744 outputDesc->mSamplingRate = config.sample_rate;
3745 outputDesc->mChannelMask = config.channel_mask;
3746 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003747 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003748 AudioParameter outputCmd = AudioParameter();
3749 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003750 mpClientInterface->setParameters(handle, outputCmd.toString());
3751 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003752 }
3753 }
3754
3755
3756 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3757 }
3758 }
3759 return false;
3760}
3761
Eric Laurente0720872014-03-11 09:30:41 -07003762void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003763{
3764 {
3765 AutoMutex _l(mLock);
3766 requestExit();
3767 mWaitWorkCV.signal();
3768 }
3769 requestExitAndWait();
3770}
3771
Eric Laurente0720872014-03-11 09:30:41 -07003772int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003773{
3774 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3775 if (output == mTestOutputs[i]) return i;
3776 }
3777 return 0;
3778}
3779#endif //AUDIO_POLICY_TEST
3780
3781// ---
3782
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003783void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003784{
François Gaffie98cc1912015-03-18 17:52:40 +01003785 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003786 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003787 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003788 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003789}
3790
François Gaffie53615e22015-03-19 09:24:12 +01003791void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3792{
3793 mOutputs.removeItem(output);
3794}
3795
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003796void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003797{
François Gaffie98cc1912015-03-18 17:52:40 +01003798 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003799 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003800 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003801}
Eric Laurente552edb2014-03-10 17:42:56 -07003802
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003803void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003804 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003805 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003806 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003807 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003808 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003809 if (devDesc != 0) {
3810 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3811 desc->mIoHandle, address.string());
3812 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003813 }
3814}
3815
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003816status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003817 audio_policy_dev_state_t state,
3818 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003819 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003820{
François Gaffie53615e22015-03-19 09:24:12 +01003821 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003822 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003823
3824 if (audio_device_is_digital(device)) {
3825 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003826 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003827 }
Eric Laurente552edb2014-03-10 17:42:56 -07003828
Eric Laurent3b73df72014-03-11 09:06:29 -07003829 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003830 // first list already open outputs that can be routed to this device
3831 for (size_t i = 0; i < mOutputs.size(); i++) {
3832 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003833 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003834 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003835 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3836 outputs.add(mOutputs.keyAt(i));
3837 } else {
3838 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003839 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003840 }
Eric Laurente552edb2014-03-10 17:42:56 -07003841 }
3842 }
3843 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003844 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003845 for (size_t i = 0; i < mHwModules.size(); i++)
3846 {
3847 if (mHwModules[i]->mHandle == 0) {
3848 continue;
3849 }
3850 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3851 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003852 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003853 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003854 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003855 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003856 profiles.add(profile);
3857 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3858 }
Eric Laurente552edb2014-03-10 17:42:56 -07003859 }
3860 }
3861 }
3862
Eric Laurent7b279bb2015-12-14 10:18:23 -08003863 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003864
Eric Laurente552edb2014-03-10 17:42:56 -07003865 if (profiles.isEmpty() && outputs.isEmpty()) {
3866 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3867 return BAD_VALUE;
3868 }
3869
3870 // open outputs for matching profiles if needed. Direct outputs are also opened to
3871 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3872 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003873 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003874
3875 // nothing to do if one output is already opened for this profile
3876 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003877 for (j = 0; j < outputs.size(); j++) {
3878 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003879 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003880 // matching profile: save the sample rates, format and channel masks supported
3881 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003882 if (audio_device_is_digital(device)) {
3883 devDesc->importAudioPort(profile);
3884 }
Eric Laurente552edb2014-03-10 17:42:56 -07003885 break;
3886 }
3887 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003888 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003889 continue;
3890 }
3891
Eric Laurent83b88082014-06-20 18:31:16 -07003892 ALOGV("opening output for device %08x with params %s profile %p",
3893 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003894 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003895 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003896 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3897 config.sample_rate = desc->mSamplingRate;
3898 config.channel_mask = desc->mChannelMask;
3899 config.format = desc->mFormat;
3900 config.offload_info.sample_rate = desc->mSamplingRate;
3901 config.offload_info.channel_mask = desc->mChannelMask;
3902 config.offload_info.format = desc->mFormat;
3903 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003904 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003905 &output,
3906 &config,
3907 &desc->mDevice,
3908 address,
3909 &desc->mLatency,
3910 desc->mFlags);
3911 if (status == NO_ERROR) {
3912 desc->mSamplingRate = config.sample_rate;
3913 desc->mChannelMask = config.channel_mask;
3914 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003915
Eric Laurentd4692962014-05-05 18:13:44 -07003916 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003917 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003918 char *param = audio_device_address_to_parameter(device, address);
3919 mpClientInterface->setParameters(output, String8(param));
3920 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003921 }
Phil Burk00eeb322016-03-31 12:41:00 -07003922 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003923 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003924 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003925 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003926 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003927 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003928 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003929 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003930 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003931 config.offload_info.sample_rate = config.sample_rate;
3932 config.offload_info.channel_mask = config.channel_mask;
3933 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003934 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003935 &output,
3936 &config,
3937 &desc->mDevice,
3938 address,
3939 &desc->mLatency,
3940 desc->mFlags);
3941 if (status == NO_ERROR) {
3942 desc->mSamplingRate = config.sample_rate;
3943 desc->mChannelMask = config.channel_mask;
3944 desc->mFormat = config.format;
3945 } else {
3946 output = AUDIO_IO_HANDLE_NONE;
3947 }
Eric Laurentd4692962014-05-05 18:13:44 -07003948 }
3949
Eric Laurentcf2c0212014-07-25 16:20:43 -07003950 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003951 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003952 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003953 sp<AudioPolicyMix> policyMix;
3954 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003955 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3956 address.string());
3957 }
François Gaffie036e1e92015-03-19 10:16:24 +01003958 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003959 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003960
Eric Laurent87ffa392015-05-22 10:32:38 -07003961 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3962 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003963 // no duplicated output for direct outputs and
3964 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003965 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003966
Eric Laurentd4692962014-05-05 18:13:44 -07003967 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003968 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003969
Eric Laurentd4692962014-05-05 18:13:44 -07003970 //TODO: configure audio effect output stage here
3971
3972 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003973 duplicatedOutput =
3974 mpClientInterface->openDuplicateOutput(output,
3975 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003976 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003977 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003978 sp<SwAudioOutputDescriptor> dupOutputDesc =
3979 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3980 dupOutputDesc->mOutput1 = mPrimaryOutput;
3981 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003982 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3983 dupOutputDesc->mFormat = desc->mFormat;
3984 dupOutputDesc->mChannelMask = desc->mChannelMask;
3985 dupOutputDesc->mLatency = desc->mLatency;
3986 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003987 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003988 } else {
3989 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003990 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003991 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003992 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003993 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003994 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003995 }
Eric Laurente552edb2014-03-10 17:42:56 -07003996 }
3997 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003998 } else {
3999 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004000 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004001 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004002 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004003 profiles.removeAt(profile_index);
4004 profile_index--;
4005 } else {
4006 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004007 // Load digital format info only for digital devices
4008 if (audio_device_is_digital(device)) {
4009 devDesc->importAudioPort(profile);
4010 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004011
François Gaffie53615e22015-03-19 09:24:12 +01004012 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004013 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4014 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004015 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004016 NULL/*patch handle*/, address.string());
4017 }
Eric Laurente552edb2014-03-10 17:42:56 -07004018 ALOGV("checkOutputsForDevice(): adding output %d", output);
4019 }
4020 }
4021
4022 if (profiles.isEmpty()) {
4023 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4024 return BAD_VALUE;
4025 }
Eric Laurentd4692962014-05-05 18:13:44 -07004026 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004027 // check if one opened output is not needed any more after disconnecting one device
4028 for (size_t i = 0; i < mOutputs.size(); i++) {
4029 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004030 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004031 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004032 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004033 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004034 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004035 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004036 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4037 mOutputs.keyAt(i));
4038 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004039 }
Eric Laurente552edb2014-03-10 17:42:56 -07004040 }
4041 }
Eric Laurentd4692962014-05-05 18:13:44 -07004042 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004043 for (size_t i = 0; i < mHwModules.size(); i++)
4044 {
4045 if (mHwModules[i]->mHandle == 0) {
4046 continue;
4047 }
4048 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4049 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004050 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004051 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004052 ALOGV("checkOutputsForDevice(): "
4053 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004054 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004055 }
4056 }
4057 }
4058 }
4059 return NO_ERROR;
4060}
4061
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004062status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004063 audio_policy_dev_state_t state,
4064 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004065 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004066{
Paul McLean9080a4c2015-06-18 08:24:02 -07004067 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004068 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004069
4070 if (audio_device_is_digital(device)) {
4071 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004072 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004073 }
4074
Eric Laurentd4692962014-05-05 18:13:44 -07004075 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4076 // first list already open inputs that can be routed to this device
4077 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4078 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004079 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004080 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4081 inputs.add(mInputs.keyAt(input_index));
4082 }
4083 }
4084
4085 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004086 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004087 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4088 {
4089 if (mHwModules[module_idx]->mHandle == 0) {
4090 continue;
4091 }
4092 for (size_t profile_index = 0;
4093 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4094 profile_index++)
4095 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004096 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4097
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004098 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004099 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004100 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004101 profiles.add(profile);
4102 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4103 profile_index, module_idx);
4104 }
Eric Laurentd4692962014-05-05 18:13:44 -07004105 }
4106 }
4107 }
4108
4109 if (profiles.isEmpty() && inputs.isEmpty()) {
4110 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4111 return BAD_VALUE;
4112 }
4113
4114 // open inputs for matching profiles if needed. Direct inputs are also opened to
4115 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4116 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4117
Eric Laurent1c333e22014-05-20 10:48:17 -07004118 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004119 // nothing to do if one input is already opened for this profile
4120 size_t input_index;
4121 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4122 desc = mInputs.valueAt(input_index);
4123 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004124 if (audio_device_is_digital(device)) {
4125 devDesc->importAudioPort(profile);
4126 }
Eric Laurentd4692962014-05-05 18:13:44 -07004127 break;
4128 }
4129 }
4130 if (input_index != mInputs.size()) {
4131 continue;
4132 }
4133
4134 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4135 desc = new AudioInputDescriptor(profile);
4136 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004137 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4138 config.sample_rate = desc->mSamplingRate;
4139 config.channel_mask = desc->mChannelMask;
4140 config.format = desc->mFormat;
4141 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004142 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004143 &input,
4144 &config,
4145 &desc->mDevice,
4146 address,
4147 AUDIO_SOURCE_MIC,
4148 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004149
Eric Laurentcf2c0212014-07-25 16:20:43 -07004150 if (status == NO_ERROR) {
4151 desc->mSamplingRate = config.sample_rate;
4152 desc->mChannelMask = config.channel_mask;
4153 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004154
Eric Laurentd4692962014-05-05 18:13:44 -07004155 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004156 char *param = audio_device_address_to_parameter(device, address);
4157 mpClientInterface->setParameters(input, String8(param));
4158 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004159 }
Phil Burk00eeb322016-03-31 12:41:00 -07004160 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004161 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004162 ALOGW("checkInputsForDevice() direct input missing param");
4163 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004164 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004165 }
4166
4167 if (input != 0) {
4168 addInput(input, desc);
4169 }
4170 } // endif input != 0
4171
Eric Laurentcf2c0212014-07-25 16:20:43 -07004172 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004173 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004174 profiles.removeAt(profile_index);
4175 profile_index--;
4176 } else {
4177 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004178 if (audio_device_is_digital(device)) {
4179 devDesc->importAudioPort(profile);
4180 }
Eric Laurentd4692962014-05-05 18:13:44 -07004181 ALOGV("checkInputsForDevice(): adding input %d", input);
4182 }
4183 } // end scan profiles
4184
4185 if (profiles.isEmpty()) {
4186 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4187 return BAD_VALUE;
4188 }
4189 } else {
4190 // Disconnect
4191 // check if one opened input is not needed any more after disconnecting one device
4192 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4193 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004194 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004195 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4196 mInputs.keyAt(input_index));
4197 inputs.add(mInputs.keyAt(input_index));
4198 }
4199 }
4200 // Clear any profiles associated with the disconnected device.
4201 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4202 if (mHwModules[module_index]->mHandle == 0) {
4203 continue;
4204 }
4205 for (size_t profile_index = 0;
4206 profile_index < mHwModules[module_index]->mInputProfiles.size();
4207 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004208 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004209 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004210 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004211 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004212 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004213 }
4214 }
4215 }
4216 } // end disconnect
4217
4218 return NO_ERROR;
4219}
4220
4221
Eric Laurente0720872014-03-11 09:30:41 -07004222void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004223{
4224 ALOGV("closeOutput(%d)", output);
4225
Eric Laurentc75307b2015-03-17 15:29:32 -07004226 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004227 if (outputDesc == NULL) {
4228 ALOGW("closeOutput() unknown output %d", output);
4229 return;
4230 }
François Gaffie036e1e92015-03-19 10:16:24 +01004231 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004232
Eric Laurente552edb2014-03-10 17:42:56 -07004233 // look for duplicated outputs connected to the output being removed.
4234 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004235 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004236 if (dupOutputDesc->isDuplicated() &&
4237 (dupOutputDesc->mOutput1 == outputDesc ||
4238 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004239 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004240 if (dupOutputDesc->mOutput1 == outputDesc) {
4241 outputDesc2 = dupOutputDesc->mOutput2;
4242 } else {
4243 outputDesc2 = dupOutputDesc->mOutput1;
4244 }
4245 // As all active tracks on duplicated output will be deleted,
4246 // and as they were also referenced on the other output, the reference
4247 // count for their stream type must be adjusted accordingly on
4248 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004249 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004251 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004252 }
4253 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4254 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4255
4256 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004257 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004258 }
4259 }
4260
Eric Laurent05b90f82014-08-27 15:32:29 -07004261 nextAudioPortGeneration();
4262
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004263 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004264 if (index >= 0) {
4265 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004266 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004267 mAudioPatches.removeItemsAt(index);
4268 mpClientInterface->onAudioPatchListUpdate();
4269 }
4270
Eric Laurente552edb2014-03-10 17:42:56 -07004271 AudioParameter param;
4272 param.add(String8("closing"), String8("true"));
4273 mpClientInterface->setParameters(output, param.toString());
4274
4275 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004276 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004277 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004278}
4279
4280void AudioPolicyManager::closeInput(audio_io_handle_t input)
4281{
4282 ALOGV("closeInput(%d)", input);
4283
4284 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4285 if (inputDesc == NULL) {
4286 ALOGW("closeInput() unknown input %d", input);
4287 return;
4288 }
4289
Eric Laurent6a94d692014-05-20 11:18:06 -07004290 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004291
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004292 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004293 if (index >= 0) {
4294 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004295 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004296 mAudioPatches.removeItemsAt(index);
4297 mpClientInterface->onAudioPatchListUpdate();
4298 }
4299
4300 mpClientInterface->closeInput(input);
4301 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004302}
4303
Eric Laurentc75307b2015-03-17 15:29:32 -07004304SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4305 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004306 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004307{
4308 SortedVector<audio_io_handle_t> outputs;
4309
4310 ALOGVV("getOutputsForDevice() device %04x", device);
4311 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004312 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004313 i, openOutputs.valueAt(i)->isDuplicated(),
4314 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004315 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4316 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4317 outputs.add(openOutputs.keyAt(i));
4318 }
4319 }
4320 return outputs;
4321}
4322
Eric Laurente0720872014-03-11 09:30:41 -07004323bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004324 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004325{
4326 if (outputs1.size() != outputs2.size()) {
4327 return false;
4328 }
4329 for (size_t i = 0; i < outputs1.size(); i++) {
4330 if (outputs1[i] != outputs2[i]) {
4331 return false;
4332 }
4333 }
4334 return true;
4335}
4336
Eric Laurente0720872014-03-11 09:30:41 -07004337void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004338{
4339 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4340 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4341 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4342 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4343
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004344 // also take into account external policy-related changes: add all outputs which are
4345 // associated with policies in the "before" and "after" output vectors
4346 ALOGVV("checkOutputForStrategy(): policy related outputs");
4347 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004348 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004349 if (desc != 0 && desc->mPolicyMix != NULL) {
4350 srcOutputs.add(desc->mIoHandle);
4351 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4352 }
4353 }
4354 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004355 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004356 if (desc != 0 && desc->mPolicyMix != NULL) {
4357 dstOutputs.add(desc->mIoHandle);
4358 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4359 }
4360 }
4361
Eric Laurente552edb2014-03-10 17:42:56 -07004362 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4363 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4364 strategy, srcOutputs[0], dstOutputs[0]);
4365 // mute strategy while moving tracks from one output to another
4366 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004367 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004368 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004369 setStrategyMute(strategy, true, desc);
4370 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004371 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004372 sp<AudioSourceDescriptor> source =
4373 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4374 if (source != 0){
4375 connectAudioSource(source);
4376 }
Eric Laurente552edb2014-03-10 17:42:56 -07004377 }
4378
4379 // Move effects associated to this strategy from previous output to new output
4380 if (strategy == STRATEGY_MEDIA) {
4381 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4382 SortedVector<audio_io_handle_t> moved;
4383 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004384 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4385 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4386 effectDesc->mIo != fxOutput) {
4387 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004388 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4389 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004390 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004391 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004392 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004393 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004394 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004395 }
4396 }
4397 }
4398 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004399 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004400 if (getStrategy((audio_stream_type_t)i) == strategy) {
4401 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004402 }
4403 }
4404 }
4405}
4406
Eric Laurente0720872014-03-11 09:30:41 -07004407void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004408{
François Gaffie2110e042015-03-24 08:41:51 +01004409 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004410 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004411 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004412 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004413 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004414 checkOutputForStrategy(STRATEGY_SONIFICATION);
4415 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004416 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004417 checkOutputForStrategy(STRATEGY_MEDIA);
4418 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004419 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004420}
4421
Eric Laurente0720872014-03-11 09:30:41 -07004422void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004423{
François Gaffie53615e22015-03-19 09:24:12 +01004424 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004425 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004426 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004427 return;
4428 }
4429
Eric Laurent3a4311c2014-03-17 12:00:47 -07004430 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004431 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4432 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4433 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004434
4435 // if suspended, restore A2DP output if:
4436 // ((SCO device is NOT connected) ||
4437 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4438 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004439 //
Eric Laurentf732e072016-08-03 19:30:28 -07004440 // if not suspended, suspend A2DP output if:
4441 // (SCO device is connected) &&
4442 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4443 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004444 //
4445 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004446 if (!isScoConnected ||
4447 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4448 AUDIO_POLICY_FORCE_BT_SCO) &&
4449 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4450 AUDIO_POLICY_FORCE_BT_SCO) &&
4451 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004452 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004453
4454 mpClientInterface->restoreOutput(a2dpOutput);
4455 mA2dpSuspended = false;
4456 }
4457 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004458 if (isScoConnected &&
4459 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4460 AUDIO_POLICY_FORCE_BT_SCO) ||
4461 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4462 AUDIO_POLICY_FORCE_BT_SCO) ||
4463 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004464 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004465
4466 mpClientInterface->suspendOutput(a2dpOutput);
4467 mA2dpSuspended = true;
4468 }
4469 }
4470}
4471
Eric Laurentc75307b2015-03-17 15:29:32 -07004472audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4473 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004474{
4475 audio_devices_t device = AUDIO_DEVICE_NONE;
4476
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004477 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004478 if (index >= 0) {
4479 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4480 if (patchDesc->mUid != mUidCached) {
4481 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004482 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 return outputDesc->device();
4484 }
4485 }
4486
Eric Laurente552edb2014-03-10 17:42:56 -07004487 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004488 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004489 // use device for strategy enforced audible
4490 // 2: we are in call or the strategy phone is active on the output:
4491 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004492 // 3: the strategy for enforced audible is active but not enforced on the output:
4493 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004494 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004495 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004496 // 5: the strategy accessibility is active on the output:
4497 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004498 // 6: the strategy "respectful" sonification is active on the output:
4499 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004500 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004501 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004502 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004503 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004504 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004505 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004506 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004507 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004508 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4509 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004510 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004511 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004512 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004513 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004514 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004515 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004516 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4517 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004518 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004519 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004520 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004521 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004522 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004523 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004524 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004525 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004526 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004527 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004528 }
4529
Eric Laurent1c333e22014-05-20 10:48:17 -07004530 ALOGV("getNewOutputDevice() selected device %x", device);
4531 return device;
4532}
4533
Eric Laurentfb66dd92016-01-28 18:32:03 -08004534audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004535{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004536 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004537
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004538 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004539 if (index >= 0) {
4540 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4541 if (patchDesc->mUid != mUidCached) {
4542 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004543 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 return inputDesc->mDevice;
4545 }
4546 }
4547
Eric Laurentfb66dd92016-01-28 18:32:03 -08004548 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4549 if (isInCall()) {
4550 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4551 } else if (source != AUDIO_SOURCE_DEFAULT) {
4552 device = getDeviceAndMixForInputSource(source);
4553 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004554
Eric Laurente552edb2014-03-10 17:42:56 -07004555 return device;
4556}
4557
Eric Laurent794fde22016-03-11 09:50:45 -08004558bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4559 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004560 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004561}
4562
Eric Laurente0720872014-03-11 09:30:41 -07004563uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004564 return (uint32_t)getStrategy(stream);
4565}
4566
Eric Laurente0720872014-03-11 09:30:41 -07004567audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004568 // By checking the range of stream before calling getStrategy, we avoid
4569 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4570 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004571 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004572 return AUDIO_DEVICE_NONE;
4573 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004574 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004575 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4576 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004577 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004578 }
Eric Laurent794fde22016-03-11 09:50:45 -08004579 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004580 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004581 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004582 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4583 for (size_t i = 0; i < outputs.size(); i++) {
4584 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004585 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004586 curDevices |= outputDesc->device();
4587 }
4588 }
4589 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004590 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004591
4592 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4593 and doesn't really need to.*/
4594 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4595 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4596 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4597 }
Eric Laurente552edb2014-03-10 17:42:56 -07004598 return devices;
4599}
4600
François Gaffie2110e042015-03-24 08:41:51 +01004601routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4602{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004603 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004604 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004605}
4606
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004607uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4608 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004609 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4610 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4611 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004612 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4613 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4614 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004615 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004616 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004617}
4618
Eric Laurente0720872014-03-11 09:30:41 -07004619void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004620 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004621 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004622 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4623 updateDevicesAndOutputs();
4624 break;
4625 default:
4626 break;
4627 }
4628}
4629
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004630uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004631
4632 // skip beacon mute management if a dedicated TTS output is available
4633 if (mTtsOutputAvailable) {
4634 return 0;
4635 }
4636
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004637 switch(event) {
4638 case STARTING_OUTPUT:
4639 mBeaconMuteRefCount++;
4640 break;
4641 case STOPPING_OUTPUT:
4642 if (mBeaconMuteRefCount > 0) {
4643 mBeaconMuteRefCount--;
4644 }
4645 break;
4646 case STARTING_BEACON:
4647 mBeaconPlayingRefCount++;
4648 break;
4649 case STOPPING_BEACON:
4650 if (mBeaconPlayingRefCount > 0) {
4651 mBeaconPlayingRefCount--;
4652 }
4653 break;
4654 }
4655
4656 if (mBeaconMuteRefCount > 0) {
4657 // any playback causes beacon to be muted
4658 return setBeaconMute(true);
4659 } else {
4660 // no other playback: unmute when beacon starts playing, mute when it stops
4661 return setBeaconMute(mBeaconPlayingRefCount == 0);
4662 }
4663}
4664
4665uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4666 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4667 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4668 // keep track of muted state to avoid repeating mute/unmute operations
4669 if (mBeaconMuted != mute) {
4670 // mute/unmute AUDIO_STREAM_TTS on all outputs
4671 ALOGV("\t muting %d", mute);
4672 uint32_t maxLatency = 0;
4673 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004674 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004675 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004676 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004677 0 /*delay*/, AUDIO_DEVICE_NONE);
4678 const uint32_t latency = desc->latency() * 2;
4679 if (latency > maxLatency) {
4680 maxLatency = latency;
4681 }
4682 }
4683 mBeaconMuted = mute;
4684 return maxLatency;
4685 }
4686 return 0;
4687}
4688
Eric Laurente0720872014-03-11 09:30:41 -07004689audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004690 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004691{
Paul McLeanaa981192015-03-21 09:55:15 -07004692 // Routing
4693 // see if we have an explicit route
4694 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4695 // (getStrategy(stream)).
4696 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4697 // and activity count is non-zero
4698 // the device = the device from the descriptor in the RouteMap, and exit.
4699 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4700 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004701 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4702 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004703 return route->mDeviceDescriptor->type();
4704 }
4705 }
4706
Eric Laurente552edb2014-03-10 17:42:56 -07004707 if (fromCache) {
4708 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4709 strategy, mDeviceForStrategy[strategy]);
4710 return mDeviceForStrategy[strategy];
4711 }
François Gaffie2110e042015-03-24 08:41:51 +01004712 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004713}
4714
Eric Laurente0720872014-03-11 09:30:41 -07004715void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004716{
4717 for (int i = 0; i < NUM_STRATEGIES; i++) {
4718 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4719 }
4720 mPreviousOutputs = mOutputs;
4721}
4722
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004723uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004724 audio_devices_t prevDevice,
4725 uint32_t delayMs)
4726{
4727 // mute/unmute strategies using an incompatible device combination
4728 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4729 // if unmuting, unmute only after the specified delay
4730 if (outputDesc->isDuplicated()) {
4731 return 0;
4732 }
4733
4734 uint32_t muteWaitMs = 0;
4735 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004736 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004737
4738 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4739 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004740 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004741 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4742 bool doMute = false;
4743
4744 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4745 doMute = true;
4746 outputDesc->mStrategyMutedByDevice[i] = true;
4747 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4748 doMute = true;
4749 outputDesc->mStrategyMutedByDevice[i] = false;
4750 }
Eric Laurent99401132014-05-07 19:48:15 -07004751 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004752 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004753 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004754 // skip output if it does not share any device with current output
4755 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4756 == AUDIO_DEVICE_NONE) {
4757 continue;
4758 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004759 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004760 mute ? "muting" : "unmuting", i, curDevice);
4761 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004762 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004763 if (mute) {
4764 // FIXME: should not need to double latency if volume could be applied
4765 // immediately by the audioflinger mixer. We must account for the delay
4766 // between now and the next time the audioflinger thread for this output
4767 // will process a buffer (which corresponds to one buffer size,
4768 // usually 1/2 or 1/4 of the latency).
4769 if (muteWaitMs < desc->latency() * 2) {
4770 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004771 }
4772 }
4773 }
4774 }
4775 }
4776 }
4777
Eric Laurent99401132014-05-07 19:48:15 -07004778 // temporary mute output if device selection changes to avoid volume bursts due to
4779 // different per device volumes
4780 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004781 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4782 // temporary mute duration is conservatively set to 4 times the reported latency
4783 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4784 if (muteWaitMs < tempMuteWaitMs) {
4785 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004786 }
Eric Laurentdc462862016-07-19 12:29:53 -07004787
Eric Laurent99401132014-05-07 19:48:15 -07004788 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004789 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004790 // make sure that we do not start the temporary mute period too early in case of
4791 // delayed device change
4792 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004793 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004794 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004795 }
4796 }
4797 }
4798
Eric Laurente552edb2014-03-10 17:42:56 -07004799 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4800 if (muteWaitMs > delayMs) {
4801 muteWaitMs -= delayMs;
4802 usleep(muteWaitMs * 1000);
4803 return muteWaitMs;
4804 }
4805 return 0;
4806}
4807
Eric Laurentc75307b2015-03-17 15:29:32 -07004808uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004809 audio_devices_t device,
4810 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004812 audio_patch_handle_t *patchHandle,
4813 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004814{
Eric Laurentc75307b2015-03-17 15:29:32 -07004815 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004816 AudioParameter param;
4817 uint32_t muteWaitMs;
4818
4819 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004820 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4821 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004822 return muteWaitMs;
4823 }
4824 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4825 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004826 if ((device != AUDIO_DEVICE_NONE) &&
4827 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004828 return 0;
4829 }
4830
4831 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004832 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004833
4834 audio_devices_t prevDevice = outputDesc->mDevice;
4835
Paul McLeanaa981192015-03-21 09:55:15 -07004836 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004837
4838 if (device != AUDIO_DEVICE_NONE) {
4839 outputDesc->mDevice = device;
4840 }
4841 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4842
4843 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004844 // the requested device is AUDIO_DEVICE_NONE
4845 // OR the requested device is the same as current device
4846 // AND force is not specified
4847 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004848 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004849 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4850 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004851 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004852 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004853 return muteWaitMs;
4854 }
4855
4856 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004857
Eric Laurente552edb2014-03-10 17:42:56 -07004858 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004859 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004860 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004861 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004862 DeviceVector deviceList;
4863 if ((address == NULL) || (strlen(address) == 0)) {
4864 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4865 } else {
4866 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4867 }
4868
Eric Laurent1c333e22014-05-20 10:48:17 -07004869 if (!deviceList.isEmpty()) {
4870 struct audio_patch patch;
4871 outputDesc->toAudioPortConfig(&patch.sources[0]);
4872 patch.num_sources = 1;
4873 patch.num_sinks = 0;
4874 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4875 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004876 patch.num_sinks++;
4877 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 ssize_t index;
4879 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4880 index = mAudioPatches.indexOfKey(*patchHandle);
4881 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004882 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 }
4884 sp< AudioPatch> patchDesc;
4885 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4886 if (index >= 0) {
4887 patchDesc = mAudioPatches.valueAt(index);
4888 afPatchHandle = patchDesc->mAfPatchHandle;
4889 }
4890
Eric Laurent1c333e22014-05-20 10:48:17 -07004891 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004892 &afPatchHandle,
4893 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004894 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4895 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004897 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004898 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004899 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 addAudioPatch(patchDesc->mHandle, patchDesc);
4901 } else {
4902 patchDesc->mPatch = patch;
4903 }
4904 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004905 if (patchHandle) {
4906 *patchHandle = patchDesc->mHandle;
4907 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004908 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004910 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004911 }
4912 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004913
4914 // inform all input as well
4915 for (size_t i = 0; i < mInputs.size(); i++) {
4916 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004917 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004918 AudioParameter inputCmd = AudioParameter();
4919 ALOGV("%s: inform input %d of device:%d", __func__,
4920 inputDescriptor->mIoHandle, device);
4921 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4922 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4923 inputCmd.toString(),
4924 delayMs);
4925 }
4926 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004927 }
Eric Laurente552edb2014-03-10 17:42:56 -07004928
4929 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004930 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004931
4932 return muteWaitMs;
4933}
4934
Eric Laurentc75307b2015-03-17 15:29:32 -07004935status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 int delayMs,
4937 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004938{
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 ssize_t index;
4940 if (patchHandle) {
4941 index = mAudioPatches.indexOfKey(*patchHandle);
4942 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004943 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004944 }
4945 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004946 return INVALID_OPERATION;
4947 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004948 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4949 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004950 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004951 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004952 removeAudioPatch(patchDesc->mHandle);
4953 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004954 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004955 return status;
4956}
4957
4958status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4959 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 bool force,
4961 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004962{
4963 status_t status = NO_ERROR;
4964
Eric Laurent1f2f2232014-06-02 12:01:23 -07004965 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4967 inputDesc->mDevice = device;
4968
4969 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4970 if (!deviceList.isEmpty()) {
4971 struct audio_patch patch;
4972 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004973 // AUDIO_SOURCE_HOTWORD is for internal use only:
4974 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004975 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004976 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004977 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4978 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004979 patch.num_sinks = 1;
4980 //only one input device for now
4981 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004982 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 ssize_t index;
4984 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4985 index = mAudioPatches.indexOfKey(*patchHandle);
4986 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004987 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 }
4989 sp< AudioPatch> patchDesc;
4990 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4991 if (index >= 0) {
4992 patchDesc = mAudioPatches.valueAt(index);
4993 afPatchHandle = patchDesc->mAfPatchHandle;
4994 }
4995
Eric Laurent1c333e22014-05-20 10:48:17 -07004996 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004998 0);
4999 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005000 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005001 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005003 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 addAudioPatch(patchDesc->mHandle, patchDesc);
5005 } else {
5006 patchDesc->mPatch = patch;
5007 }
5008 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 if (patchHandle) {
5010 *patchHandle = patchDesc->mHandle;
5011 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005012 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005014 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005015 }
5016 }
5017 }
5018 return status;
5019}
5020
Eric Laurent6a94d692014-05-20 11:18:06 -07005021status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5022 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005023{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005024 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005025 ssize_t index;
5026 if (patchHandle) {
5027 index = mAudioPatches.indexOfKey(*patchHandle);
5028 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005029 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 }
5031 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005032 return INVALID_OPERATION;
5033 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5035 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005036 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005037 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 removeAudioPatch(patchDesc->mHandle);
5039 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005040 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005041 return status;
5042}
5043
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005044sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005045 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005046 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005047 audio_format_t& format,
5048 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005049 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005050{
5051 // Choose an input profile based on the requested capture parameters: select the first available
5052 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005053 //
5054 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5055 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005056
5057 for (size_t i = 0; i < mHwModules.size(); i++)
5058 {
5059 if (mHwModules[i]->mHandle == 0) {
5060 continue;
5061 }
5062 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5063 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005064 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005065 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005066 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005067 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005068 format,
5069 &format /*updatedFormat*/,
5070 channelMask,
5071 &channelMask /*updatedChannelMask*/,
5072 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005073
Eric Laurente552edb2014-03-10 17:42:56 -07005074 return profile;
5075 }
5076 }
5077 }
5078 return NULL;
5079}
5080
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005081
5082audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005083 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005084{
François Gaffie036e1e92015-03-19 10:16:24 +01005085 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5086 audio_devices_t selectedDeviceFromMix =
5087 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005088
François Gaffie036e1e92015-03-19 10:16:24 +01005089 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5090 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005091 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005092 return getDeviceForInputSource(inputSource);
5093}
5094
5095audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5096{
Paul McLean466dc8e2015-04-17 13:15:36 -06005097 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5098 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005099 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005100 return route->mDeviceDescriptor->type();
5101 }
5102 }
5103
5104 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005105}
5106
Eric Laurente0720872014-03-11 09:30:41 -07005107float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005108 int index,
5109 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005110{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005111 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005112
5113 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5114 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5115 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5116 // the ringtone volume
5117 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5118 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5119 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5120 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5121 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5122 }
5123
Eric Laurente552edb2014-03-10 17:42:56 -07005124 // if a headset is connected, apply the following rules to ring tones and notifications
5125 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005126 // - always attenuate notifications volume by 6dB
5127 // - attenuate ring tones volume by 6dB unless music is not playing and
5128 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005129 // - if music is playing, always limit the volume to current music volume,
5130 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005131 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005132 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5133 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5134 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5135 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5136 ((stream_strategy == STRATEGY_SONIFICATION)
5137 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005138 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005139 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005140 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005141 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005142 // when the phone is ringing we must consider that music could have been paused just before
5143 // by the music application and behave as if music was active if the last music track was
5144 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005145 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005146 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005147 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005148 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005149 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005150 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5151 musicDevice),
5152 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005153 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5154 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005155 if (volumeDB > minVolDB) {
5156 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005157 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005158 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005159 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5160 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5161 // on A2DP, also ensure notification volume is not too low compared to media when
5162 // intended to be played
5163 if ((volumeDB > -96.0f) &&
5164 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5165 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5166 stream, device,
5167 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5168 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5169 }
5170 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005171 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5172 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005173 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005174 }
5175 }
5176
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005177 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005178}
5179
Eric Laurente0720872014-03-11 09:30:41 -07005180status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005181 int index,
5182 const sp<AudioOutputDescriptor>& outputDesc,
5183 audio_devices_t device,
5184 int delayMs,
5185 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005186{
Eric Laurente552edb2014-03-10 17:42:56 -07005187 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005188 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005189 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005190 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005191 return NO_ERROR;
5192 }
François Gaffie2110e042015-03-24 08:41:51 +01005193 audio_policy_forced_cfg_t forceUseForComm =
5194 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005195 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005196 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5197 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005198 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005199 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005200 return INVALID_OPERATION;
5201 }
5202
Eric Laurentc75307b2015-03-17 15:29:32 -07005203 if (device == AUDIO_DEVICE_NONE) {
5204 device = outputDesc->device();
5205 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005206
Eric Laurentffbc80f2015-03-18 18:30:19 -07005207 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005208 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005209 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005210 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005211
Eric Laurentffbc80f2015-03-18 18:30:19 -07005212 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005213
Eric Laurent3b73df72014-03-11 09:06:29 -07005214 if (stream == AUDIO_STREAM_VOICE_CALL ||
5215 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005216 float voiceVolume;
5217 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005218 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005219 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005220 } else {
5221 voiceVolume = 1.0;
5222 }
5223
Eric Laurent18fba842016-03-31 14:41:26 -07005224 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005225 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5226 mLastVoiceVolume = voiceVolume;
5227 }
5228 }
5229
5230 return NO_ERROR;
5231}
5232
Eric Laurentc75307b2015-03-17 15:29:32 -07005233void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5234 audio_devices_t device,
5235 int delayMs,
5236 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005237{
Eric Laurentc75307b2015-03-17 15:29:32 -07005238 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005239
Eric Laurent794fde22016-03-11 09:50:45 -08005240 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005241 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005242 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005243 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005244 device,
5245 delayMs,
5246 force);
5247 }
5248}
5249
Eric Laurente0720872014-03-11 09:30:41 -07005250void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005251 bool on,
5252 const sp<AudioOutputDescriptor>& outputDesc,
5253 int delayMs,
5254 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005255{
Eric Laurent72249d52015-06-08 11:12:15 -07005256 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5257 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005258 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005259 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005260 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005261 }
5262 }
5263}
5264
Eric Laurente0720872014-03-11 09:30:41 -07005265void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005266 bool on,
5267 const sp<AudioOutputDescriptor>& outputDesc,
5268 int delayMs,
5269 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005270{
Eric Laurente552edb2014-03-10 17:42:56 -07005271 if (device == AUDIO_DEVICE_NONE) {
5272 device = outputDesc->device();
5273 }
5274
Eric Laurentc75307b2015-03-17 15:29:32 -07005275 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5276 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005277
5278 if (on) {
5279 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005280 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005281 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005282 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005283 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005284 }
5285 }
5286 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5287 outputDesc->mMuteCount[stream]++;
5288 } else {
5289 if (outputDesc->mMuteCount[stream] == 0) {
5290 ALOGV("setStreamMute() unmuting non muted stream!");
5291 return;
5292 }
5293 if (--outputDesc->mMuteCount[stream] == 0) {
5294 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005295 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005296 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005297 device,
5298 delayMs);
5299 }
5300 }
5301}
5302
Eric Laurente0720872014-03-11 09:30:41 -07005303void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005304 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005305{
Eric Laurent87ffa392015-05-22 10:32:38 -07005306 if(!hasPrimaryOutput()) {
5307 return;
5308 }
5309
Eric Laurente552edb2014-03-10 17:42:56 -07005310 // if the stream pertains to sonification strategy and we are in call we must
5311 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5312 // in the device used for phone strategy and play the tone if the selected device does not
5313 // interfere with the device used for phone strategy
5314 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5315 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005316 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005317 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5318 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005319 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005320 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5321 stream, starting, outputDesc->mDevice, stateChange);
5322 if (outputDesc->mRefCount[stream]) {
5323 int muteCount = 1;
5324 if (stateChange) {
5325 muteCount = outputDesc->mRefCount[stream];
5326 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005327 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005328 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5329 for (int i = 0; i < muteCount; i++) {
5330 setStreamMute(stream, starting, mPrimaryOutput);
5331 }
5332 } else {
5333 ALOGV("handleIncallSonification() high visibility");
5334 if (outputDesc->device() &
5335 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5336 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5337 for (int i = 0; i < muteCount; i++) {
5338 setStreamMute(stream, starting, mPrimaryOutput);
5339 }
5340 }
5341 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005342 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5343 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005344 } else {
5345 mpClientInterface->stopTone();
5346 }
5347 }
5348 }
5349 }
5350}
5351
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005352audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5353{
5354 // flags to stream type mapping
5355 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5356 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5357 }
5358 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5359 return AUDIO_STREAM_BLUETOOTH_SCO;
5360 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005361 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5362 return AUDIO_STREAM_TTS;
5363 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005364
5365 // usage to stream type mapping
5366 switch (attr->usage) {
5367 case AUDIO_USAGE_MEDIA:
5368 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005369 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005370 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5371 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005372 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5373 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005374 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5375 return AUDIO_STREAM_SYSTEM;
5376 case AUDIO_USAGE_VOICE_COMMUNICATION:
5377 return AUDIO_STREAM_VOICE_CALL;
5378
5379 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5380 return AUDIO_STREAM_DTMF;
5381
5382 case AUDIO_USAGE_ALARM:
5383 return AUDIO_STREAM_ALARM;
5384 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5385 return AUDIO_STREAM_RING;
5386
5387 case AUDIO_USAGE_NOTIFICATION:
5388 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5389 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5390 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5391 case AUDIO_USAGE_NOTIFICATION_EVENT:
5392 return AUDIO_STREAM_NOTIFICATION;
5393
5394 case AUDIO_USAGE_UNKNOWN:
5395 default:
5396 return AUDIO_STREAM_MUSIC;
5397 }
5398}
Eric Laurente83b55d2014-11-14 10:06:21 -08005399
François Gaffie53615e22015-03-19 09:24:12 +01005400bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5401{
Eric Laurente83b55d2014-11-14 10:06:21 -08005402 // has flags that map to a strategy?
5403 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5404 return true;
5405 }
5406
5407 // has known usage?
5408 switch (paa->usage) {
5409 case AUDIO_USAGE_UNKNOWN:
5410 case AUDIO_USAGE_MEDIA:
5411 case AUDIO_USAGE_VOICE_COMMUNICATION:
5412 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5413 case AUDIO_USAGE_ALARM:
5414 case AUDIO_USAGE_NOTIFICATION:
5415 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5416 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5417 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5418 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5419 case AUDIO_USAGE_NOTIFICATION_EVENT:
5420 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5421 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5422 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5423 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005424 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005425 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005426 break;
5427 default:
5428 return false;
5429 }
5430 return true;
5431}
5432
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005433bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005434 routing_strategy strategy, uint32_t inPastMs,
5435 nsecs_t sysTime) const
5436{
5437 if ((sysTime == 0) && (inPastMs != 0)) {
5438 sysTime = systemTime();
5439 }
Eric Laurent794fde22016-03-11 09:50:45 -08005440 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005441 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5442 (NUM_STRATEGIES == strategy)) &&
5443 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5444 return true;
5445 }
5446 }
5447 return false;
5448}
5449
François Gaffie2110e042015-03-24 08:41:51 +01005450audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5451{
5452 return mEngine->getForceUse(usage);
5453}
5454
5455bool AudioPolicyManager::isInCall()
5456{
5457 return isStateInCall(mEngine->getPhoneState());
5458}
5459
5460bool AudioPolicyManager::isStateInCall(int state)
5461{
5462 return is_state_in_call(state);
5463}
5464
Eric Laurentd60560a2015-04-10 11:31:20 -07005465void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5466{
5467 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5468 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5469 if (sourceDesc->mDevice->equals(deviceDesc)) {
5470 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5471 stopAudioSource(sourceDesc->getHandle());
5472 }
5473 }
5474
5475 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5476 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5477 bool release = false;
5478 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5479 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5480 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5481 source->ext.device.type == deviceDesc->type()) {
5482 release = true;
5483 }
5484 }
5485 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5486 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5487 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5488 sink->ext.device.type == deviceDesc->type()) {
5489 release = true;
5490 }
5491 }
5492 if (release) {
5493 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5494 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5495 }
5496 }
5497}
5498
Phil Burk09bc4612016-02-24 15:58:15 -08005499// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005500void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5501 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005502 // TODO Set this based on Config properties.
5503 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005504
5505 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5506 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005507 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005508
5509 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005510 bool supportsAC3 = false;
5511 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005512 bool supportsIEC61937 = false;
5513 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5514 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005515 switch (format) {
5516 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005517 supportsAC3 = true;
5518 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005519 case AUDIO_FORMAT_E_AC3:
5520 case AUDIO_FORMAT_DTS:
5521 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005522 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005523 break;
5524 case AUDIO_FORMAT_IEC61937:
5525 supportsIEC61937 = true;
5526 break;
5527 default:
5528 break;
5529 }
5530 }
Phil Burk09bc4612016-02-24 15:58:15 -08005531
5532 // Modify formats based on surround preferences.
5533 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005534 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5535 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5536 // Remove surround sound related formats.
5537 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5538 audio_format_t format = formats[formatIndex];
5539 switch(format) {
5540 case AUDIO_FORMAT_AC3:
5541 case AUDIO_FORMAT_E_AC3:
5542 case AUDIO_FORMAT_DTS:
5543 case AUDIO_FORMAT_DTS_HD:
5544 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005545 formats.removeAt(formatIndex);
5546 break;
5547 default:
5548 formatIndex++; // keep it
5549 break;
5550 }
Phil Burk09bc4612016-02-24 15:58:15 -08005551 }
Phil Burk07ac1142016-03-25 13:39:29 -07005552 supportsAC3 = false;
5553 supportsOtherSurround = false;
5554 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005555 }
Phil Burk07ac1142016-03-25 13:39:29 -07005556 } else { // AUTO or ALWAYS
5557 // Most TVs support AC3 even if they do not report it in the EDID.
5558 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5559 && !supportsAC3) {
5560 formats.add(AUDIO_FORMAT_AC3);
5561 supportsAC3 = true;
5562 }
5563
5564 // If ALWAYS, add support for raw surround formats if all are missing.
5565 // This assumes that if any of these formats are reported by the HAL
5566 // then the report is valid and should not be modified.
5567 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5568 && !supportsOtherSurround) {
5569 formats.add(AUDIO_FORMAT_E_AC3);
5570 formats.add(AUDIO_FORMAT_DTS);
5571 formats.add(AUDIO_FORMAT_DTS_HD);
5572 supportsOtherSurround = true;
5573 }
5574
5575 // Add support for IEC61937 if any raw surround supported.
5576 // The HAL could do this but add it here, just in case.
5577 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5578 formats.add(AUDIO_FORMAT_IEC61937);
5579 supportsIEC61937 = true;
5580 }
Phil Burk09bc4612016-02-24 15:58:15 -08005581 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005582}
5583
5584// Modify the list of channel masks supported.
5585void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5586 ChannelsVector &channelMasks = *channelMasksPtr;
5587 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5588 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5589
5590 // If NEVER, then remove support for channelMasks > stereo.
5591 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5592 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5593 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5594 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5595 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5596 channelMasks.removeAt(maskIndex);
5597 } else {
5598 maskIndex++;
5599 }
5600 }
5601 // If ALWAYS, then make sure we at least support 5.1
5602 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5603 bool supports5dot1 = false;
5604 // Are there any channel masks that can be considered "surround"?
5605 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5606 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5607 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5608 supports5dot1 = true;
5609 break;
5610 }
5611 }
5612 // If not then add 5.1 support.
5613 if (!supports5dot1) {
5614 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5615 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5616 }
Phil Burk09bc4612016-02-24 15:58:15 -08005617 }
5618}
5619
Phil Burk00eeb322016-03-31 12:41:00 -07005620void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5621 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005622 AudioProfileVector &profiles)
5623{
5624 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005625
François Gaffie112b0af2015-11-19 16:13:25 +01005626 // Format MUST be checked first to update the list of AudioProfile
5627 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005628 reply = mpClientInterface->getParameters(
5629 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005630 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005631 AudioParameter repliedParameters(reply);
5632 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005633 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005634 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5635 return;
5636 }
Phil Burk09bc4612016-02-24 15:58:15 -08005637 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005638 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005639 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005640 }
Phil Burk09bc4612016-02-24 15:58:15 -08005641 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005642 }
5643 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5644
Eric Laurent20eb3a42016-01-26 18:39:17 -08005645 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005646 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005647 ChannelsVector channelMasks;
5648 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005649 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005650 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005651
5652 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005653 reply = mpClientInterface->getParameters(
5654 ioHandle,
5655 requestedParameters.toString() + ";" +
5656 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005657 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005658 AudioParameter repliedParameters(reply);
5659 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005660 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005661 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005662 }
5663 }
5664 if (profiles.hasDynamicChannelsFor(format)) {
5665 reply = mpClientInterface->getParameters(ioHandle,
5666 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005667 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005668 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005669 AudioParameter repliedParameters(reply);
5670 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005671 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005672 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005673 if (device == AUDIO_DEVICE_OUT_HDMI) {
5674 filterSurroundChannelMasks(&channelMasks);
5675 }
François Gaffie112b0af2015-11-19 16:13:25 +01005676 }
5677 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005678 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005679 }
5680}
Eric Laurentd60560a2015-04-10 11:31:20 -07005681
Eric Laurente552edb2014-03-10 17:42:56 -07005682}; // namespace android