blob: f64c4f978ec3174ee7e897705bbc753df2d4df9c [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>
36#include <hardware/audio.h>
37#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
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 ?
73 AUDIO_PARAMETER_DEVICE_CONNECT : AUDIO_PARAMETER_DEVICE_DISCONNECT);
74 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
Eric Laurent87ffa392015-05-22 10:32:38 -0700388 if(!hasPrimaryOutput()) {
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 Laurent232f26f2016-02-17 18:06:27 -0800495 audio_io_handle_t activeInput = mInputs.getActiveInput();
496 if (activeInput != 0) {
497 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
498 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
499 //FIXME: consider all active sessions
500 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
501 audio_session_t activeSession = activeSessions.keyAt(0);
502 stopInput(activeInput, activeSession);
503 releaseInput(activeInput, activeSession);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700504 }
505 }
506
Eric Laurentc2730ba2014-07-20 15:47:07 -0700507 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700508 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700509 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
510 status);
511 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100512 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700513 mCallTxPatch->mAfPatchHandle = afPatchHandle;
514 mCallTxPatch->mUid = mUidCached;
515 }
516 }
Eric Laurentdc462862016-07-19 12:29:53 -0700517
518 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700519}
520
Eric Laurente0720872014-03-11 09:30:41 -0700521void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700522{
523 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100524 // store previous phone state for management of sonification strategy below
525 int oldState = mEngine->getPhoneState();
526
527 if (mEngine->setPhoneState(state) != NO_ERROR) {
528 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700529 return;
530 }
François Gaffie2110e042015-03-24 08:41:51 +0100531 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700532 // if leaving call state, handle special case of active streams
533 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700534 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700535 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800536 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700537 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700538 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800539
Eric Laurent63dea1d2015-07-02 17:10:28 -0700540 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800541 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700542 }
543
François Gaffie2110e042015-03-24 08:41:51 +0100544 /**
545 * Switching to or from incall state or switching between telephony and VoIP lead to force
546 * routing command.
547 */
548 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
549 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700550
551 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700552 checkA2dpSuspend();
553 checkOutputForAllStrategies();
554 updateDevicesAndOutputs();
555
Eric Laurente552edb2014-03-10 17:42:56 -0700556 int delayMs = 0;
557 if (isStateInCall(state)) {
558 nsecs_t sysTime = systemTime();
559 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700561 // mute media and sonification strategies and delay device switch by the largest
562 // latency of any output where either strategy is active.
563 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100564 if ((isStrategyActive(desc, STRATEGY_MEDIA,
565 SONIFICATION_HEADSET_MUSIC_DELAY,
566 sysTime) ||
567 isStrategyActive(desc, STRATEGY_SONIFICATION,
568 SONIFICATION_HEADSET_MUSIC_DELAY,
569 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700570 (delayMs < (int)desc->latency()*2)) {
571 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700572 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700573 setStrategyMute(STRATEGY_MEDIA, true, desc);
574 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700575 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
577 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700578 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
579 }
580 }
581
Eric Laurent87ffa392015-05-22 10:32:38 -0700582 if (hasPrimaryOutput()) {
583 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
584 // the device returned is not necessarily reachable via this output
585 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
586 // force routing command to audio hardware when ending call
587 // even if no device change is needed
588 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
589 rxDevice = mPrimaryOutput->device();
590 }
Eric Laurente552edb2014-03-10 17:42:56 -0700591
Eric Laurent87ffa392015-05-22 10:32:38 -0700592 if (state == AUDIO_MODE_IN_CALL) {
593 updateCallRouting(rxDevice, delayMs);
594 } else if (oldState == AUDIO_MODE_IN_CALL) {
595 if (mCallRxPatch != 0) {
596 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
597 mCallRxPatch.clear();
598 }
599 if (mCallTxPatch != 0) {
600 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
601 mCallTxPatch.clear();
602 }
603 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
604 } else {
605 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700607 }
Eric Laurente552edb2014-03-10 17:42:56 -0700608 // if entering in call state, handle special case of active streams
609 // pertaining to sonification strategy see handleIncallSonification()
610 if (isStateInCall(state)) {
611 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800612 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700613 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700614 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700615
616 // force reevaluating accessibility routing when call starts
617 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700618 }
619
620 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700621 if (state == AUDIO_MODE_RINGTONE &&
622 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700623 mLimitRingtoneVolume = true;
624 } else {
625 mLimitRingtoneVolume = false;
626 }
627}
628
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700629audio_mode_t AudioPolicyManager::getPhoneState() {
630 return mEngine->getPhoneState();
631}
632
Eric Laurente0720872014-03-11 09:30:41 -0700633void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700634 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700635{
François Gaffie2110e042015-03-24 08:41:51 +0100636 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700637
François Gaffie2110e042015-03-24 08:41:51 +0100638 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
639 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
640 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700641 }
François Gaffie2110e042015-03-24 08:41:51 +0100642 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
643 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
644 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700645
646 // check for device and output changes triggered by new force usage
647 checkA2dpSuspend();
648 checkOutputForAllStrategies();
649 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800650
Eric Laurentdc462862016-07-19 12:29:53 -0700651 //FIXME: workaround for truncated touch sounds
652 // to be removed when the problem is handled by system UI
653 uint32_t delayMs = 0;
654 uint32_t waitMs = 0;
655 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
656 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
657 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700658 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700659 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700660 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700661 }
Eric Laurente552edb2014-03-10 17:42:56 -0700662 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700663 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
664 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
665 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700666 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
667 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 }
Eric Laurente552edb2014-03-10 17:42:56 -0700669 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700670 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700671 }
672 }
673
Eric Laurent232f26f2016-02-17 18:06:27 -0800674 audio_io_handle_t activeInput = mInputs.getActiveInput();
675 if (activeInput != 0) {
676 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
677 audio_devices_t newDevice = getNewInputDevice(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700678 // Force new input selection if the new device can not be reached via current input
Eric Laurent232f26f2016-02-17 18:06:27 -0800679 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
680 setInputDevice(activeInput, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700681 } else {
Eric Laurent232f26f2016-02-17 18:06:27 -0800682 closeInput(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700683 }
Eric Laurente552edb2014-03-10 17:42:56 -0700684 }
Eric Laurente552edb2014-03-10 17:42:56 -0700685}
686
Eric Laurente0720872014-03-11 09:30:41 -0700687void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700688{
689 ALOGV("setSystemProperty() property %s, value %s", property, value);
690}
691
692// Find a direct output profile compatible with the parameters passed, even if the input flags do
693// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800694sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700695 audio_devices_t device,
696 uint32_t samplingRate,
697 audio_format_t format,
698 audio_channel_mask_t channelMask,
699 audio_output_flags_t flags)
700{
Eric Laurent861a6282015-05-18 15:40:16 -0700701 // only retain flags that will drive the direct output profile selection
702 // if explicitly requested
703 static const uint32_t kRelevantFlags =
704 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
705 flags =
706 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
707
708 sp<IOProfile> profile;
709
Eric Laurente552edb2014-03-10 17:42:56 -0700710 for (size_t i = 0; i < mHwModules.size(); i++) {
711 if (mHwModules[i]->mHandle == 0) {
712 continue;
713 }
714 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700715 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
716 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700717 samplingRate, NULL /*updatedSamplingRate*/,
718 format, NULL /*updatedFormat*/,
719 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700720 flags)) {
721 continue;
722 }
723 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100724 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700725 continue;
726 }
727 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100728 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 continue;
730 }
731 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100732 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700733 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700734 }
Eric Laurente552edb2014-03-10 17:42:56 -0700735 }
736 }
Eric Laurent861a6282015-05-18 15:40:16 -0700737 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700738}
739
Eric Laurente0720872014-03-11 09:30:41 -0700740audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100741 uint32_t samplingRate,
742 audio_format_t format,
743 audio_channel_mask_t channelMask,
744 audio_output_flags_t flags,
745 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700746{
Eric Laurent3b73df72014-03-11 09:06:29 -0700747 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700748 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
749 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
750 device, stream, samplingRate, format, channelMask, flags);
751
Eric Laurente83b55d2014-11-14 10:06:21 -0800752 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
753 stream, samplingRate,format, channelMask,
754 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700755}
756
Eric Laurente83b55d2014-11-14 10:06:21 -0800757status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
758 audio_io_handle_t *output,
759 audio_session_t session,
760 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700761 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800762 uint32_t samplingRate,
763 audio_format_t format,
764 audio_channel_mask_t channelMask,
765 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700766 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800767 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768{
Eric Laurente83b55d2014-11-14 10:06:21 -0800769 audio_attributes_t attributes;
770 if (attr != NULL) {
771 if (!isValidAttributes(attr)) {
772 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
773 attr->usage, attr->content_type, attr->flags,
774 attr->tags);
775 return BAD_VALUE;
776 }
777 attributes = *attr;
778 } else {
779 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
780 ALOGE("getOutputForAttr(): invalid stream type");
781 return BAD_VALUE;
782 }
783 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700784 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700785 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800786 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100787 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800788 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100789 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800790 }
François Gaffie036e1e92015-03-19 10:16:24 +0100791 *stream = streamTypefromAttributesInt(&attributes);
792 *output = desc->mIoHandle;
793 ALOGV("getOutputForAttr() returns output %d", *output);
794 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800795 }
796 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
797 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
798 return BAD_VALUE;
799 }
800
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700801 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
802 " session %d selectedDeviceId %d",
803 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
804 session, selectedDeviceId);
805
806 *stream = streamTypefromAttributesInt(&attributes);
807
808 // Explicit routing?
809 sp<DeviceDescriptor> deviceDesc;
810 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
811 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
812 deviceDesc = mAvailableOutputDevices[i];
813 break;
814 }
815 }
816 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700817
Eric Laurente83b55d2014-11-14 10:06:21 -0800818 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700819 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700820
Eric Laurente83b55d2014-11-14 10:06:21 -0800821 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700822 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
823 }
824
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700825 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700826 device, samplingRate, format, channelMask, flags);
827
Eric Laurente83b55d2014-11-14 10:06:21 -0800828 *output = getOutputForDevice(device, session, *stream,
829 samplingRate, format, channelMask,
830 flags, offloadInfo);
831 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700832 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800833 return INVALID_OPERATION;
834 }
Paul McLeanaa981192015-03-21 09:55:15 -0700835
Eric Laurente83b55d2014-11-14 10:06:21 -0800836 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700837}
838
839audio_io_handle_t AudioPolicyManager::getOutputForDevice(
840 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800841 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700842 audio_stream_type_t stream,
843 uint32_t samplingRate,
844 audio_format_t format,
845 audio_channel_mask_t channelMask,
846 audio_output_flags_t flags,
847 const audio_offload_info_t *offloadInfo)
848{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700849 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700850 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700851
Eric Laurente552edb2014-03-10 17:42:56 -0700852#ifdef AUDIO_POLICY_TEST
853 if (mCurOutput != 0) {
854 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
855 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
856
857 if (mTestOutputs[mCurOutput] == 0) {
858 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700859 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
860 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700861 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700862 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700863 outputDesc->mFlags =
864 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700865 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700866 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
867 config.sample_rate = mTestSamplingRate;
868 config.channel_mask = mTestChannels;
869 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700870 if (offloadInfo != NULL) {
871 config.offload_info = *offloadInfo;
872 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700873 status = mpClientInterface->openOutput(0,
874 &mTestOutputs[mCurOutput],
875 &config,
876 &outputDesc->mDevice,
877 String8(""),
878 &outputDesc->mLatency,
879 outputDesc->mFlags);
880 if (status == NO_ERROR) {
881 outputDesc->mSamplingRate = config.sample_rate;
882 outputDesc->mFormat = config.format;
883 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700884 AudioParameter outputCmd = AudioParameter();
885 outputCmd.addInt(String8("set_id"),mCurOutput);
886 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
887 addOutput(mTestOutputs[mCurOutput], outputDesc);
888 }
889 }
890 return mTestOutputs[mCurOutput];
891 }
892#endif //AUDIO_POLICY_TEST
893
894 // open a direct output if required by specified parameters
895 //force direct flag if offload flag is set: offloading implies a direct output stream
896 // and all common behaviors are driven by checking only the direct flag
897 // this should normally be set appropriately in the policy configuration file
898 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700899 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700900 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700901 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
902 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
903 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800904 // only allow deep buffering for music stream type
905 if (stream != AUDIO_STREAM_MUSIC) {
906 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700907 } else if (/* stream == AUDIO_STREAM_MUSIC && */
908 flags == AUDIO_OUTPUT_FLAG_NONE &&
909 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
910 // use DEEP_BUFFER as default output for music stream type
911 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800912 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700913 if (stream == AUDIO_STREAM_TTS) {
914 flags = AUDIO_OUTPUT_FLAG_TTS;
915 }
Eric Laurente552edb2014-03-10 17:42:56 -0700916
Eric Laurentb732cf52014-09-24 19:08:21 -0700917 sp<IOProfile> profile;
918
919 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700920 // and not explicitly requested
921 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800922 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700923 audio_channel_count_from_out_mask(channelMask) <= 2) {
924 goto non_direct_output;
925 }
926
Andy Hung2ddee192015-12-18 17:34:44 -0800927 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
928 // This prevents creating an offloaded track and tearing it down immediately after start
929 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700930 // FIXME: We should check the audio session here but we do not have it in this context.
931 // This may prevent offloading in rare situations where effects are left active by apps
932 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700933
Eric Laurente552edb2014-03-10 17:42:56 -0700934 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800935 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700936 profile = getProfileForDirectOutput(device,
937 samplingRate,
938 format,
939 channelMask,
940 (audio_output_flags_t)flags);
941 }
942
Eric Laurent1c333e22014-05-20 10:48:17 -0700943 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700944 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700945
946 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700947 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700948 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
949 outputDesc = desc;
950 // reuse direct output if currently open and configured with same parameters
951 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800952 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700953 (channelMask == outputDesc->mChannelMask)) {
954 outputDesc->mDirectOpenCount++;
955 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
956 return mOutputs.keyAt(i);
957 }
958 }
959 }
960 // close direct output if currently open and configured with different parameters
961 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700962 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700963 }
Eric Laurent861a6282015-05-18 15:40:16 -0700964
965 // if the selected profile is offloaded and no offload info was specified,
966 // create a default one
967 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100968 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700969 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
970 defaultOffloadInfo.sample_rate = samplingRate;
971 defaultOffloadInfo.channel_mask = channelMask;
972 defaultOffloadInfo.format = format;
973 defaultOffloadInfo.stream_type = stream;
974 defaultOffloadInfo.bit_rate = 0;
975 defaultOffloadInfo.duration_us = -1;
976 defaultOffloadInfo.has_video = true; // conservative
977 defaultOffloadInfo.is_streaming = true; // likely
978 offloadInfo = &defaultOffloadInfo;
979 }
980
Eric Laurentc75307b2015-03-17 15:29:32 -0700981 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700982 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700983 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700984 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700985 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
986 config.sample_rate = samplingRate;
987 config.channel_mask = channelMask;
988 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700989 if (offloadInfo != NULL) {
990 config.offload_info = *offloadInfo;
991 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700992 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700993 &output,
994 &config,
995 &outputDesc->mDevice,
996 String8(""),
997 &outputDesc->mLatency,
998 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700999
1000 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001001 if (status != NO_ERROR ||
1002 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001003 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001004 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001005 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1006 "format %d %d, channelMask %04x %04x", output, samplingRate,
1007 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1008 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001009 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001010 mpClientInterface->closeOutput(output);
1011 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001012 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001013 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001014 goto non_direct_output;
1015 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001016 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001018 outputDesc->mSamplingRate = config.sample_rate;
1019 outputDesc->mChannelMask = config.channel_mask;
1020 outputDesc->mFormat = config.format;
1021 outputDesc->mRefCount[stream] = 0;
1022 outputDesc->mStopTime[stream] = 0;
1023 outputDesc->mDirectOpenCount = 1;
1024
Eric Laurente552edb2014-03-10 17:42:56 -07001025 audio_io_handle_t srcOutput = getOutputForEffect();
1026 addOutput(output, outputDesc);
1027 audio_io_handle_t dstOutput = getOutputForEffect();
1028 if (dstOutput == output) {
1029 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1030 }
1031 mPreviousOutputs = mOutputs;
1032 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001033 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001034 return output;
1035 }
1036
Eric Laurentb732cf52014-09-24 19:08:21 -07001037non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001038
1039 // A request for HW A/V sync cannot fallback to a mixed output because time
1040 // stamps are embedded in audio data
1041 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1042 return AUDIO_IO_HANDLE_NONE;
1043 }
1044
Eric Laurente552edb2014-03-10 17:42:56 -07001045 // ignoring channel mask due to downmix capability in mixer
1046
1047 // open a non direct output
1048
1049 // for non direct outputs, only PCM is supported
1050 if (audio_is_linear_pcm(format)) {
1051 // get which output is suitable for the specified stream. The actual
1052 // routing change will happen when startOutput() will be called
1053 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1054
Eric Laurent8838a382014-09-08 16:44:28 -07001055 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1056 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1057 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001058 }
1059 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1060 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1061
Paul McLeanaa981192015-03-21 09:55:15 -07001062 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001063
1064 return output;
1065}
1066
Eric Laurente0720872014-03-11 09:30:41 -07001067audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001068 audio_output_flags_t flags,
1069 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001070{
1071 // select one output among several that provide a path to a particular device or set of
1072 // devices (the list was previously build by getOutputsForDevice()).
1073 // The priority is as follows:
1074 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001075 // 2: the output with the bit depth the closest to the requested one
1076 // 3: the primary output
1077 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001078
1079 if (outputs.size() == 0) {
1080 return 0;
1081 }
1082 if (outputs.size() == 1) {
1083 return outputs[0];
1084 }
1085
1086 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001087 audio_io_handle_t outputForFlags = 0;
1088 audio_io_handle_t outputForPrimary = 0;
1089 audio_io_handle_t outputForFormat = 0;
1090 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1091 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001092
1093 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001094 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001095 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001096 // if a valid format is specified, skip output if not compatible
1097 if (format != AUDIO_FORMAT_INVALID) {
1098 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001099 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001100 continue;
1101 }
1102 } else if (!audio_is_linear_pcm(format)) {
1103 continue;
1104 }
Eric Laurente6930022016-02-11 10:20:40 -08001105 if (AudioPort::isBetterFormatMatch(
1106 outputDesc->mFormat, bestFormat, format)) {
1107 outputForFormat = outputs[i];
1108 bestFormat = outputDesc->mFormat;
1109 }
Eric Laurent8838a382014-09-08 16:44:28 -07001110 }
1111
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001112 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001113 if (commonFlags >= maxCommonFlags) {
1114 if (commonFlags == maxCommonFlags) {
1115 if (AudioPort::isBetterFormatMatch(
1116 outputDesc->mFormat, bestFormatForFlags, format)) {
1117 outputForFlags = outputs[i];
1118 bestFormatForFlags = outputDesc->mFormat;
1119 }
1120 } else {
1121 outputForFlags = outputs[i];
1122 maxCommonFlags = commonFlags;
1123 bestFormatForFlags = outputDesc->mFormat;
1124 }
Eric Laurente552edb2014-03-10 17:42:56 -07001125 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1126 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001127 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001128 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001129 }
1130 }
1131 }
1132
Eric Laurente6930022016-02-11 10:20:40 -08001133 if (outputForFlags != 0) {
1134 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001135 }
Eric Laurente6930022016-02-11 10:20:40 -08001136 if (outputForFormat != 0) {
1137 return outputForFormat;
1138 }
1139 if (outputForPrimary != 0) {
1140 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001141 }
1142
1143 return outputs[0];
1144}
1145
Eric Laurente0720872014-03-11 09:30:41 -07001146status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001147 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001148 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001149{
Paul McLeanaa981192015-03-21 09:55:15 -07001150 ALOGV("startOutput() output %d, stream %d, session %d",
1151 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001152 ssize_t index = mOutputs.indexOfKey(output);
1153 if (index < 0) {
1154 ALOGW("startOutput() unknown output %d", output);
1155 return BAD_VALUE;
1156 }
1157
Eric Laurentc75307b2015-03-17 15:29:32 -07001158 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1159
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001160 // Routing?
1161 mOutputRoutes.incRouteActivity(session);
1162
Eric Laurentc75307b2015-03-17 15:29:32 -07001163 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001164 AudioMix *policyMix = NULL;
1165 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001166 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001167 policyMix = outputDesc->mPolicyMix;
1168 address = policyMix->mDeviceAddress.string();
1169 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1170 newDevice = policyMix->mDeviceType;
1171 } else {
1172 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1173 }
Eric Laurent493404d2015-04-21 15:07:36 -07001174 } else if (mOutputRoutes.hasRouteChanged(session)) {
1175 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001176 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001177 } else {
1178 newDevice = AUDIO_DEVICE_NONE;
1179 }
1180
1181 uint32_t delayMs = 0;
1182
Eric Laurentc40d9692016-04-13 19:14:13 -07001183 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001184
1185 if (status != NO_ERROR) {
1186 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001187 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001188 }
1189 // Automatically enable the remote submix input when output is started on a re routing mix
1190 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001191 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1192 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001193 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1194 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001195 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001196 "remote-submix");
1197 }
1198
1199 if (delayMs != 0) {
1200 usleep(delayMs * 1000);
1201 }
1202
1203 return status;
1204}
1205
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001206status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001207 audio_stream_type_t stream,
1208 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001209 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001210 uint32_t *delayMs)
1211{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001212 // cannot start playback of STREAM_TTS if any other output is being used
1213 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001214
1215 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001216 if (stream == AUDIO_STREAM_TTS) {
1217 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001218 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001219 return INVALID_OPERATION;
1220 } else {
1221 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1222 }
1223 } else {
1224 // some playback other than beacon starts
1225 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1226 }
1227
Eric Laurent77305a62016-07-25 16:39:22 -07001228 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001229 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001230 bool force = !outputDesc->isActive() &&
1231 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001232
Eric Laurente552edb2014-03-10 17:42:56 -07001233 // increment usage count for this stream on the requested output:
1234 // NOTE that the usage count is the same for duplicated output and hardware output which is
1235 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1236 outputDesc->changeRefCount(stream, 1);
1237
Eric Laurent493404d2015-04-21 15:07:36 -07001238 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001239 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001240 if (device == AUDIO_DEVICE_NONE) {
1241 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001242 }
Eric Laurente552edb2014-03-10 17:42:56 -07001243 routing_strategy strategy = getStrategy(stream);
1244 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001245 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1246 (beaconMuteLatency > 0);
1247 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001248 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001249 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001250 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001251 // force a device change if any other output is:
1252 // - managed by the same hw module
1253 // - has a current device selection that differs from selected device.
1254 // - supports currently selected device
1255 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001256 // In this case, the audio HAL must receive the new device selection so that it can
1257 // change the device currently selected by the other active output.
1258 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001259 desc->device() != device &&
1260 desc->supportedDevices() & device &&
1261 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001262 force = true;
1263 }
1264 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001265 // a notification so that audio focus effect can propagate, or that a mute/unmute
1266 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001267 uint32_t latency = desc->latency();
1268 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1269 waitMs = latency;
1270 }
1271 }
1272 }
Eric Laurentdc462862016-07-19 12:29:53 -07001273 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001274
1275 // handle special case for sonification while in call
1276 if (isInCall()) {
1277 handleIncallSonification(stream, true, false);
1278 }
1279
1280 // apply volume rules for current stream and device if necessary
1281 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001282 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001283 outputDesc,
1284 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001285
1286 // update the outputs if starting an output with a stream that can affect notification
1287 // routing
1288 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001289
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001290 // force reevaluating accessibility routing when ringtone or alarm starts
1291 if (strategy == STRATEGY_SONIFICATION) {
1292 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1293 }
Eric Laurentdc462862016-07-19 12:29:53 -07001294
1295 if (waitMs > muteWaitMs) {
1296 *delayMs = waitMs - muteWaitMs;
1297 }
Eric Laurente552edb2014-03-10 17:42:56 -07001298 }
Eric Laurentdc462862016-07-19 12:29:53 -07001299
Eric Laurente552edb2014-03-10 17:42:56 -07001300 return NO_ERROR;
1301}
1302
1303
Eric Laurente0720872014-03-11 09:30:41 -07001304status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001305 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001306 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001307{
1308 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1309 ssize_t index = mOutputs.indexOfKey(output);
1310 if (index < 0) {
1311 ALOGW("stopOutput() unknown output %d", output);
1312 return BAD_VALUE;
1313 }
1314
Eric Laurentc75307b2015-03-17 15:29:32 -07001315 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001316
Eric Laurentc75307b2015-03-17 15:29:32 -07001317 if (outputDesc->mRefCount[stream] == 1) {
1318 // Automatically disable the remote submix input when output is stopped on a
1319 // re routing mix of type MIX_TYPE_RECORDERS
1320 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1321 outputDesc->mPolicyMix != NULL &&
1322 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1323 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1324 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001325 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001326 "remote-submix");
1327 }
1328 }
1329
1330 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001331 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001332 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001333 int activityCount = mOutputRoutes.decRouteActivity(session);
1334 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1335
1336 if (forceDeviceUpdate) {
1337 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1338 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 }
1340
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001341 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001342}
1343
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001344status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001345 audio_stream_type_t stream,
1346 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001347{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001348 // always handle stream stop, check which stream type is stopping
1349 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1350
Eric Laurente552edb2014-03-10 17:42:56 -07001351 // handle special case for sonification while in call
1352 if (isInCall()) {
1353 handleIncallSonification(stream, false, false);
1354 }
1355
1356 if (outputDesc->mRefCount[stream] > 0) {
1357 // decrement usage count of this stream on the output
1358 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001359
Eric Laurente552edb2014-03-10 17:42:56 -07001360 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001361 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001362 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001363 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001364 // delay the device switch by twice the latency because stopOutput() is executed when
1365 // the track stop() command is received and at that time the audio track buffer can
1366 // still contain data that needs to be drained. The latency only covers the audio HAL
1367 // and kernel buffers. Also the latency does not always include additional delay in the
1368 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001369 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001370
1371 // force restoring the device selection on other active outputs if it differs from the
1372 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001373 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001374 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001375 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001376 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001377 desc->isActive() &&
1378 outputDesc->sharesHwModuleWith(desc) &&
1379 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001380 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1381 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001382 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001383 newDevice2,
1384 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001385 delayMs);
1386 // re-apply device specific volume if not done by setOutputDevice()
1387 if (!force) {
1388 applyStreamVolumes(desc, newDevice2, delayMs);
1389 }
Eric Laurente552edb2014-03-10 17:42:56 -07001390 }
1391 }
1392 // update the outputs if stopping one with a stream that can affect notification routing
1393 handleNotificationRoutingForStream(stream);
1394 }
1395 return NO_ERROR;
1396 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001397 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001398 return INVALID_OPERATION;
1399 }
1400}
1401
Eric Laurente83b55d2014-11-14 10:06:21 -08001402void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001403 audio_stream_type_t stream __unused,
1404 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001405{
1406 ALOGV("releaseOutput() %d", output);
1407 ssize_t index = mOutputs.indexOfKey(output);
1408 if (index < 0) {
1409 ALOGW("releaseOutput() releasing unknown output %d", output);
1410 return;
1411 }
1412
1413#ifdef AUDIO_POLICY_TEST
1414 int testIndex = testOutputIndex(output);
1415 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001416 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001417 if (outputDesc->isActive()) {
1418 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001419 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001420 mTestOutputs[testIndex] = 0;
1421 }
1422 return;
1423 }
1424#endif //AUDIO_POLICY_TEST
1425
Paul McLeanaa981192015-03-21 09:55:15 -07001426 // Routing
1427 mOutputRoutes.removeRoute(session);
1428
Eric Laurentc75307b2015-03-17 15:29:32 -07001429 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001430 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001431 if (desc->mDirectOpenCount <= 0) {
1432 ALOGW("releaseOutput() invalid open count %d for output %d",
1433 desc->mDirectOpenCount, output);
1434 return;
1435 }
1436 if (--desc->mDirectOpenCount == 0) {
1437 closeOutput(output);
1438 // If effects where present on the output, audioflinger moved them to the primary
1439 // output by default: move them back to the appropriate output.
1440 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001441 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001442 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1443 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001444 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001445 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001446 }
1447 }
1448}
1449
1450
Eric Laurentcaf7f482014-11-25 17:50:47 -08001451status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1452 audio_io_handle_t *input,
1453 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001454 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001455 uint32_t samplingRate,
1456 audio_format_t format,
1457 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001458 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001459 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001460 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001461{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001462 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1463 "session %d, flags %#x",
1464 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001465
Eric Laurentcaf7f482014-11-25 17:50:47 -08001466 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001467 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001468 audio_devices_t device;
1469 // handle legacy remote submix case where the address was not always specified
1470 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001471 audio_source_t inputSource = attr->source;
1472 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001473 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001474
Eric Laurentc447ded2015-01-06 08:47:05 -08001475 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1476 inputSource = AUDIO_SOURCE_MIC;
1477 }
1478 halInputSource = inputSource;
1479
Paul McLean466dc8e2015-04-17 13:15:36 -06001480 // Explicit routing?
1481 sp<DeviceDescriptor> deviceDesc;
1482 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1483 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1484 deviceDesc = mAvailableInputDevices[i];
1485 break;
1486 }
1487 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001488 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001489
Eric Laurentc447ded2015-01-06 08:47:05 -08001490 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001491 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001492 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001493 if (ret != NO_ERROR) {
1494 return ret;
1495 }
1496 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001497 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1498 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001499 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001500 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001501 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001502 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001503 return BAD_VALUE;
1504 }
Eric Laurentc722f302014-12-10 11:21:49 -08001505 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001506 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001507 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1508 // there is an external policy, but this input is attached to a mix of recorders,
1509 // meaning it receives audio injected into the framework, so the recorder doesn't
1510 // know about it and is therefore considered "legacy"
1511 *inputType = API_INPUT_LEGACY;
1512 } else {
1513 // recording a mix of players defined by an external policy, we're rerouting for
1514 // an external policy
1515 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1516 }
Eric Laurentc722f302014-12-10 11:21:49 -08001517 } else if (audio_is_remote_submix_device(device)) {
1518 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001519 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001520 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1521 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001522 } else {
1523 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001524 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001525
Eric Laurent599c7582015-12-07 18:05:55 -08001526 }
1527
1528 *input = getInputForDevice(device, address, session, uid, inputSource,
1529 samplingRate, format, channelMask, flags,
1530 policyMix);
1531 if (*input == AUDIO_IO_HANDLE_NONE) {
1532 mInputRoutes.removeRoute(session);
1533 return INVALID_OPERATION;
1534 }
1535 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1536 return NO_ERROR;
1537}
1538
1539
1540audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1541 String8 address,
1542 audio_session_t session,
1543 uid_t uid,
1544 audio_source_t inputSource,
1545 uint32_t samplingRate,
1546 audio_format_t format,
1547 audio_channel_mask_t channelMask,
1548 audio_input_flags_t flags,
1549 AudioMix *policyMix)
1550{
1551 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1552 audio_source_t halInputSource = inputSource;
1553 bool isSoundTrigger = false;
1554
1555 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1556 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1557 if (index >= 0) {
1558 input = mSoundTriggerSessions.valueFor(session);
1559 isSoundTrigger = true;
1560 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1561 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1562 } else {
1563 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001564 }
1565 }
1566
Andy Hungf129b032015-04-07 13:45:50 -07001567 // find a compatible input profile (not necessarily identical in parameters)
1568 sp<IOProfile> profile;
1569 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001570 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001571 audio_format_t profileFormat = format;
1572 audio_channel_mask_t profileChannelMask = channelMask;
1573 audio_input_flags_t profileFlags = flags;
1574 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001575 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001576 profileSamplingRate, profileFormat, profileChannelMask,
1577 profileFlags);
1578 if (profile != 0) {
1579 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001580 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1581 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001582 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1583 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1584 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001585 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1586 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001587 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001588 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001589 }
Eric Laurente552edb2014-03-10 17:42:56 -07001590 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001591 // Pick input sampling rate if not specified by client
1592 if (samplingRate == 0) {
1593 samplingRate = profileSamplingRate;
1594 }
Eric Laurente552edb2014-03-10 17:42:56 -07001595
Eric Laurent322b4d22015-04-03 15:57:54 -07001596 if (profile->getModuleHandle() == 0) {
1597 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001598 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001599 }
1600
Eric Laurent599c7582015-12-07 18:05:55 -08001601 sp<AudioSession> audioSession = new AudioSession(session,
1602 inputSource,
1603 format,
1604 samplingRate,
1605 channelMask,
1606 flags,
1607 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001608 isSoundTrigger,
1609 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001610
Eric Laurent232f26f2016-02-17 18:06:27 -08001611// TODO enable input reuse
1612#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001613 // reuse an open input if possible
1614 for (size_t i = 0; i < mInputs.size(); i++) {
1615 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent232f26f2016-02-17 18:06:27 -08001616 // reuse input if it shares the same profile and same sound trigger attribute
1617 if (profile == desc->mProfile &&
1618 isSoundTrigger == desc->isSoundTrigger()) {
Eric Laurent599c7582015-12-07 18:05:55 -08001619
1620 sp<AudioSession> as = desc->getAudioSession(session);
1621 if (as != 0) {
1622 // do not allow unmatching properties on same session
1623 if (as->matches(audioSession)) {
1624 as->changeOpenCount(1);
1625 } else {
1626 ALOGW("getInputForDevice() record with different attributes"
1627 " exists for session %d", session);
Eric Laurent232f26f2016-02-17 18:06:27 -08001628 return input;
Eric Laurent599c7582015-12-07 18:05:55 -08001629 }
1630 } else {
1631 desc->addAudioSession(session, audioSession);
1632 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001633 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1634 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001635 }
1636 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001637#endif
Eric Laurent599c7582015-12-07 18:05:55 -08001638
Eric Laurentcf2c0212014-07-25 16:20:43 -07001639 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001640 config.sample_rate = profileSamplingRate;
1641 config.channel_mask = profileChannelMask;
1642 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001643
Eric Laurent322b4d22015-04-03 15:57:54 -07001644 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001645 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001646 &config,
1647 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001648 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001649 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001650 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001651
1652 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001653 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001654 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001655 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001656 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001657 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1658 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001659 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001660 if (input != AUDIO_IO_HANDLE_NONE) {
1661 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001662 }
Eric Laurent599c7582015-12-07 18:05:55 -08001663 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001664 }
1665
Eric Laurent1f2f2232014-06-02 12:01:23 -07001666 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001667 inputDesc->mSamplingRate = profileSamplingRate;
1668 inputDesc->mFormat = profileFormat;
1669 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001670 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001671 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001672 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001673
Eric Laurent599c7582015-12-07 18:05:55 -08001674 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001675 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001676
Eric Laurent599c7582015-12-07 18:05:55 -08001677 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001678}
1679
Eric Laurent4dc68062014-07-28 17:26:49 -07001680status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurent232f26f2016-02-17 18:06:27 -08001681 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001682{
1683 ALOGV("startInput() input %d", input);
1684 ssize_t index = mInputs.indexOfKey(input);
1685 if (index < 0) {
1686 ALOGW("startInput() unknown input %d", input);
1687 return BAD_VALUE;
1688 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001689 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001690
Eric Laurent599c7582015-12-07 18:05:55 -08001691 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1692 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001693 ALOGW("startInput() unknown session %d on input %d", session, input);
1694 return BAD_VALUE;
1695 }
1696
Eric Laurent232f26f2016-02-17 18:06:27 -08001697 // virtual input devices are compatible with other input devices
1698 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001699
Eric Laurent232f26f2016-02-17 18:06:27 -08001700 // for a non-virtual input device, check if there is another (non-virtual) active input
1701 audio_io_handle_t activeInput = mInputs.getActiveInput();
1702 if (activeInput != 0 && activeInput != input) {
Eric Laurente552edb2014-03-10 17:42:56 -07001703
Eric Laurent232f26f2016-02-17 18:06:27 -08001704 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1705 // otherwise the active input continues and the new input cannot be started.
1706 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1707 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
1708 !activeDesc->hasPreemptedSession(session)) {
1709 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1710 //FIXME: consider all active sessions
1711 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1712 audio_session_t activeSession = activeSessions.keyAt(0);
1713 SortedVector<audio_session_t> sessions =
1714 activeDesc->getPreemptedSessions();
1715 sessions.add(activeSession);
1716 inputDesc->setPreemptedSessions(sessions);
1717 stopInput(activeInput, activeSession);
1718 releaseInput(activeInput, activeSession);
1719 } else {
1720 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1721 return INVALID_OPERATION;
1722 }
1723 }
1724
1725 // Do not allow capture if an active voice call is using a software patch and
1726 // the call TX source device is on the same HW module.
1727 // FIXME: would be better to refine to only inputs whose profile connects to the
1728 // call TX device but this information is not in the audio patch
1729 if (mCallTxPatch != 0 &&
1730 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1731 return INVALID_OPERATION;
1732 }
1733 }
Eric Laurent313d1e72016-01-29 09:56:57 -08001734
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001735 // Routing?
1736 mInputRoutes.incRouteActivity(session);
1737
Eric Laurent232f26f2016-02-17 18:06:27 -08001738 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
1739 // if input maps to a dynamic policy with an activity listener, notify of state change
1740 if ((inputDesc->mPolicyMix != NULL)
1741 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001742 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001743 MIX_STATE_MIXING);
1744 }
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001745
Eric Laurent271a93e2016-09-29 14:47:06 -07001746 // indicate active capture to sound trigger service if starting capture from a mic on
1747 // primary HW module
1748 audio_devices_t device = getNewInputDevice(input);
1749 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1750 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1751 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurent232f26f2016-02-17 18:06:27 -08001752 SoundTrigger::setCaptureState(true);
1753 }
Eric Laurent271a93e2016-09-29 14:47:06 -07001754 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001755
Eric Laurent232f26f2016-02-17 18:06:27 -08001756 // automatically enable the remote submix output when input is started if not
1757 // used by a policy mix of type MIX_TYPE_RECORDERS
1758 // For remote submix (a virtual device), we open only one input per capture request.
1759 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1760 String8 address = String8("");
1761 if (inputDesc->mPolicyMix == NULL) {
1762 address = String8("0");
1763 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001764 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurentc722f302014-12-10 11:21:49 -08001765 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001766 if (address != "") {
1767 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1768 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1769 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001770 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001771 }
Eric Laurente552edb2014-03-10 17:42:56 -07001772 }
1773
Eric Laurent599c7582015-12-07 18:05:55 -08001774 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001775
Eric Laurent232f26f2016-02-17 18:06:27 -08001776 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001777 return NO_ERROR;
1778}
1779
Eric Laurent4dc68062014-07-28 17:26:49 -07001780status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1781 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001782{
1783 ALOGV("stopInput() input %d", input);
1784 ssize_t index = mInputs.indexOfKey(input);
1785 if (index < 0) {
1786 ALOGW("stopInput() unknown input %d", input);
1787 return BAD_VALUE;
1788 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001789 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001790
Eric Laurent599c7582015-12-07 18:05:55 -08001791 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001792 if (index < 0) {
1793 ALOGW("stopInput() unknown session %d on input %d", session, input);
1794 return BAD_VALUE;
1795 }
1796
Eric Laurent599c7582015-12-07 18:05:55 -08001797 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001798 ALOGW("stopInput() input %d already stopped", input);
1799 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001800 }
1801
Eric Laurent599c7582015-12-07 18:05:55 -08001802 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001803
1804 // Routing?
1805 mInputRoutes.decRouteActivity(session);
1806
Eric Laurent232f26f2016-02-17 18:06:27 -08001807 if (!inputDesc->isActive()) {
1808 // if input maps to a dynamic policy with an activity listener, notify of state change
1809 if ((inputDesc->mPolicyMix != NULL)
1810 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001811 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001812 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001813 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001814
1815 // automatically disable the remote submix output when input is stopped if not
1816 // used by a policy mix of type MIX_TYPE_RECORDERS
1817 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1818 String8 address = String8("");
1819 if (inputDesc->mPolicyMix == NULL) {
1820 address = String8("0");
1821 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001822 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurent232f26f2016-02-17 18:06:27 -08001823 }
1824 if (address != "") {
1825 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1826 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1827 address, "remote-submix");
1828 }
1829 }
1830
Eric Laurent271a93e2016-09-29 14:47:06 -07001831 audio_devices_t device = inputDesc->mDevice;
Eric Laurent232f26f2016-02-17 18:06:27 -08001832 resetInputDevice(input);
1833
Eric Laurent271a93e2016-09-29 14:47:06 -07001834 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1835 // primary HW module
1836 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1837 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1838 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurent232f26f2016-02-17 18:06:27 -08001839 SoundTrigger::setCaptureState(false);
1840 }
1841 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001842 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001843 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001844}
1845
Eric Laurent4dc68062014-07-28 17:26:49 -07001846void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1847 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001848{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001849
Eric Laurente552edb2014-03-10 17:42:56 -07001850 ALOGV("releaseInput() %d", input);
1851 ssize_t index = mInputs.indexOfKey(input);
1852 if (index < 0) {
1853 ALOGW("releaseInput() releasing unknown input %d", input);
1854 return;
1855 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001856
1857 // Routing
1858 mInputRoutes.removeRoute(session);
1859
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001860 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1861 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001862
Eric Laurent599c7582015-12-07 18:05:55 -08001863 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001864 if (index < 0) {
1865 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1866 return;
1867 }
Eric Laurent599c7582015-12-07 18:05:55 -08001868
1869 if (audioSession->openCount() == 0) {
1870 ALOGW("releaseInput() invalid open count %d on session %d",
1871 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001872 return;
1873 }
Eric Laurent599c7582015-12-07 18:05:55 -08001874
1875 if (audioSession->changeOpenCount(-1) == 0) {
1876 inputDesc->removeAudioSession(session);
1877 }
1878
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001879 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001880 ALOGV("releaseInput() exit > 0");
1881 return;
1882 }
1883
Eric Laurent05b90f82014-08-27 15:32:29 -07001884 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001885 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001886 ALOGV("releaseInput() exit");
1887}
1888
Eric Laurentd4692962014-05-05 18:13:44 -07001889void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001890 bool patchRemoved = false;
1891
Eric Laurentd4692962014-05-05 18:13:44 -07001892 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001893 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001894 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001895 if (patch_index >= 0) {
1896 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001897 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001898 mAudioPatches.removeItemsAt(patch_index);
1899 patchRemoved = true;
1900 }
Eric Laurentd4692962014-05-05 18:13:44 -07001901 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1902 }
1903 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001904 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001905 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001906
1907 if (patchRemoved) {
1908 mpClientInterface->onAudioPatchListUpdate();
1909 }
Eric Laurentd4692962014-05-05 18:13:44 -07001910}
1911
Eric Laurente0720872014-03-11 09:30:41 -07001912void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001913 int indexMin,
1914 int indexMax)
1915{
1916 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001917 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001918
1919 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001920 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1921 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001922 continue;
1923 }
1924 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001925 }
Eric Laurente552edb2014-03-10 17:42:56 -07001926}
1927
Eric Laurente0720872014-03-11 09:30:41 -07001928status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001929 int index,
1930 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001931{
1932
François Gaffied1ab2bd2015-12-02 18:20:06 +01001933 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1934 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001935 return BAD_VALUE;
1936 }
1937 if (!audio_is_output_device(device)) {
1938 return BAD_VALUE;
1939 }
1940
1941 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001942 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001943
Eric Laurent1fd372e2016-04-06 14:23:53 -07001944 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001945 stream, device, index);
1946
Eric Laurent28d09f02016-03-08 10:43:05 -08001947 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001948 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1949 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001950 continue;
1951 }
1952 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1953 }
Eric Laurente552edb2014-03-10 17:42:56 -07001954
Eric Laurent1fd372e2016-04-06 14:23:53 -07001955 // update volume on all outputs and streams matching the following:
1956 // - The requested stream (or a stream matching for volume control) is active on the output
1957 // - The device (or devices) selected by the strategy corresponding to this stream includes
1958 // the requested device
1959 // - For non default requested device, currently selected device on the output is either the
1960 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001961 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1962 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001963 status_t status = NO_ERROR;
1964 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001965 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1966 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001967 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1968 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001969 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001970 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001971 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1972 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001973 continue;
1974 }
Eric Laurent794fde22016-03-11 09:50:45 -08001975 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07001976 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
1977 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
1978 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001979 continue;
1980 }
Eric Laurente76f29c2016-09-14 17:17:53 -07001981 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001982 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001983 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07001984 applyVolume = (curDevice & curStreamDevice) != 0;
1985 } else {
1986 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
1987 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07001988 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001989
Eric Laurente76f29c2016-09-14 17:17:53 -07001990 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07001991 //FIXME: workaround for truncated touch sounds
1992 // delayed volume change for system stream to be removed when the problem is
1993 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08001994 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07001995 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
1996 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08001997 if (volStatus != NO_ERROR) {
1998 status = volStatus;
1999 }
2000 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002001 }
Eric Laurente552edb2014-03-10 17:42:56 -07002002 }
2003 return status;
2004}
2005
Eric Laurente0720872014-03-11 09:30:41 -07002006status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002007 int *index,
2008 audio_devices_t device)
2009{
2010 if (index == NULL) {
2011 return BAD_VALUE;
2012 }
2013 if (!audio_is_output_device(device)) {
2014 return BAD_VALUE;
2015 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002016 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002017 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002018 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002019 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2020 }
François Gaffiedfd74092015-03-19 12:10:59 +01002021 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002022
François Gaffied1ab2bd2015-12-02 18:20:06 +01002023 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002024 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2025 return NO_ERROR;
2026}
2027
Eric Laurente0720872014-03-11 09:30:41 -07002028audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002029 const SortedVector<audio_io_handle_t>& outputs)
2030{
2031 // select one output among several suitable for global effects.
2032 // The priority is as follows:
2033 // 1: An offloaded output. If the effect ends up not being offloadable,
2034 // AudioFlinger will invalidate the track and the offloaded output
2035 // will be closed causing the effect to be moved to a PCM output.
2036 // 2: A deep buffer output
2037 // 3: the first output in the list
2038
2039 if (outputs.size() == 0) {
2040 return 0;
2041 }
2042
2043 audio_io_handle_t outputOffloaded = 0;
2044 audio_io_handle_t outputDeepBuffer = 0;
2045
2046 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002047 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002048 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002049 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2050 outputOffloaded = outputs[i];
2051 }
2052 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2053 outputDeepBuffer = outputs[i];
2054 }
2055 }
2056
2057 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2058 outputOffloaded, outputDeepBuffer);
2059 if (outputOffloaded != 0) {
2060 return outputOffloaded;
2061 }
2062 if (outputDeepBuffer != 0) {
2063 return outputDeepBuffer;
2064 }
2065
2066 return outputs[0];
2067}
2068
Eric Laurente0720872014-03-11 09:30:41 -07002069audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002070{
2071 // apply simple rule where global effects are attached to the same output as MUSIC streams
2072
Eric Laurent3b73df72014-03-11 09:06:29 -07002073 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002074 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2075 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2076
2077 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2078 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2079 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2080
2081 return output;
2082}
2083
Eric Laurente0720872014-03-11 09:30:41 -07002084status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002085 audio_io_handle_t io,
2086 uint32_t strategy,
2087 int session,
2088 int id)
2089{
2090 ssize_t index = mOutputs.indexOfKey(io);
2091 if (index < 0) {
2092 index = mInputs.indexOfKey(io);
2093 if (index < 0) {
2094 ALOGW("registerEffect() unknown io %d", io);
2095 return INVALID_OPERATION;
2096 }
2097 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002098 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002099}
2100
Eric Laurentc75307b2015-03-17 15:29:32 -07002101bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2102{
Eric Laurent28d09f02016-03-08 10:43:05 -08002103 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002104 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2105 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002106 continue;
2107 }
2108 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2109 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002110 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002111}
2112
2113bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2114{
2115 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2116}
2117
Eric Laurente0720872014-03-11 09:30:41 -07002118bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002119{
2120 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002121 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002122 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002123 return true;
2124 }
2125 }
2126 return false;
2127}
2128
Eric Laurent275e8e92014-11-30 15:14:47 -08002129// Register a list of custom mixes with their attributes and format.
2130// When a mix is registered, corresponding input and output profiles are
2131// added to the remote submix hw module. The profile contains only the
2132// parameters (sampling rate, format...) specified by the mix.
2133// The corresponding input remote submix device is also connected.
2134//
2135// When a remote submix device is connected, the address is checked to select the
2136// appropriate profile and the corresponding input or output stream is opened.
2137//
2138// When capture starts, getInputForAttr() will:
2139// - 1 look for a mix matching the address passed in attribtutes tags if any
2140// - 2 if none found, getDeviceForInputSource() will:
2141// - 2.1 look for a mix matching the attributes source
2142// - 2.2 if none found, default to device selection by policy rules
2143// At this time, the corresponding output remote submix device is also connected
2144// and active playback use cases can be transferred to this mix if needed when reconnecting
2145// after AudioTracks are invalidated
2146//
2147// When playback starts, getOutputForAttr() will:
2148// - 1 look for a mix matching the address passed in attribtutes tags if any
2149// - 2 if none found, look for a mix matching the attributes usage
2150// - 3 if none found, default to device and output selection by policy rules.
2151
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002152status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002153{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002154 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2155 status_t res = NO_ERROR;
2156
2157 sp<HwModule> rSubmixModule;
2158 // examine each mix's route type
2159 for (size_t i = 0; i < mixes.size(); i++) {
2160 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2161 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2162 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002163 break;
2164 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002165 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2166 // Loop back through "remote submix"
2167 if (rSubmixModule == 0) {
2168 for (size_t j = 0; i < mHwModules.size(); j++) {
2169 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2170 && mHwModules[j]->mHandle != 0) {
2171 rSubmixModule = mHwModules[j];
2172 break;
2173 }
2174 }
2175 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002176
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002177 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002178
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002179 if (rSubmixModule == 0) {
2180 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2181 res = INVALID_OPERATION;
2182 break;
2183 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002184
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002185 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002186
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002187 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002188 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002189 res = INVALID_OPERATION;
2190 break;
2191 }
2192 audio_config_t outputConfig = mixes[i].mFormat;
2193 audio_config_t inputConfig = mixes[i].mFormat;
2194 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2195 // stereo and let audio flinger do the channel conversion if needed.
2196 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2197 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2198 rSubmixModule->addOutputProfile(address, &outputConfig,
2199 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2200 rSubmixModule->addInputProfile(address, &inputConfig,
2201 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002202
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002203 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2204 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2205 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2206 address.string(), "remote-submix");
2207 } else {
2208 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2209 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2210 address.string(), "remote-submix");
2211 }
2212 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002213 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002214 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002215 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2216 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002217
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002218 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002219 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2220 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2221 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2222 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2223 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2224 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002225 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2226 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002227 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2228 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002229 } else {
2230 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002231 }
2232 break;
2233 }
2234 }
2235
2236 if (res != NO_ERROR) {
2237 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002238 i, device, address.string());
2239 res = INVALID_OPERATION;
2240 break;
2241 } else if (!foundOutput) {
2242 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2243 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002244 res = INVALID_OPERATION;
2245 break;
2246 }
Eric Laurentc722f302014-12-10 11:21:49 -08002247 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002248 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002249 if (res != NO_ERROR) {
2250 unregisterPolicyMixes(mixes);
2251 }
2252 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002253}
2254
2255status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2256{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002257 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002258 status_t res = NO_ERROR;
2259 sp<HwModule> rSubmixModule;
2260 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002261 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002262 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002263
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002264 if (rSubmixModule == 0) {
2265 for (size_t j = 0; i < mHwModules.size(); j++) {
2266 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2267 && mHwModules[j]->mHandle != 0) {
2268 rSubmixModule = mHwModules[j];
2269 break;
2270 }
2271 }
2272 }
2273 if (rSubmixModule == 0) {
2274 res = INVALID_OPERATION;
2275 continue;
2276 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002277
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002278 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002279
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002280 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2281 res = INVALID_OPERATION;
2282 continue;
2283 }
2284
2285 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2286 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2287 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2288 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2289 address.string(), "remote-submix");
2290 }
2291 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2292 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2293 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2294 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2295 address.string(), "remote-submix");
2296 }
2297 rSubmixModule->removeOutputProfile(address);
2298 rSubmixModule->removeInputProfile(address);
2299
2300 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2301 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2302 res = INVALID_OPERATION;
2303 continue;
2304 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002305 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002306 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002307 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002308}
2309
Eric Laurente552edb2014-03-10 17:42:56 -07002310
Eric Laurente0720872014-03-11 09:30:41 -07002311status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002312{
2313 const size_t SIZE = 256;
2314 char buffer[SIZE];
2315 String8 result;
2316
2317 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2318 result.append(buffer);
2319
Eric Laurent87ffa392015-05-22 10:32:38 -07002320 snprintf(buffer, SIZE, " Primary Output: %d\n",
2321 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002322 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002323 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002324 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002325 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002326 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002327 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002328 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002329 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002330 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002331 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002332 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002333 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002334 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002335 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002336 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002337 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002338 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002339 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2340 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2341 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002342 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2343 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002344 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2345 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002346
François Gaffie2110e042015-03-24 08:41:51 +01002347 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002348
François Gaffie112b0af2015-11-19 16:13:25 +01002349 mAvailableOutputDevices.dump(fd, String8("Available output"));
2350 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002351 mHwModules.dump(fd);
2352 mOutputs.dump(fd);
2353 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002354 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002355 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002356 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002357
2358 return NO_ERROR;
2359}
2360
2361// This function checks for the parameters which can be offloaded.
2362// This can be enhanced depending on the capability of the DSP and policy
2363// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002364bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002365{
2366 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002367 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002368 offloadInfo.sample_rate, offloadInfo.channel_mask,
2369 offloadInfo.format,
2370 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2371 offloadInfo.has_video);
2372
Andy Hung2ddee192015-12-18 17:34:44 -08002373 if (mMasterMono) {
2374 return false; // no offloading if mono is set.
2375 }
2376
Eric Laurente552edb2014-03-10 17:42:56 -07002377 // Check if offload has been disabled
2378 char propValue[PROPERTY_VALUE_MAX];
2379 if (property_get("audio.offload.disable", propValue, "0")) {
2380 if (atoi(propValue) != 0) {
2381 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2382 return false;
2383 }
2384 }
2385
2386 // Check if stream type is music, then only allow offload as of now.
2387 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2388 {
2389 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2390 return false;
2391 }
2392
2393 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002394 const bool allowOffloadWithVideo =
2395 property_get_bool("audio.offload.video", false /* default_value */);
2396 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002397 ALOGV("isOffloadSupported: has_video == true, returning false");
2398 return false;
2399 }
2400
2401 //If duration is less than minimum value defined in property, return false
2402 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2403 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2404 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2405 return false;
2406 }
2407 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2408 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2409 return false;
2410 }
2411
2412 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2413 // creating an offloaded track and tearing it down immediately after start when audioflinger
2414 // detects there is an active non offloadable effect.
2415 // FIXME: We should check the audio session here but we do not have it in this context.
2416 // This may prevent offloading in rare situations where effects are left active by apps
2417 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002418 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002419 return false;
2420 }
2421
2422 // See if there is a profile to support this.
2423 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002424 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002425 offloadInfo.sample_rate,
2426 offloadInfo.format,
2427 offloadInfo.channel_mask,
2428 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002429 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2430 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002431}
2432
Eric Laurent6a94d692014-05-20 11:18:06 -07002433status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2434 audio_port_type_t type,
2435 unsigned int *num_ports,
2436 struct audio_port *ports,
2437 unsigned int *generation)
2438{
2439 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2440 generation == NULL) {
2441 return BAD_VALUE;
2442 }
2443 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2444 if (ports == NULL) {
2445 *num_ports = 0;
2446 }
2447
2448 size_t portsWritten = 0;
2449 size_t portsMax = *num_ports;
2450 *num_ports = 0;
2451 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002452 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2453 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002454 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002455 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2456 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2457 continue;
2458 }
2459 if (portsWritten < portsMax) {
2460 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2461 }
2462 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002463 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002464 }
2465 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002466 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2467 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2468 continue;
2469 }
2470 if (portsWritten < portsMax) {
2471 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2472 }
2473 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002474 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 }
2476 }
2477 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2478 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2479 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2480 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2481 }
2482 *num_ports += mInputs.size();
2483 }
2484 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002485 size_t numOutputs = 0;
2486 for (size_t i = 0; i < mOutputs.size(); i++) {
2487 if (!mOutputs[i]->isDuplicated()) {
2488 numOutputs++;
2489 if (portsWritten < portsMax) {
2490 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2491 }
2492 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002493 }
Eric Laurent84c70242014-06-23 08:46:27 -07002494 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002495 }
2496 }
2497 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002498 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002499 return NO_ERROR;
2500}
2501
2502status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2503{
2504 return NO_ERROR;
2505}
2506
Eric Laurent6a94d692014-05-20 11:18:06 -07002507status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2508 audio_patch_handle_t *handle,
2509 uid_t uid)
2510{
2511 ALOGV("createAudioPatch()");
2512
2513 if (handle == NULL || patch == NULL) {
2514 return BAD_VALUE;
2515 }
2516 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2517
Eric Laurent874c42872014-08-08 15:13:39 -07002518 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2519 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2520 return BAD_VALUE;
2521 }
2522 // only one source per audio patch supported for now
2523 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002524 return INVALID_OPERATION;
2525 }
Eric Laurent874c42872014-08-08 15:13:39 -07002526
2527 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002528 return INVALID_OPERATION;
2529 }
Eric Laurent874c42872014-08-08 15:13:39 -07002530 for (size_t i = 0; i < patch->num_sinks; i++) {
2531 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2532 return INVALID_OPERATION;
2533 }
2534 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002535
2536 sp<AudioPatch> patchDesc;
2537 ssize_t index = mAudioPatches.indexOfKey(*handle);
2538
Eric Laurent6a94d692014-05-20 11:18:06 -07002539 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2540 patch->sources[0].role,
2541 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002542#if LOG_NDEBUG == 0
2543 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002544 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002545 patch->sinks[i].role,
2546 patch->sinks[i].type);
2547 }
2548#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002549
2550 if (index >= 0) {
2551 patchDesc = mAudioPatches.valueAt(index);
2552 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2553 mUidCached, patchDesc->mUid, uid);
2554 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2555 return INVALID_OPERATION;
2556 }
2557 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002558 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002559 }
2560
2561 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002562 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002563 if (outputDesc == NULL) {
2564 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2565 return BAD_VALUE;
2566 }
Eric Laurent84c70242014-06-23 08:46:27 -07002567 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2568 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002569 if (patchDesc != 0) {
2570 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2571 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2572 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2573 return BAD_VALUE;
2574 }
2575 }
Eric Laurent874c42872014-08-08 15:13:39 -07002576 DeviceVector devices;
2577 for (size_t i = 0; i < patch->num_sinks; i++) {
2578 // Only support mix to devices connection
2579 // TODO add support for mix to mix connection
2580 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2581 ALOGV("createAudioPatch() source mix but sink is not a device");
2582 return INVALID_OPERATION;
2583 }
2584 sp<DeviceDescriptor> devDesc =
2585 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2586 if (devDesc == 0) {
2587 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2588 return BAD_VALUE;
2589 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002590
François Gaffie53615e22015-03-19 09:24:12 +01002591 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002592 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002593 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002594 NULL, // updatedSamplingRate
2595 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002596 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002597 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002598 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002599 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002600 ALOGV("createAudioPatch() profile not supported for device %08x",
2601 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002602 return INVALID_OPERATION;
2603 }
2604 devices.add(devDesc);
2605 }
2606 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002607 return INVALID_OPERATION;
2608 }
Eric Laurent874c42872014-08-08 15:13:39 -07002609
Eric Laurent6a94d692014-05-20 11:18:06 -07002610 // TODO: reconfigure output format and channels here
2611 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002612 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002613 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002614 index = mAudioPatches.indexOfKey(*handle);
2615 if (index >= 0) {
2616 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2617 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2618 }
2619 patchDesc = mAudioPatches.valueAt(index);
2620 patchDesc->mUid = uid;
2621 ALOGV("createAudioPatch() success");
2622 } else {
2623 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2624 return INVALID_OPERATION;
2625 }
2626 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2627 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2628 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002629 // only one sink supported when connecting an input device to a mix
2630 if (patch->num_sinks > 1) {
2631 return INVALID_OPERATION;
2632 }
François Gaffie53615e22015-03-19 09:24:12 +01002633 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002634 if (inputDesc == NULL) {
2635 return BAD_VALUE;
2636 }
2637 if (patchDesc != 0) {
2638 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2639 return BAD_VALUE;
2640 }
2641 }
2642 sp<DeviceDescriptor> devDesc =
2643 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2644 if (devDesc == 0) {
2645 return BAD_VALUE;
2646 }
2647
François Gaffie53615e22015-03-19 09:24:12 +01002648 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002649 devDesc->mAddress,
2650 patch->sinks[0].sample_rate,
2651 NULL, /*updatedSampleRate*/
2652 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002653 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002654 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002655 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002656 // FIXME for the parameter type,
2657 // and the NONE
2658 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002659 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002660 return INVALID_OPERATION;
2661 }
2662 // TODO: reconfigure output format and channels here
2663 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002664 devDesc->type(), inputDesc->mIoHandle);
2665 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002666 index = mAudioPatches.indexOfKey(*handle);
2667 if (index >= 0) {
2668 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2669 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2670 }
2671 patchDesc = mAudioPatches.valueAt(index);
2672 patchDesc->mUid = uid;
2673 ALOGV("createAudioPatch() success");
2674 } else {
2675 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2676 return INVALID_OPERATION;
2677 }
2678 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2679 // device to device connection
2680 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002681 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002682 return BAD_VALUE;
2683 }
2684 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002685 sp<DeviceDescriptor> srcDeviceDesc =
2686 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002687 if (srcDeviceDesc == 0) {
2688 return BAD_VALUE;
2689 }
Eric Laurent874c42872014-08-08 15:13:39 -07002690
Eric Laurent6a94d692014-05-20 11:18:06 -07002691 //update source and sink with our own data as the data passed in the patch may
2692 // be incomplete.
2693 struct audio_patch newPatch = *patch;
2694 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002695
Eric Laurent874c42872014-08-08 15:13:39 -07002696 for (size_t i = 0; i < patch->num_sinks; i++) {
2697 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2698 ALOGV("createAudioPatch() source device but one sink is not a device");
2699 return INVALID_OPERATION;
2700 }
2701
2702 sp<DeviceDescriptor> sinkDeviceDesc =
2703 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2704 if (sinkDeviceDesc == 0) {
2705 return BAD_VALUE;
2706 }
2707 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2708
Eric Laurent3bcf8592015-04-03 12:13:24 -07002709 // create a software bridge in PatchPanel if:
2710 // - source and sink devices are on differnt HW modules OR
2711 // - audio HAL version is < 3.0
Eric Laurent232f26f2016-02-17 18:06:27 -08002712 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002713 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002714 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002715 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002716 return INVALID_OPERATION;
2717 }
Eric Laurent874c42872014-08-08 15:13:39 -07002718 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002719 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002720 // if the sink device is reachable via an opened output stream, request to go via
2721 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002722 audio_io_handle_t output = selectOutput(outputs,
2723 AUDIO_OUTPUT_FLAG_NONE,
2724 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002725 if (output != AUDIO_IO_HANDLE_NONE) {
2726 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2727 if (outputDesc->isDuplicated()) {
2728 return INVALID_OPERATION;
2729 }
2730 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002731 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002732 newPatch.num_sources = 2;
2733 }
Eric Laurent83b88082014-06-20 18:31:16 -07002734 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002735 }
2736 // TODO: check from routing capabilities in config file and other conflicting patches
2737
2738 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2739 if (index >= 0) {
2740 afPatchHandle = patchDesc->mAfPatchHandle;
2741 }
2742
2743 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2744 &afPatchHandle,
2745 0);
2746 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2747 status, afPatchHandle);
2748 if (status == NO_ERROR) {
2749 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002750 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002751 addAudioPatch(patchDesc->mHandle, patchDesc);
2752 } else {
2753 patchDesc->mPatch = newPatch;
2754 }
2755 patchDesc->mAfPatchHandle = afPatchHandle;
2756 *handle = patchDesc->mHandle;
2757 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002758 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002759 } else {
2760 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2761 status);
2762 return INVALID_OPERATION;
2763 }
2764 } else {
2765 return BAD_VALUE;
2766 }
2767 } else {
2768 return BAD_VALUE;
2769 }
2770 return NO_ERROR;
2771}
2772
2773status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2774 uid_t uid)
2775{
2776 ALOGV("releaseAudioPatch() patch %d", handle);
2777
2778 ssize_t index = mAudioPatches.indexOfKey(handle);
2779
2780 if (index < 0) {
2781 return BAD_VALUE;
2782 }
2783 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2784 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2785 mUidCached, patchDesc->mUid, uid);
2786 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2787 return INVALID_OPERATION;
2788 }
2789
2790 struct audio_patch *patch = &patchDesc->mPatch;
2791 patchDesc->mUid = mUidCached;
2792 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002793 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002794 if (outputDesc == NULL) {
2795 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2796 return BAD_VALUE;
2797 }
2798
Eric Laurentc75307b2015-03-17 15:29:32 -07002799 setOutputDevice(outputDesc,
2800 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002801 true,
2802 0,
2803 NULL);
2804 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2805 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002806 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002807 if (inputDesc == NULL) {
2808 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2809 return BAD_VALUE;
2810 }
2811 setInputDevice(inputDesc->mIoHandle,
Eric Laurent232f26f2016-02-17 18:06:27 -08002812 getNewInputDevice(inputDesc->mIoHandle),
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 true,
2814 NULL);
2815 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2817 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2818 status, patchDesc->mAfPatchHandle);
2819 removeAudioPatch(patchDesc->mHandle);
2820 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002821 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002822 } else {
2823 return BAD_VALUE;
2824 }
2825 } else {
2826 return BAD_VALUE;
2827 }
2828 return NO_ERROR;
2829}
2830
2831status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2832 struct audio_patch *patches,
2833 unsigned int *generation)
2834{
François Gaffie53615e22015-03-19 09:24:12 +01002835 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002836 return BAD_VALUE;
2837 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002838 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002839 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002840}
2841
Eric Laurente1715a42014-05-20 11:30:42 -07002842status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002843{
Eric Laurente1715a42014-05-20 11:30:42 -07002844 ALOGV("setAudioPortConfig()");
2845
2846 if (config == NULL) {
2847 return BAD_VALUE;
2848 }
2849 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2850 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002851 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2852 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002853 }
2854
Eric Laurenta121f902014-06-03 13:32:54 -07002855 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002856 if (config->type == AUDIO_PORT_TYPE_MIX) {
2857 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002858 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002859 if (outputDesc == NULL) {
2860 return BAD_VALUE;
2861 }
Eric Laurent84c70242014-06-23 08:46:27 -07002862 ALOG_ASSERT(!outputDesc->isDuplicated(),
2863 "setAudioPortConfig() called on duplicated output %d",
2864 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002865 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002866 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002867 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002868 if (inputDesc == NULL) {
2869 return BAD_VALUE;
2870 }
Eric Laurenta121f902014-06-03 13:32:54 -07002871 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002872 } else {
2873 return BAD_VALUE;
2874 }
2875 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2876 sp<DeviceDescriptor> deviceDesc;
2877 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2878 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2879 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2880 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2881 } else {
2882 return BAD_VALUE;
2883 }
2884 if (deviceDesc == NULL) {
2885 return BAD_VALUE;
2886 }
Eric Laurenta121f902014-06-03 13:32:54 -07002887 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002888 } else {
2889 return BAD_VALUE;
2890 }
2891
Eric Laurenta121f902014-06-03 13:32:54 -07002892 struct audio_port_config backupConfig;
2893 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2894 if (status == NO_ERROR) {
2895 struct audio_port_config newConfig;
2896 audioPortConfig->toAudioPortConfig(&newConfig, config);
2897 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002898 }
Eric Laurenta121f902014-06-03 13:32:54 -07002899 if (status != NO_ERROR) {
2900 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002901 }
Eric Laurente1715a42014-05-20 11:30:42 -07002902
2903 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002904}
2905
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002906void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2907{
Eric Laurentd60560a2015-04-10 11:31:20 -07002908 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002909 clearAudioPatches(uid);
2910 clearSessionRoutes(uid);
2911}
2912
Eric Laurent6a94d692014-05-20 11:18:06 -07002913void AudioPolicyManager::clearAudioPatches(uid_t uid)
2914{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002915 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002916 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2917 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002918 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 }
2920 }
2921}
2922
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002923void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2924 audio_io_handle_t ouptutToSkip)
2925{
2926 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2927 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2928 for (size_t j = 0; j < mOutputs.size(); j++) {
2929 if (mOutputs.keyAt(j) == ouptutToSkip) {
2930 continue;
2931 }
2932 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2933 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2934 continue;
2935 }
2936 // If the default device for this strategy is on another output mix,
2937 // invalidate all tracks in this strategy to force re connection.
2938 // Otherwise select new device on the output mix.
2939 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002940 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002941 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2942 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2943 }
2944 }
2945 } else {
2946 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2947 setOutputDevice(outputDesc, newDevice, false);
2948 }
2949 }
2950}
2951
2952void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2953{
2954 // remove output routes associated with this uid
2955 SortedVector<routing_strategy> affectedStrategies;
2956 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2957 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2958 if (route->mUid == uid) {
2959 mOutputRoutes.removeItemsAt(i);
2960 if (route->mDeviceDescriptor != 0) {
2961 affectedStrategies.add(getStrategy(route->mStreamType));
2962 }
2963 }
2964 }
2965 // reroute outputs if necessary
2966 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2967 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2968 }
2969
2970 // remove input routes associated with this uid
2971 SortedVector<audio_source_t> affectedSources;
2972 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2973 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2974 if (route->mUid == uid) {
2975 mInputRoutes.removeItemsAt(i);
2976 if (route->mDeviceDescriptor != 0) {
2977 affectedSources.add(route->mSource);
2978 }
2979 }
2980 }
2981 // reroute inputs if necessary
2982 SortedVector<audio_io_handle_t> inputsToClose;
2983 for (size_t i = 0; i < mInputs.size(); i++) {
2984 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002985 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002986 inputsToClose.add(inputDesc->mIoHandle);
2987 }
2988 }
2989 for (size_t i = 0; i < inputsToClose.size(); i++) {
2990 closeInput(inputsToClose[i]);
2991 }
2992}
2993
Eric Laurentd60560a2015-04-10 11:31:20 -07002994void AudioPolicyManager::clearAudioSources(uid_t uid)
2995{
2996 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2997 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2998 if (sourceDesc->mUid == uid) {
2999 stopAudioSource(mAudioSources.keyAt(i));
3000 }
3001 }
3002}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003003
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003004status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3005 audio_io_handle_t *ioHandle,
3006 audio_devices_t *device)
3007{
Glenn Kasteneeecb982016-02-26 10:44:04 -08003008 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3009 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003010 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003011
François Gaffiedf372692015-03-19 10:43:27 +01003012 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003013}
3014
Eric Laurentd60560a2015-04-10 11:31:20 -07003015status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3016 const audio_attributes_t *attributes,
3017 audio_io_handle_t *handle,
3018 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003019{
Eric Laurentd60560a2015-04-10 11:31:20 -07003020 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3021 if (source == NULL || attributes == NULL || handle == NULL) {
3022 return BAD_VALUE;
3023 }
3024
3025 *handle = AUDIO_IO_HANDLE_NONE;
3026
3027 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3028 source->type != AUDIO_PORT_TYPE_DEVICE) {
3029 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3030 return INVALID_OPERATION;
3031 }
3032
3033 sp<DeviceDescriptor> srcDeviceDesc =
3034 mAvailableInputDevices.getDevice(source->ext.device.type,
3035 String8(source->ext.device.address));
3036 if (srcDeviceDesc == 0) {
3037 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3038 return BAD_VALUE;
3039 }
3040 sp<AudioSourceDescriptor> sourceDesc =
3041 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3042
3043 struct audio_patch dummyPatch;
3044 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3045 sourceDesc->mPatchDesc = patchDesc;
3046
3047 status_t status = connectAudioSource(sourceDesc);
3048 if (status == NO_ERROR) {
3049 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3050 *handle = sourceDesc->getHandle();
3051 }
3052 return status;
3053}
3054
3055status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3056{
3057 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3058
3059 // make sure we only have one patch per source.
3060 disconnectAudioSource(sourceDesc);
3061
3062 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003063 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003064 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3065
3066 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3067 sp<DeviceDescriptor> sinkDeviceDesc =
3068 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3069
3070 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3071 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3072
3073 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3074 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003075 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003076 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3077 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3078 // create patch between src device and output device
3079 // create Hwoutput and add to mHwOutputs
3080 } else {
3081 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3082 audio_io_handle_t output =
3083 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3084 if (output == AUDIO_IO_HANDLE_NONE) {
3085 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3086 return INVALID_OPERATION;
3087 }
3088 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3089 if (outputDesc->isDuplicated()) {
3090 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3091 return INVALID_OPERATION;
3092 }
3093 // create a special patch with no sink and two sources:
3094 // - the second source indicates to PatchPanel through which output mix this patch should
3095 // be connected as well as the stream type for volume control
3096 // - the sink is defined by whatever output device is currently selected for the output
3097 // though which this patch is routed.
3098 patch->num_sinks = 0;
3099 patch->num_sources = 2;
3100 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3101 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3102 patch->sources[1].ext.mix.usecase.stream = stream;
3103 status_t status = mpClientInterface->createAudioPatch(patch,
3104 &afPatchHandle,
3105 0);
3106 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3107 status, afPatchHandle);
3108 if (status != NO_ERROR) {
3109 ALOGW("%s patch panel could not connect device patch, error %d",
3110 __FUNCTION__, status);
3111 return INVALID_OPERATION;
3112 }
3113 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003114 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003115
3116 if (status != NO_ERROR) {
3117 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3118 return status;
3119 }
3120 sourceDesc->mSwOutput = outputDesc;
3121 if (delayMs != 0) {
3122 usleep(delayMs * 1000);
3123 }
3124 }
3125
3126 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3127 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3128
3129 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003130}
3131
Eric Laurent493404d2015-04-21 15:07:36 -07003132status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003133{
Eric Laurentd60560a2015-04-10 11:31:20 -07003134 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3135 ALOGV("%s handle %d", __FUNCTION__, handle);
3136 if (sourceDesc == 0) {
3137 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3138 return BAD_VALUE;
3139 }
3140 status_t status = disconnectAudioSource(sourceDesc);
3141
3142 mAudioSources.removeItem(handle);
3143 return status;
3144}
3145
Andy Hung2ddee192015-12-18 17:34:44 -08003146status_t AudioPolicyManager::setMasterMono(bool mono)
3147{
3148 if (mMasterMono == mono) {
3149 return NO_ERROR;
3150 }
3151 mMasterMono = mono;
3152 // if enabling mono we close all offloaded devices, which will invalidate the
3153 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3154 // for recreating the new AudioTrack as non-offloaded PCM.
3155 //
3156 // If disabling mono, we leave all tracks as is: we don't know which clients
3157 // and tracks are able to be recreated as offloaded. The next "song" should
3158 // play back offloaded.
3159 if (mMasterMono) {
3160 Vector<audio_io_handle_t> offloaded;
3161 for (size_t i = 0; i < mOutputs.size(); ++i) {
3162 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3163 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3164 offloaded.push(desc->mIoHandle);
3165 }
3166 }
3167 for (size_t i = 0; i < offloaded.size(); ++i) {
3168 closeOutput(offloaded[i]);
3169 }
3170 }
3171 // update master mono for all remaining outputs
3172 for (size_t i = 0; i < mOutputs.size(); ++i) {
3173 updateMono(mOutputs.keyAt(i));
3174 }
3175 return NO_ERROR;
3176}
3177
3178status_t AudioPolicyManager::getMasterMono(bool *mono)
3179{
3180 *mono = mMasterMono;
3181 return NO_ERROR;
3182}
3183
Eric Laurentd60560a2015-04-10 11:31:20 -07003184status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3185{
3186 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3187
3188 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3189 if (patchDesc == 0) {
3190 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3191 sourceDesc->mPatchDesc->mHandle);
3192 return BAD_VALUE;
3193 }
3194 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3195
Eric Laurent28d09f02016-03-08 10:43:05 -08003196 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003197 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3198 if (swOutputDesc != 0) {
3199 stopSource(swOutputDesc, stream, false);
3200 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3201 } else {
3202 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3203 if (hwOutputDesc != 0) {
3204 // release patch between src device and output device
3205 // close Hwoutput and remove from mHwOutputs
3206 } else {
3207 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3208 }
3209 }
3210 return NO_ERROR;
3211}
3212
3213sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3214 audio_io_handle_t output, routing_strategy strategy)
3215{
3216 sp<AudioSourceDescriptor> source;
3217 for (size_t i = 0; i < mAudioSources.size(); i++) {
3218 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3219 routing_strategy sourceStrategy =
3220 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3221 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3222 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3223 source = sourceDesc;
3224 break;
3225 }
3226 }
3227 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003228}
3229
Eric Laurente552edb2014-03-10 17:42:56 -07003230// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003231// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003232// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003233uint32_t AudioPolicyManager::nextAudioPortGeneration()
3234{
3235 return android_atomic_inc(&mAudioPortGeneration);
3236}
3237
Eric Laurente0720872014-03-11 09:30:41 -07003238AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003239 :
3240#ifdef AUDIO_POLICY_TEST
3241 Thread(false),
3242#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003243 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003244 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003245 mAudioPortGeneration(1),
3246 mBeaconMuteRefCount(0),
3247 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003248 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003249 mTtsOutputAvailable(false),
3250 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003251{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003252 mUidCached = getuid();
3253 mpClientInterface = clientInterface;
3254
3255 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3256 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3257 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3258 bool speakerDrcEnabled = false;
3259
3260#ifdef USE_XML_AUDIO_POLICY_CONF
3261 mVolumeCurves = new VolumeCurvesCollection();
3262 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3263 mDefaultOutputDevice, speakerDrcEnabled,
3264 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3265 PolicySerializer serializer;
3266 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3267#else
3268 mVolumeCurves = new StreamDescriptorCollection();
3269 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3270 mDefaultOutputDevice, speakerDrcEnabled);
3271 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3272 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3273#endif
3274 ALOGE("could not load audio policy configuration file, setting defaults");
3275 config.setDefault();
3276 }
3277 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3278 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3279
3280 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003281 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3282 if (!engineInstance) {
3283 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3284 return;
3285 }
3286 // Retrieve the Policy Manager Interface
3287 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3288 if (mEngine == NULL) {
3289 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3290 return;
3291 }
3292 mEngine->setObserver(this);
3293 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003294 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003295 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3296
Eric Laurent3a4311c2014-03-17 12:00:47 -07003297 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003298 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003299 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3300 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003301 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003302 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003303 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003304 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003305 continue;
3306 }
3307 // open all output streams needed to access attached devices
3308 // except for direct output streams that are only opened when they are actually
3309 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003310 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003311 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3312 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003313 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003314
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003315 if (!outProfile->hasSupportedDevices()) {
3316 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003317 continue;
3318 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003319 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003320 mTtsOutputAvailable = true;
3321 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003322
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003323 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003324 continue;
3325 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003326 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003327 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3328 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003329 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003330 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003331 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003332 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003333 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003334 if ((profileType & outputDeviceTypes) == 0) {
3335 continue;
3336 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003337 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3338 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003339 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3340 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3341 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3342 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003343
3344 outputDesc->mDevice = profileType;
3345 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3346 config.sample_rate = outputDesc->mSamplingRate;
3347 config.channel_mask = outputDesc->mChannelMask;
3348 config.format = outputDesc->mFormat;
3349 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003350 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003351 &output,
3352 &config,
3353 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003354 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003355 &outputDesc->mLatency,
3356 outputDesc->mFlags);
3357
3358 if (status != NO_ERROR) {
3359 ALOGW("Cannot open output stream for device %08x on hw module %s",
3360 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003361 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003362 } else {
3363 outputDesc->mSamplingRate = config.sample_rate;
3364 outputDesc->mChannelMask = config.channel_mask;
3365 outputDesc->mFormat = config.format;
3366
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003367 for (size_t k = 0; k < supportedDevices.size(); k++) {
3368 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003369 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003370 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3371 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003372 }
3373 }
3374 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003375 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003376 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003377 }
3378 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003379 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003380 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003381 true,
3382 0,
3383 NULL,
3384 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003385 }
Eric Laurente552edb2014-03-10 17:42:56 -07003386 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003387 // open input streams needed to access attached devices to validate
3388 // mAvailableInputDevices list
3389 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3390 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003391 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003392
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003393 if (!inProfile->hasSupportedDevices()) {
3394 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003395 continue;
3396 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003397 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003398 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003399 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3400
Eric Laurentd78f1532014-09-16 16:38:20 -07003401 if ((profileType & inputDeviceTypes) == 0) {
3402 continue;
3403 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003404 sp<AudioInputDescriptor> inputDesc =
3405 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003406
Eric Laurentd78f1532014-09-16 16:38:20 -07003407 inputDesc->mDevice = profileType;
3408
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003409 // find the address
3410 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3411 // the inputs vector must be of size 1, but we don't want to crash here
3412 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3413 : String8("");
3414 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3415 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3416
Eric Laurentd78f1532014-09-16 16:38:20 -07003417 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3418 config.sample_rate = inputDesc->mSamplingRate;
3419 config.channel_mask = inputDesc->mChannelMask;
3420 config.format = inputDesc->mFormat;
3421 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003422 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003423 &input,
3424 &config,
3425 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003426 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003427 AUDIO_SOURCE_MIC,
3428 AUDIO_INPUT_FLAG_NONE);
3429
3430 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003431 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3432 for (size_t k = 0; k < supportedDevices.size(); k++) {
3433 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003434 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003435 if (index >= 0) {
3436 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3437 if (!devDesc->isAttached()) {
3438 devDesc->attach(mHwModules[i]);
3439 devDesc->importAudioPort(inProfile);
3440 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003441 }
3442 }
3443 mpClientInterface->closeInput(input);
3444 } else {
3445 ALOGW("Cannot open input stream for device %08x on hw module %s",
3446 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003447 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003448 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003449 }
3450 }
3451 // make sure all attached devices have been allocated a unique ID
3452 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003453 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003454 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003455 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3456 continue;
3457 }
François Gaffie2110e042015-03-24 08:41:51 +01003458 // The device is now validated and can be appended to the available devices of the engine
3459 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3460 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003461 i++;
3462 }
3463 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003464 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003465 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003466 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3467 continue;
3468 }
François Gaffie2110e042015-03-24 08:41:51 +01003469 // The device is now validated and can be appended to the available devices of the engine
3470 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3471 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003472 i++;
3473 }
3474 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003475 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003476 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003477 }
Eric Laurente552edb2014-03-10 17:42:56 -07003478
3479 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3480
3481 updateDevicesAndOutputs();
3482
3483#ifdef AUDIO_POLICY_TEST
3484 if (mPrimaryOutput != 0) {
3485 AudioParameter outputCmd = AudioParameter();
3486 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003487 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003488
3489 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3490 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003491 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3492 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003493 mTestLatencyMs = 0;
3494 mCurOutput = 0;
3495 mDirectOutput = false;
3496 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3497 mTestOutputs[i] = 0;
3498 }
3499
3500 const size_t SIZE = 256;
3501 char buffer[SIZE];
3502 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3503 run(buffer, ANDROID_PRIORITY_AUDIO);
3504 }
3505#endif //AUDIO_POLICY_TEST
3506}
3507
Eric Laurente0720872014-03-11 09:30:41 -07003508AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003509{
3510#ifdef AUDIO_POLICY_TEST
3511 exit();
3512#endif //AUDIO_POLICY_TEST
3513 for (size_t i = 0; i < mOutputs.size(); i++) {
3514 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003515 }
3516 for (size_t i = 0; i < mInputs.size(); i++) {
3517 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003518 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003519 mAvailableOutputDevices.clear();
3520 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003521 mOutputs.clear();
3522 mInputs.clear();
3523 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003524}
3525
Eric Laurente0720872014-03-11 09:30:41 -07003526status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003527{
Eric Laurent87ffa392015-05-22 10:32:38 -07003528 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003529}
3530
3531#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003532bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003533{
3534 ALOGV("entering threadLoop()");
3535 while (!exitPending())
3536 {
3537 String8 command;
3538 int valueInt;
3539 String8 value;
3540
3541 Mutex::Autolock _l(mLock);
3542 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3543
3544 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3545 AudioParameter param = AudioParameter(command);
3546
3547 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3548 valueInt != 0) {
3549 ALOGV("Test command %s received", command.string());
3550 String8 target;
3551 if (param.get(String8("target"), target) != NO_ERROR) {
3552 target = "Manager";
3553 }
3554 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3555 param.remove(String8("test_cmd_policy_output"));
3556 mCurOutput = valueInt;
3557 }
3558 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3559 param.remove(String8("test_cmd_policy_direct"));
3560 if (value == "false") {
3561 mDirectOutput = false;
3562 } else if (value == "true") {
3563 mDirectOutput = true;
3564 }
3565 }
3566 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3567 param.remove(String8("test_cmd_policy_input"));
3568 mTestInput = valueInt;
3569 }
3570
3571 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3572 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003573 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003574 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003575 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003576 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003577 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003578 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003579 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003580 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003581 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003582 if (target == "Manager") {
3583 mTestFormat = format;
3584 } else if (mTestOutputs[mCurOutput] != 0) {
3585 AudioParameter outputParam = AudioParameter();
3586 outputParam.addInt(String8("format"), format);
3587 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3588 }
3589 }
3590 }
3591 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3592 param.remove(String8("test_cmd_policy_channels"));
3593 int channels = 0;
3594
3595 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003596 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003597 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003598 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003599 }
3600 if (channels != 0) {
3601 if (target == "Manager") {
3602 mTestChannels = channels;
3603 } else if (mTestOutputs[mCurOutput] != 0) {
3604 AudioParameter outputParam = AudioParameter();
3605 outputParam.addInt(String8("channels"), channels);
3606 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3607 }
3608 }
3609 }
3610 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3611 param.remove(String8("test_cmd_policy_sampleRate"));
3612 if (valueInt >= 0 && valueInt <= 96000) {
3613 int samplingRate = valueInt;
3614 if (target == "Manager") {
3615 mTestSamplingRate = samplingRate;
3616 } else if (mTestOutputs[mCurOutput] != 0) {
3617 AudioParameter outputParam = AudioParameter();
3618 outputParam.addInt(String8("sampling_rate"), samplingRate);
3619 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3620 }
3621 }
3622 }
3623
3624 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3625 param.remove(String8("test_cmd_policy_reopen"));
3626
Eric Laurentc75307b2015-03-17 15:29:32 -07003627 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003628
Eric Laurentc75307b2015-03-17 15:29:32 -07003629 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003630
Eric Laurentc75307b2015-03-17 15:29:32 -07003631 removeOutput(mPrimaryOutput->mIoHandle);
3632 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3633 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003634 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003635 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3636 config.sample_rate = outputDesc->mSamplingRate;
3637 config.channel_mask = outputDesc->mChannelMask;
3638 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003639 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003640 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003641 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003642 &config,
3643 &outputDesc->mDevice,
3644 String8(""),
3645 &outputDesc->mLatency,
3646 outputDesc->mFlags);
3647 if (status != NO_ERROR) {
3648 ALOGE("Failed to reopen hardware output stream, "
3649 "samplingRate: %d, format %d, channels %d",
3650 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003651 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003652 outputDesc->mSamplingRate = config.sample_rate;
3653 outputDesc->mChannelMask = config.channel_mask;
3654 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003655 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003656 AudioParameter outputCmd = AudioParameter();
3657 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003658 mpClientInterface->setParameters(handle, outputCmd.toString());
3659 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003660 }
3661 }
3662
3663
3664 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3665 }
3666 }
3667 return false;
3668}
3669
Eric Laurente0720872014-03-11 09:30:41 -07003670void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003671{
3672 {
3673 AutoMutex _l(mLock);
3674 requestExit();
3675 mWaitWorkCV.signal();
3676 }
3677 requestExitAndWait();
3678}
3679
Eric Laurente0720872014-03-11 09:30:41 -07003680int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003681{
3682 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3683 if (output == mTestOutputs[i]) return i;
3684 }
3685 return 0;
3686}
3687#endif //AUDIO_POLICY_TEST
3688
3689// ---
3690
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003691void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003692{
François Gaffie98cc1912015-03-18 17:52:40 +01003693 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003694 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003695 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003696 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003697}
3698
François Gaffie53615e22015-03-19 09:24:12 +01003699void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3700{
3701 mOutputs.removeItem(output);
3702}
3703
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003704void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003705{
François Gaffie98cc1912015-03-18 17:52:40 +01003706 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003707 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003708 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003709}
Eric Laurente552edb2014-03-10 17:42:56 -07003710
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003711void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003712 const audio_devices_t device /*in*/,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003713 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003714 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003715 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003716 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003717 if (devDesc != 0) {
3718 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3719 desc->mIoHandle, address.string());
3720 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003721 }
3722}
3723
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003724status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003725 audio_policy_dev_state_t state,
3726 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003727 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003728{
François Gaffie53615e22015-03-19 09:24:12 +01003729 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003730 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003731
3732 if (audio_device_is_digital(device)) {
3733 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003734 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003735 }
Eric Laurente552edb2014-03-10 17:42:56 -07003736
Eric Laurent3b73df72014-03-11 09:06:29 -07003737 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003738 // first list already open outputs that can be routed to this device
3739 for (size_t i = 0; i < mOutputs.size(); i++) {
3740 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003741 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003742 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003743 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3744 outputs.add(mOutputs.keyAt(i));
3745 } else {
3746 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003747 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003748 }
Eric Laurente552edb2014-03-10 17:42:56 -07003749 }
3750 }
3751 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003752 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003753 for (size_t i = 0; i < mHwModules.size(); i++)
3754 {
3755 if (mHwModules[i]->mHandle == 0) {
3756 continue;
3757 }
3758 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3759 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003760 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003761 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003762 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003763 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003764 profiles.add(profile);
3765 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3766 }
Eric Laurente552edb2014-03-10 17:42:56 -07003767 }
3768 }
3769 }
3770
Eric Laurent7b279bb2015-12-14 10:18:23 -08003771 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003772
Eric Laurente552edb2014-03-10 17:42:56 -07003773 if (profiles.isEmpty() && outputs.isEmpty()) {
3774 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3775 return BAD_VALUE;
3776 }
3777
3778 // open outputs for matching profiles if needed. Direct outputs are also opened to
3779 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3780 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003781 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003782
3783 // nothing to do if one output is already opened for this profile
3784 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003785 for (j = 0; j < outputs.size(); j++) {
3786 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003787 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003788 // matching profile: save the sample rates, format and channel masks supported
3789 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003790 if (audio_device_is_digital(device)) {
3791 devDesc->importAudioPort(profile);
3792 }
Eric Laurente552edb2014-03-10 17:42:56 -07003793 break;
3794 }
3795 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003796 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003797 continue;
3798 }
3799
Eric Laurent83b88082014-06-20 18:31:16 -07003800 ALOGV("opening output for device %08x with params %s profile %p",
3801 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003802 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003803 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003804 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3805 config.sample_rate = desc->mSamplingRate;
3806 config.channel_mask = desc->mChannelMask;
3807 config.format = desc->mFormat;
3808 config.offload_info.sample_rate = desc->mSamplingRate;
3809 config.offload_info.channel_mask = desc->mChannelMask;
3810 config.offload_info.format = desc->mFormat;
3811 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003812 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003813 &output,
3814 &config,
3815 &desc->mDevice,
3816 address,
3817 &desc->mLatency,
3818 desc->mFlags);
3819 if (status == NO_ERROR) {
3820 desc->mSamplingRate = config.sample_rate;
3821 desc->mChannelMask = config.channel_mask;
3822 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003823
Eric Laurentd4692962014-05-05 18:13:44 -07003824 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003825 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003826 char *param = audio_device_address_to_parameter(device, address);
3827 mpClientInterface->setParameters(output, String8(param));
3828 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003829 }
Phil Burk00eeb322016-03-31 12:41:00 -07003830 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003831 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003832 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003833 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003834 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003835 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003836 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003837 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003838 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003839 config.offload_info.sample_rate = config.sample_rate;
3840 config.offload_info.channel_mask = config.channel_mask;
3841 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003842 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003843 &output,
3844 &config,
3845 &desc->mDevice,
3846 address,
3847 &desc->mLatency,
3848 desc->mFlags);
3849 if (status == NO_ERROR) {
3850 desc->mSamplingRate = config.sample_rate;
3851 desc->mChannelMask = config.channel_mask;
3852 desc->mFormat = config.format;
3853 } else {
3854 output = AUDIO_IO_HANDLE_NONE;
3855 }
Eric Laurentd4692962014-05-05 18:13:44 -07003856 }
3857
Eric Laurentcf2c0212014-07-25 16:20:43 -07003858 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003859 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003860 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003861 sp<AudioPolicyMix> policyMix;
3862 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003863 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3864 address.string());
3865 }
François Gaffie036e1e92015-03-19 10:16:24 +01003866 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003867 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003868
Eric Laurent87ffa392015-05-22 10:32:38 -07003869 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3870 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003871 // no duplicated output for direct outputs and
3872 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003873 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003874
Eric Laurentd4692962014-05-05 18:13:44 -07003875 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003876 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003877
Eric Laurentd4692962014-05-05 18:13:44 -07003878 //TODO: configure audio effect output stage here
3879
3880 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003881 duplicatedOutput =
3882 mpClientInterface->openDuplicateOutput(output,
3883 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003884 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003885 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003886 sp<SwAudioOutputDescriptor> dupOutputDesc =
3887 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3888 dupOutputDesc->mOutput1 = mPrimaryOutput;
3889 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003890 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3891 dupOutputDesc->mFormat = desc->mFormat;
3892 dupOutputDesc->mChannelMask = desc->mChannelMask;
3893 dupOutputDesc->mLatency = desc->mLatency;
3894 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003895 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003896 } else {
3897 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003898 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003899 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003900 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003901 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003902 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003903 }
Eric Laurente552edb2014-03-10 17:42:56 -07003904 }
3905 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003906 } else {
3907 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003908 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003909 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003910 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003911 profiles.removeAt(profile_index);
3912 profile_index--;
3913 } else {
3914 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003915 // Load digital format info only for digital devices
3916 if (audio_device_is_digital(device)) {
3917 devDesc->importAudioPort(profile);
3918 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003919
François Gaffie53615e22015-03-19 09:24:12 +01003920 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003921 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3922 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003923 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003924 NULL/*patch handle*/, address.string());
3925 }
Eric Laurente552edb2014-03-10 17:42:56 -07003926 ALOGV("checkOutputsForDevice(): adding output %d", output);
3927 }
3928 }
3929
3930 if (profiles.isEmpty()) {
3931 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3932 return BAD_VALUE;
3933 }
Eric Laurentd4692962014-05-05 18:13:44 -07003934 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003935 // check if one opened output is not needed any more after disconnecting one device
3936 for (size_t i = 0; i < mOutputs.size(); i++) {
3937 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003938 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003939 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003940 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003941 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003942 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003943 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003944 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3945 mOutputs.keyAt(i));
3946 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003947 }
Eric Laurente552edb2014-03-10 17:42:56 -07003948 }
3949 }
Eric Laurentd4692962014-05-05 18:13:44 -07003950 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003951 for (size_t i = 0; i < mHwModules.size(); i++)
3952 {
3953 if (mHwModules[i]->mHandle == 0) {
3954 continue;
3955 }
3956 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3957 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003958 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003959 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003960 ALOGV("checkOutputsForDevice(): "
3961 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003962 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003963 }
3964 }
3965 }
3966 }
3967 return NO_ERROR;
3968}
3969
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003970status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003971 audio_policy_dev_state_t state,
3972 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003973 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003974{
Paul McLean9080a4c2015-06-18 08:24:02 -07003975 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003976 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003977
3978 if (audio_device_is_digital(device)) {
3979 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003980 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003981 }
3982
Eric Laurentd4692962014-05-05 18:13:44 -07003983 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3984 // first list already open inputs that can be routed to this device
3985 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3986 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003987 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003988 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3989 inputs.add(mInputs.keyAt(input_index));
3990 }
3991 }
3992
3993 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003994 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003995 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3996 {
3997 if (mHwModules[module_idx]->mHandle == 0) {
3998 continue;
3999 }
4000 for (size_t profile_index = 0;
4001 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4002 profile_index++)
4003 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004004 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4005
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004006 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004007 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004008 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004009 profiles.add(profile);
4010 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4011 profile_index, module_idx);
4012 }
Eric Laurentd4692962014-05-05 18:13:44 -07004013 }
4014 }
4015 }
4016
4017 if (profiles.isEmpty() && inputs.isEmpty()) {
4018 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4019 return BAD_VALUE;
4020 }
4021
4022 // open inputs for matching profiles if needed. Direct inputs are also opened to
4023 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4024 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4025
Eric Laurent1c333e22014-05-20 10:48:17 -07004026 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004027 // nothing to do if one input is already opened for this profile
4028 size_t input_index;
4029 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4030 desc = mInputs.valueAt(input_index);
4031 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004032 if (audio_device_is_digital(device)) {
4033 devDesc->importAudioPort(profile);
4034 }
Eric Laurentd4692962014-05-05 18:13:44 -07004035 break;
4036 }
4037 }
4038 if (input_index != mInputs.size()) {
4039 continue;
4040 }
4041
4042 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4043 desc = new AudioInputDescriptor(profile);
4044 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004045 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4046 config.sample_rate = desc->mSamplingRate;
4047 config.channel_mask = desc->mChannelMask;
4048 config.format = desc->mFormat;
4049 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004050 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004051 &input,
4052 &config,
4053 &desc->mDevice,
4054 address,
4055 AUDIO_SOURCE_MIC,
4056 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004057
Eric Laurentcf2c0212014-07-25 16:20:43 -07004058 if (status == NO_ERROR) {
4059 desc->mSamplingRate = config.sample_rate;
4060 desc->mChannelMask = config.channel_mask;
4061 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004062
Eric Laurentd4692962014-05-05 18:13:44 -07004063 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004064 char *param = audio_device_address_to_parameter(device, address);
4065 mpClientInterface->setParameters(input, String8(param));
4066 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004067 }
Phil Burk00eeb322016-03-31 12:41:00 -07004068 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004069 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004070 ALOGW("checkInputsForDevice() direct input missing param");
4071 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004072 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004073 }
4074
4075 if (input != 0) {
4076 addInput(input, desc);
4077 }
4078 } // endif input != 0
4079
Eric Laurentcf2c0212014-07-25 16:20:43 -07004080 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004081 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004082 profiles.removeAt(profile_index);
4083 profile_index--;
4084 } else {
4085 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004086 if (audio_device_is_digital(device)) {
4087 devDesc->importAudioPort(profile);
4088 }
Eric Laurentd4692962014-05-05 18:13:44 -07004089 ALOGV("checkInputsForDevice(): adding input %d", input);
4090 }
4091 } // end scan profiles
4092
4093 if (profiles.isEmpty()) {
4094 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4095 return BAD_VALUE;
4096 }
4097 } else {
4098 // Disconnect
4099 // check if one opened input is not needed any more after disconnecting one device
4100 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4101 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004102 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004103 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4104 mInputs.keyAt(input_index));
4105 inputs.add(mInputs.keyAt(input_index));
4106 }
4107 }
4108 // Clear any profiles associated with the disconnected device.
4109 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4110 if (mHwModules[module_index]->mHandle == 0) {
4111 continue;
4112 }
4113 for (size_t profile_index = 0;
4114 profile_index < mHwModules[module_index]->mInputProfiles.size();
4115 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004116 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004117 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004118 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004119 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004120 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004121 }
4122 }
4123 }
4124 } // end disconnect
4125
4126 return NO_ERROR;
4127}
4128
4129
Eric Laurente0720872014-03-11 09:30:41 -07004130void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004131{
4132 ALOGV("closeOutput(%d)", output);
4133
Eric Laurentc75307b2015-03-17 15:29:32 -07004134 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004135 if (outputDesc == NULL) {
4136 ALOGW("closeOutput() unknown output %d", output);
4137 return;
4138 }
François Gaffie036e1e92015-03-19 10:16:24 +01004139 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004140
Eric Laurente552edb2014-03-10 17:42:56 -07004141 // look for duplicated outputs connected to the output being removed.
4142 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004143 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004144 if (dupOutputDesc->isDuplicated() &&
4145 (dupOutputDesc->mOutput1 == outputDesc ||
4146 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004147 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004148 if (dupOutputDesc->mOutput1 == outputDesc) {
4149 outputDesc2 = dupOutputDesc->mOutput2;
4150 } else {
4151 outputDesc2 = dupOutputDesc->mOutput1;
4152 }
4153 // As all active tracks on duplicated output will be deleted,
4154 // and as they were also referenced on the other output, the reference
4155 // count for their stream type must be adjusted accordingly on
4156 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004157 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004158 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004159 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004160 }
4161 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4162 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4163
4164 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004165 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004166 }
4167 }
4168
Eric Laurent05b90f82014-08-27 15:32:29 -07004169 nextAudioPortGeneration();
4170
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004171 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004172 if (index >= 0) {
4173 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004174 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004175 mAudioPatches.removeItemsAt(index);
4176 mpClientInterface->onAudioPatchListUpdate();
4177 }
4178
Eric Laurente552edb2014-03-10 17:42:56 -07004179 AudioParameter param;
4180 param.add(String8("closing"), String8("true"));
4181 mpClientInterface->setParameters(output, param.toString());
4182
4183 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004184 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004185 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004186}
4187
4188void AudioPolicyManager::closeInput(audio_io_handle_t input)
4189{
4190 ALOGV("closeInput(%d)", input);
4191
4192 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4193 if (inputDesc == NULL) {
4194 ALOGW("closeInput() unknown input %d", input);
4195 return;
4196 }
4197
Eric Laurent6a94d692014-05-20 11:18:06 -07004198 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004199
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004200 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004201 if (index >= 0) {
4202 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004203 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004204 mAudioPatches.removeItemsAt(index);
4205 mpClientInterface->onAudioPatchListUpdate();
4206 }
4207
4208 mpClientInterface->closeInput(input);
4209 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004210}
4211
Eric Laurentc75307b2015-03-17 15:29:32 -07004212SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4213 audio_devices_t device,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004214 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004215{
4216 SortedVector<audio_io_handle_t> outputs;
4217
4218 ALOGVV("getOutputsForDevice() device %04x", device);
4219 for (size_t i = 0; i < openOutputs.size(); i++) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -08004220 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004221 i, openOutputs.valueAt(i)->isDuplicated(),
4222 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004223 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4224 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4225 outputs.add(openOutputs.keyAt(i));
4226 }
4227 }
4228 return outputs;
4229}
4230
Eric Laurente0720872014-03-11 09:30:41 -07004231bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004232 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004233{
4234 if (outputs1.size() != outputs2.size()) {
4235 return false;
4236 }
4237 for (size_t i = 0; i < outputs1.size(); i++) {
4238 if (outputs1[i] != outputs2[i]) {
4239 return false;
4240 }
4241 }
4242 return true;
4243}
4244
Eric Laurente0720872014-03-11 09:30:41 -07004245void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004246{
4247 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4248 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4249 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4250 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4251
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004252 // also take into account external policy-related changes: add all outputs which are
4253 // associated with policies in the "before" and "after" output vectors
4254 ALOGVV("checkOutputForStrategy(): policy related outputs");
4255 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004256 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004257 if (desc != 0 && desc->mPolicyMix != NULL) {
4258 srcOutputs.add(desc->mIoHandle);
4259 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4260 }
4261 }
4262 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004263 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004264 if (desc != 0 && desc->mPolicyMix != NULL) {
4265 dstOutputs.add(desc->mIoHandle);
4266 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4267 }
4268 }
4269
Eric Laurente552edb2014-03-10 17:42:56 -07004270 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4271 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4272 strategy, srcOutputs[0], dstOutputs[0]);
4273 // mute strategy while moving tracks from one output to another
4274 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004275 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004276 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004277 setStrategyMute(strategy, true, desc);
4278 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004279 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004280 sp<AudioSourceDescriptor> source =
4281 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4282 if (source != 0){
4283 connectAudioSource(source);
4284 }
Eric Laurente552edb2014-03-10 17:42:56 -07004285 }
4286
4287 // Move effects associated to this strategy from previous output to new output
4288 if (strategy == STRATEGY_MEDIA) {
4289 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4290 SortedVector<audio_io_handle_t> moved;
4291 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004292 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4293 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4294 effectDesc->mIo != fxOutput) {
4295 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004296 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4297 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004298 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004299 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004300 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004301 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004302 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004303 }
4304 }
4305 }
4306 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004307 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004308 if (getStrategy((audio_stream_type_t)i) == strategy) {
4309 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004310 }
4311 }
4312 }
4313}
4314
Eric Laurente0720872014-03-11 09:30:41 -07004315void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004316{
François Gaffie2110e042015-03-24 08:41:51 +01004317 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004318 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004319 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004320 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004321 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004322 checkOutputForStrategy(STRATEGY_SONIFICATION);
4323 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004324 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004325 checkOutputForStrategy(STRATEGY_MEDIA);
4326 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004327 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004328}
4329
Eric Laurente0720872014-03-11 09:30:41 -07004330void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004331{
François Gaffie53615e22015-03-19 09:24:12 +01004332 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004333 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004334 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004335 return;
4336 }
4337
Eric Laurent3a4311c2014-03-17 12:00:47 -07004338 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004339 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4340 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4341 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004342 // suspend A2DP output if:
4343 // (NOT already suspended) &&
4344 // ((SCO device is connected &&
4345 // (forced usage for communication || for record is SCO))) ||
4346 // (phone state is ringing || in call)
4347 //
4348 // restore A2DP output if:
4349 // (Already suspended) &&
4350 // ((SCO device is NOT connected ||
4351 // (forced usage NOT for communication && NOT for record is SCO))) &&
4352 // (phone state is NOT ringing && NOT in call)
4353 //
4354 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004355 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004356 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4357 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4358 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4359 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004360
4361 mpClientInterface->restoreOutput(a2dpOutput);
4362 mA2dpSuspended = false;
4363 }
4364 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004365 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004366 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4367 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4368 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4369 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004370
4371 mpClientInterface->suspendOutput(a2dpOutput);
4372 mA2dpSuspended = true;
4373 }
4374 }
4375}
4376
Eric Laurentc75307b2015-03-17 15:29:32 -07004377audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4378 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004379{
4380 audio_devices_t device = AUDIO_DEVICE_NONE;
4381
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004382 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004383 if (index >= 0) {
4384 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4385 if (patchDesc->mUid != mUidCached) {
4386 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004387 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004388 return outputDesc->device();
4389 }
4390 }
4391
Eric Laurente552edb2014-03-10 17:42:56 -07004392 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004393 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004394 // use device for strategy enforced audible
4395 // 2: we are in call or the strategy phone is active on the output:
4396 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004397 // 3: the strategy for enforced audible is active but not enforced on the output:
4398 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004399 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004400 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004401 // 5: the strategy accessibility is active on the output:
4402 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004403 // 6: the strategy "respectful" sonification is active on the output:
4404 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004405 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004406 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004407 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004408 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004409 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004410 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004411 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004412 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004413 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4414 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004415 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004416 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004417 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004418 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004419 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004420 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004421 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4422 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004423 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004424 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004425 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004426 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004427 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004428 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004429 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004430 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004431 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004432 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004433 }
4434
Eric Laurent1c333e22014-05-20 10:48:17 -07004435 ALOGV("getNewOutputDevice() selected device %x", device);
4436 return device;
4437}
4438
Eric Laurent232f26f2016-02-17 18:06:27 -08004439audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
Eric Laurent1c333e22014-05-20 10:48:17 -07004440{
Eric Laurent232f26f2016-02-17 18:06:27 -08004441 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004442
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004443 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004444 if (index >= 0) {
4445 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4446 if (patchDesc->mUid != mUidCached) {
4447 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004448 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004449 return inputDesc->mDevice;
4450 }
4451 }
4452
Eric Laurent232f26f2016-02-17 18:06:27 -08004453 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004454
Eric Laurente552edb2014-03-10 17:42:56 -07004455 return device;
4456}
4457
Eric Laurent794fde22016-03-11 09:50:45 -08004458bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4459 audio_stream_type_t stream2) {
4460 return ((stream1 == stream2) ||
4461 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4462 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004463}
4464
Eric Laurente0720872014-03-11 09:30:41 -07004465uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004466 return (uint32_t)getStrategy(stream);
4467}
4468
Eric Laurente0720872014-03-11 09:30:41 -07004469audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004470 // By checking the range of stream before calling getStrategy, we avoid
4471 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4472 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004473 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004474 return AUDIO_DEVICE_NONE;
4475 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004476 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004477 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4478 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004479 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004480 }
Eric Laurent794fde22016-03-11 09:50:45 -08004481 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004482 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004483 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004484 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4485 for (size_t i = 0; i < outputs.size(); i++) {
4486 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004487 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004488 curDevices |= outputDesc->device();
4489 }
4490 }
4491 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004492 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004493
4494 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4495 and doesn't really need to.*/
4496 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4497 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4498 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4499 }
Eric Laurente552edb2014-03-10 17:42:56 -07004500 return devices;
4501}
4502
François Gaffie2110e042015-03-24 08:41:51 +01004503routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4504{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004505 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004506 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004507}
4508
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004509uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4510 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004511 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4512 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4513 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004514 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4515 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4516 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004517 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004518 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004519}
4520
Eric Laurente0720872014-03-11 09:30:41 -07004521void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004522 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004523 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004524 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4525 updateDevicesAndOutputs();
4526 break;
4527 default:
4528 break;
4529 }
4530}
4531
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004532uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004533
4534 // skip beacon mute management if a dedicated TTS output is available
4535 if (mTtsOutputAvailable) {
4536 return 0;
4537 }
4538
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004539 switch(event) {
4540 case STARTING_OUTPUT:
4541 mBeaconMuteRefCount++;
4542 break;
4543 case STOPPING_OUTPUT:
4544 if (mBeaconMuteRefCount > 0) {
4545 mBeaconMuteRefCount--;
4546 }
4547 break;
4548 case STARTING_BEACON:
4549 mBeaconPlayingRefCount++;
4550 break;
4551 case STOPPING_BEACON:
4552 if (mBeaconPlayingRefCount > 0) {
4553 mBeaconPlayingRefCount--;
4554 }
4555 break;
4556 }
4557
4558 if (mBeaconMuteRefCount > 0) {
4559 // any playback causes beacon to be muted
4560 return setBeaconMute(true);
4561 } else {
4562 // no other playback: unmute when beacon starts playing, mute when it stops
4563 return setBeaconMute(mBeaconPlayingRefCount == 0);
4564 }
4565}
4566
4567uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4568 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4569 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4570 // keep track of muted state to avoid repeating mute/unmute operations
4571 if (mBeaconMuted != mute) {
4572 // mute/unmute AUDIO_STREAM_TTS on all outputs
4573 ALOGV("\t muting %d", mute);
4574 uint32_t maxLatency = 0;
4575 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004576 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004577 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004578 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004579 0 /*delay*/, AUDIO_DEVICE_NONE);
4580 const uint32_t latency = desc->latency() * 2;
4581 if (latency > maxLatency) {
4582 maxLatency = latency;
4583 }
4584 }
4585 mBeaconMuted = mute;
4586 return maxLatency;
4587 }
4588 return 0;
4589}
4590
Eric Laurente0720872014-03-11 09:30:41 -07004591audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004592 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004593{
Paul McLeanaa981192015-03-21 09:55:15 -07004594 // Routing
4595 // see if we have an explicit route
4596 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4597 // (getStrategy(stream)).
4598 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4599 // and activity count is non-zero
4600 // the device = the device from the descriptor in the RouteMap, and exit.
4601 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4602 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004603 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4604 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004605 return route->mDeviceDescriptor->type();
4606 }
4607 }
4608
Eric Laurente552edb2014-03-10 17:42:56 -07004609 if (fromCache) {
4610 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4611 strategy, mDeviceForStrategy[strategy]);
4612 return mDeviceForStrategy[strategy];
4613 }
François Gaffie2110e042015-03-24 08:41:51 +01004614 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004615}
4616
Eric Laurente0720872014-03-11 09:30:41 -07004617void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004618{
4619 for (int i = 0; i < NUM_STRATEGIES; i++) {
4620 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4621 }
4622 mPreviousOutputs = mOutputs;
4623}
4624
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004625uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004626 audio_devices_t prevDevice,
4627 uint32_t delayMs)
4628{
4629 // mute/unmute strategies using an incompatible device combination
4630 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4631 // if unmuting, unmute only after the specified delay
4632 if (outputDesc->isDuplicated()) {
4633 return 0;
4634 }
4635
4636 uint32_t muteWaitMs = 0;
4637 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004638 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004639
4640 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4641 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004642 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004643 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4644 bool doMute = false;
4645
4646 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4647 doMute = true;
4648 outputDesc->mStrategyMutedByDevice[i] = true;
4649 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4650 doMute = true;
4651 outputDesc->mStrategyMutedByDevice[i] = false;
4652 }
Eric Laurent99401132014-05-07 19:48:15 -07004653 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004654 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004655 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004656 // skip output if it does not share any device with current output
4657 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4658 == AUDIO_DEVICE_NONE) {
4659 continue;
4660 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -08004661 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004662 mute ? "muting" : "unmuting", i, curDevice);
4663 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004664 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004665 if (mute) {
4666 // FIXME: should not need to double latency if volume could be applied
4667 // immediately by the audioflinger mixer. We must account for the delay
4668 // between now and the next time the audioflinger thread for this output
4669 // will process a buffer (which corresponds to one buffer size,
4670 // usually 1/2 or 1/4 of the latency).
4671 if (muteWaitMs < desc->latency() * 2) {
4672 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004673 }
4674 }
4675 }
4676 }
4677 }
4678 }
4679
Eric Laurent99401132014-05-07 19:48:15 -07004680 // temporary mute output if device selection changes to avoid volume bursts due to
4681 // different per device volumes
4682 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004683 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4684 // temporary mute duration is conservatively set to 4 times the reported latency
4685 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4686 if (muteWaitMs < tempMuteWaitMs) {
4687 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004688 }
Eric Laurentdc462862016-07-19 12:29:53 -07004689
Eric Laurent99401132014-05-07 19:48:15 -07004690 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004691 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004692 // make sure that we do not start the temporary mute period too early in case of
4693 // delayed device change
4694 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004695 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004696 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004697 }
4698 }
4699 }
4700
Eric Laurente552edb2014-03-10 17:42:56 -07004701 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4702 if (muteWaitMs > delayMs) {
4703 muteWaitMs -= delayMs;
4704 usleep(muteWaitMs * 1000);
4705 return muteWaitMs;
4706 }
4707 return 0;
4708}
4709
Eric Laurentc75307b2015-03-17 15:29:32 -07004710uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004711 audio_devices_t device,
4712 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004713 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004714 audio_patch_handle_t *patchHandle,
4715 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004716{
Eric Laurentc75307b2015-03-17 15:29:32 -07004717 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 AudioParameter param;
4719 uint32_t muteWaitMs;
4720
4721 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004722 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4723 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004724 return muteWaitMs;
4725 }
4726 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4727 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004728 if ((device != AUDIO_DEVICE_NONE) &&
4729 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004730 return 0;
4731 }
4732
4733 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004734 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004735
4736 audio_devices_t prevDevice = outputDesc->mDevice;
4737
Paul McLeanaa981192015-03-21 09:55:15 -07004738 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004739
4740 if (device != AUDIO_DEVICE_NONE) {
4741 outputDesc->mDevice = device;
4742 }
4743 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4744
4745 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004746 // the requested device is AUDIO_DEVICE_NONE
4747 // OR the requested device is the same as current device
4748 // AND force is not specified
4749 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004750 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004751 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4752 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004753 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004754 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004755 return muteWaitMs;
4756 }
4757
4758 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004759
Eric Laurente552edb2014-03-10 17:42:56 -07004760 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004761 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004762 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004763 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004764 DeviceVector deviceList;
4765 if ((address == NULL) || (strlen(address) == 0)) {
4766 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4767 } else {
4768 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4769 }
4770
Eric Laurent1c333e22014-05-20 10:48:17 -07004771 if (!deviceList.isEmpty()) {
4772 struct audio_patch patch;
4773 outputDesc->toAudioPortConfig(&patch.sources[0]);
4774 patch.num_sources = 1;
4775 patch.num_sinks = 0;
4776 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4777 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004778 patch.num_sinks++;
4779 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004780 ssize_t index;
4781 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4782 index = mAudioPatches.indexOfKey(*patchHandle);
4783 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004784 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 }
4786 sp< AudioPatch> patchDesc;
4787 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4788 if (index >= 0) {
4789 patchDesc = mAudioPatches.valueAt(index);
4790 afPatchHandle = patchDesc->mAfPatchHandle;
4791 }
4792
Eric Laurent1c333e22014-05-20 10:48:17 -07004793 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 &afPatchHandle,
4795 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4797 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004799 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004800 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004801 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004802 addAudioPatch(patchDesc->mHandle, patchDesc);
4803 } else {
4804 patchDesc->mPatch = patch;
4805 }
4806 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 if (patchHandle) {
4808 *patchHandle = patchDesc->mHandle;
4809 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004810 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004812 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004813 }
4814 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004815
4816 // inform all input as well
4817 for (size_t i = 0; i < mInputs.size(); i++) {
4818 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004819 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004820 AudioParameter inputCmd = AudioParameter();
4821 ALOGV("%s: inform input %d of device:%d", __func__,
4822 inputDescriptor->mIoHandle, device);
4823 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4824 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4825 inputCmd.toString(),
4826 delayMs);
4827 }
4828 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004829 }
Eric Laurente552edb2014-03-10 17:42:56 -07004830
4831 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004832 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004833
4834 return muteWaitMs;
4835}
4836
Eric Laurentc75307b2015-03-17 15:29:32 -07004837status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004838 int delayMs,
4839 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004840{
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 ssize_t index;
4842 if (patchHandle) {
4843 index = mAudioPatches.indexOfKey(*patchHandle);
4844 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004845 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004846 }
4847 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 return INVALID_OPERATION;
4849 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004850 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4851 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004852 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004853 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 removeAudioPatch(patchDesc->mHandle);
4855 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004856 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004857 return status;
4858}
4859
4860status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4861 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 bool force,
4863 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004864{
4865 status_t status = NO_ERROR;
4866
Eric Laurent1f2f2232014-06-02 12:01:23 -07004867 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004868 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4869 inputDesc->mDevice = device;
4870
4871 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4872 if (!deviceList.isEmpty()) {
4873 struct audio_patch patch;
4874 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004875 // AUDIO_SOURCE_HOTWORD is for internal use only:
4876 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004877 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004878 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004879 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4880 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004881 patch.num_sinks = 1;
4882 //only one input device for now
4883 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004884 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 ssize_t index;
4886 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4887 index = mAudioPatches.indexOfKey(*patchHandle);
4888 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004889 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004890 }
4891 sp< AudioPatch> patchDesc;
4892 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4893 if (index >= 0) {
4894 patchDesc = mAudioPatches.valueAt(index);
4895 afPatchHandle = patchDesc->mAfPatchHandle;
4896 }
4897
Eric Laurent1c333e22014-05-20 10:48:17 -07004898 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 0);
4901 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004903 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004904 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004905 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004906 addAudioPatch(patchDesc->mHandle, patchDesc);
4907 } else {
4908 patchDesc->mPatch = patch;
4909 }
4910 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 if (patchHandle) {
4912 *patchHandle = patchDesc->mHandle;
4913 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004914 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004915 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004916 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004917 }
4918 }
4919 }
4920 return status;
4921}
4922
Eric Laurent6a94d692014-05-20 11:18:06 -07004923status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4924 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004925{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004926 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 ssize_t index;
4928 if (patchHandle) {
4929 index = mAudioPatches.indexOfKey(*patchHandle);
4930 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004931 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004932 }
4933 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 return INVALID_OPERATION;
4935 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4937 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004939 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004940 removeAudioPatch(patchDesc->mHandle);
4941 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004942 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004943 return status;
4944}
4945
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004946sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004947 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004948 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004949 audio_format_t& format,
4950 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004951 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004952{
4953 // Choose an input profile based on the requested capture parameters: select the first available
4954 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004955 //
4956 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4957 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004958
4959 for (size_t i = 0; i < mHwModules.size(); i++)
4960 {
4961 if (mHwModules[i]->mHandle == 0) {
4962 continue;
4963 }
4964 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4965 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004967 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004968 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004969 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004970 format,
4971 &format /*updatedFormat*/,
4972 channelMask,
4973 &channelMask /*updatedChannelMask*/,
4974 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004975
Eric Laurente552edb2014-03-10 17:42:56 -07004976 return profile;
4977 }
4978 }
4979 }
4980 return NULL;
4981}
4982
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004983
4984audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004985 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004986{
François Gaffie036e1e92015-03-19 10:16:24 +01004987 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4988 audio_devices_t selectedDeviceFromMix =
4989 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004990
François Gaffie036e1e92015-03-19 10:16:24 +01004991 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4992 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004993 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004994 return getDeviceForInputSource(inputSource);
4995}
4996
4997audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4998{
Paul McLean466dc8e2015-04-17 13:15:36 -06004999 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5000 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005001 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005002 return route->mDeviceDescriptor->type();
5003 }
5004 }
5005
5006 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005007}
5008
Eric Laurente0720872014-03-11 09:30:41 -07005009float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005010 int index,
5011 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005012{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005013 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005014
5015 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5016 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5017 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5018 // the ringtone volume
5019 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5020 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5021 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5022 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5023 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5024 }
5025
Eric Laurente552edb2014-03-10 17:42:56 -07005026 // if a headset is connected, apply the following rules to ring tones and notifications
5027 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005028 // - always attenuate notifications volume by 6dB
5029 // - attenuate ring tones volume by 6dB unless music is not playing and
5030 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005031 // - if music is playing, always limit the volume to current music volume,
5032 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005033 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005034 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5035 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5036 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5037 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5038 ((stream_strategy == STRATEGY_SONIFICATION)
5039 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005040 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005041 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005042 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005043 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005044 // when the phone is ringing we must consider that music could have been paused just before
5045 // by the music application and behave as if music was active if the last music track was
5046 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005047 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005048 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005049 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005050 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005051 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005052 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5053 musicDevice),
5054 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005055 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5056 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005057 if (volumeDB > minVolDB) {
5058 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005059 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005060 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005061 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5062 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5063 // on A2DP, also ensure notification volume is not too low compared to media when
5064 // intended to be played
5065 if ((volumeDB > -96.0f) &&
5066 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5067 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5068 stream, device,
5069 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5070 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5071 }
5072 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005073 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5074 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005075 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005076 }
5077 }
5078
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005079 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005080}
5081
Eric Laurente0720872014-03-11 09:30:41 -07005082status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005083 int index,
5084 const sp<AudioOutputDescriptor>& outputDesc,
5085 audio_devices_t device,
5086 int delayMs,
5087 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005088{
Eric Laurente552edb2014-03-10 17:42:56 -07005089 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005090 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005091 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005092 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005093 return NO_ERROR;
5094 }
François Gaffie2110e042015-03-24 08:41:51 +01005095 audio_policy_forced_cfg_t forceUseForComm =
5096 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005097 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005098 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5099 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005100 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005101 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005102 return INVALID_OPERATION;
5103 }
5104
Eric Laurentc75307b2015-03-17 15:29:32 -07005105 if (device == AUDIO_DEVICE_NONE) {
5106 device = outputDesc->device();
5107 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005108
Eric Laurentffbc80f2015-03-18 18:30:19 -07005109 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005110 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005111 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005112 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005113
Eric Laurentffbc80f2015-03-18 18:30:19 -07005114 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005115
Eric Laurent3b73df72014-03-11 09:06:29 -07005116 if (stream == AUDIO_STREAM_VOICE_CALL ||
5117 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005118 float voiceVolume;
5119 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005120 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005121 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005122 } else {
5123 voiceVolume = 1.0;
5124 }
5125
Eric Laurent18fba842016-03-31 14:41:26 -07005126 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005127 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5128 mLastVoiceVolume = voiceVolume;
5129 }
5130 }
5131
5132 return NO_ERROR;
5133}
5134
Eric Laurentc75307b2015-03-17 15:29:32 -07005135void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5136 audio_devices_t device,
5137 int delayMs,
5138 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005139{
Eric Laurentc75307b2015-03-17 15:29:32 -07005140 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005141
Eric Laurent794fde22016-03-11 09:50:45 -08005142 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005143 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005144 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005145 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005146 device,
5147 delayMs,
5148 force);
5149 }
5150}
5151
Eric Laurente0720872014-03-11 09:30:41 -07005152void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005153 bool on,
5154 const sp<AudioOutputDescriptor>& outputDesc,
5155 int delayMs,
5156 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005157{
Eric Laurent72249d52015-06-08 11:12:15 -07005158 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5159 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005160 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005161 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005162 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005163 }
5164 }
5165}
5166
Eric Laurente0720872014-03-11 09:30:41 -07005167void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005168 bool on,
5169 const sp<AudioOutputDescriptor>& outputDesc,
5170 int delayMs,
5171 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005172{
Eric Laurente552edb2014-03-10 17:42:56 -07005173 if (device == AUDIO_DEVICE_NONE) {
5174 device = outputDesc->device();
5175 }
5176
Eric Laurentc75307b2015-03-17 15:29:32 -07005177 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5178 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005179
5180 if (on) {
5181 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005182 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005183 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005184 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005185 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005186 }
5187 }
5188 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5189 outputDesc->mMuteCount[stream]++;
5190 } else {
5191 if (outputDesc->mMuteCount[stream] == 0) {
5192 ALOGV("setStreamMute() unmuting non muted stream!");
5193 return;
5194 }
5195 if (--outputDesc->mMuteCount[stream] == 0) {
5196 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005197 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005198 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005199 device,
5200 delayMs);
5201 }
5202 }
5203}
5204
Eric Laurente0720872014-03-11 09:30:41 -07005205void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005206 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005207{
Eric Laurent87ffa392015-05-22 10:32:38 -07005208 if(!hasPrimaryOutput()) {
5209 return;
5210 }
5211
Eric Laurente552edb2014-03-10 17:42:56 -07005212 // if the stream pertains to sonification strategy and we are in call we must
5213 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5214 // in the device used for phone strategy and play the tone if the selected device does not
5215 // interfere with the device used for phone strategy
5216 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5217 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005218 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005219 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5220 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005221 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005222 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5223 stream, starting, outputDesc->mDevice, stateChange);
5224 if (outputDesc->mRefCount[stream]) {
5225 int muteCount = 1;
5226 if (stateChange) {
5227 muteCount = outputDesc->mRefCount[stream];
5228 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005229 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005230 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5231 for (int i = 0; i < muteCount; i++) {
5232 setStreamMute(stream, starting, mPrimaryOutput);
5233 }
5234 } else {
5235 ALOGV("handleIncallSonification() high visibility");
5236 if (outputDesc->device() &
5237 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5238 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5239 for (int i = 0; i < muteCount; i++) {
5240 setStreamMute(stream, starting, mPrimaryOutput);
5241 }
5242 }
5243 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005244 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5245 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005246 } else {
5247 mpClientInterface->stopTone();
5248 }
5249 }
5250 }
5251 }
5252}
5253
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005254audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5255{
5256 // flags to stream type mapping
5257 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5258 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5259 }
5260 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5261 return AUDIO_STREAM_BLUETOOTH_SCO;
5262 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005263 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5264 return AUDIO_STREAM_TTS;
5265 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005266
5267 // usage to stream type mapping
5268 switch (attr->usage) {
5269 case AUDIO_USAGE_MEDIA:
5270 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005271 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5272 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005273 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5274 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005275 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5276 return AUDIO_STREAM_SYSTEM;
5277 case AUDIO_USAGE_VOICE_COMMUNICATION:
5278 return AUDIO_STREAM_VOICE_CALL;
5279
5280 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5281 return AUDIO_STREAM_DTMF;
5282
5283 case AUDIO_USAGE_ALARM:
5284 return AUDIO_STREAM_ALARM;
5285 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5286 return AUDIO_STREAM_RING;
5287
5288 case AUDIO_USAGE_NOTIFICATION:
5289 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5290 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5291 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5292 case AUDIO_USAGE_NOTIFICATION_EVENT:
5293 return AUDIO_STREAM_NOTIFICATION;
5294
5295 case AUDIO_USAGE_UNKNOWN:
5296 default:
5297 return AUDIO_STREAM_MUSIC;
5298 }
5299}
Eric Laurente83b55d2014-11-14 10:06:21 -08005300
François Gaffie53615e22015-03-19 09:24:12 +01005301bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5302{
Eric Laurente83b55d2014-11-14 10:06:21 -08005303 // has flags that map to a strategy?
5304 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5305 return true;
5306 }
5307
5308 // has known usage?
5309 switch (paa->usage) {
5310 case AUDIO_USAGE_UNKNOWN:
5311 case AUDIO_USAGE_MEDIA:
5312 case AUDIO_USAGE_VOICE_COMMUNICATION:
5313 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5314 case AUDIO_USAGE_ALARM:
5315 case AUDIO_USAGE_NOTIFICATION:
5316 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5317 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5318 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5319 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5320 case AUDIO_USAGE_NOTIFICATION_EVENT:
5321 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5322 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5323 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5324 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005325 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005326 break;
5327 default:
5328 return false;
5329 }
5330 return true;
5331}
5332
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07005333bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005334 routing_strategy strategy, uint32_t inPastMs,
5335 nsecs_t sysTime) const
5336{
5337 if ((sysTime == 0) && (inPastMs != 0)) {
5338 sysTime = systemTime();
5339 }
Eric Laurent794fde22016-03-11 09:50:45 -08005340 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005341 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5342 (NUM_STRATEGIES == strategy)) &&
5343 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5344 return true;
5345 }
5346 }
5347 return false;
5348}
5349
François Gaffie2110e042015-03-24 08:41:51 +01005350audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5351{
5352 return mEngine->getForceUse(usage);
5353}
5354
5355bool AudioPolicyManager::isInCall()
5356{
5357 return isStateInCall(mEngine->getPhoneState());
5358}
5359
5360bool AudioPolicyManager::isStateInCall(int state)
5361{
5362 return is_state_in_call(state);
5363}
5364
Eric Laurentd60560a2015-04-10 11:31:20 -07005365void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5366{
5367 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5368 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5369 if (sourceDesc->mDevice->equals(deviceDesc)) {
5370 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5371 stopAudioSource(sourceDesc->getHandle());
5372 }
5373 }
5374
5375 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5376 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5377 bool release = false;
5378 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5379 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5380 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5381 source->ext.device.type == deviceDesc->type()) {
5382 release = true;
5383 }
5384 }
5385 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5386 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5387 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5388 sink->ext.device.type == deviceDesc->type()) {
5389 release = true;
5390 }
5391 }
5392 if (release) {
5393 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5394 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5395 }
5396 }
5397}
5398
Phil Burk09bc4612016-02-24 15:58:15 -08005399// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005400void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5401 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005402 // TODO Set this based on Config properties.
5403 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005404
5405 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5406 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005407 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005408
5409 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005410 bool supportsAC3 = false;
5411 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005412 bool supportsIEC61937 = false;
5413 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5414 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005415 switch (format) {
5416 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005417 supportsAC3 = true;
5418 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005419 case AUDIO_FORMAT_E_AC3:
5420 case AUDIO_FORMAT_DTS:
5421 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005422 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005423 break;
5424 case AUDIO_FORMAT_IEC61937:
5425 supportsIEC61937 = true;
5426 break;
5427 default:
5428 break;
5429 }
5430 }
Phil Burk09bc4612016-02-24 15:58:15 -08005431
5432 // Modify formats based on surround preferences.
5433 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005434 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5435 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5436 // Remove surround sound related formats.
5437 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5438 audio_format_t format = formats[formatIndex];
5439 switch(format) {
5440 case AUDIO_FORMAT_AC3:
5441 case AUDIO_FORMAT_E_AC3:
5442 case AUDIO_FORMAT_DTS:
5443 case AUDIO_FORMAT_DTS_HD:
5444 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005445 formats.removeAt(formatIndex);
5446 break;
5447 default:
5448 formatIndex++; // keep it
5449 break;
5450 }
Phil Burk09bc4612016-02-24 15:58:15 -08005451 }
Phil Burk07ac1142016-03-25 13:39:29 -07005452 supportsAC3 = false;
5453 supportsOtherSurround = false;
5454 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005455 }
Phil Burk07ac1142016-03-25 13:39:29 -07005456 } else { // AUTO or ALWAYS
5457 // Most TVs support AC3 even if they do not report it in the EDID.
5458 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5459 && !supportsAC3) {
5460 formats.add(AUDIO_FORMAT_AC3);
5461 supportsAC3 = true;
5462 }
5463
5464 // If ALWAYS, add support for raw surround formats if all are missing.
5465 // This assumes that if any of these formats are reported by the HAL
5466 // then the report is valid and should not be modified.
5467 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5468 && !supportsOtherSurround) {
5469 formats.add(AUDIO_FORMAT_E_AC3);
5470 formats.add(AUDIO_FORMAT_DTS);
5471 formats.add(AUDIO_FORMAT_DTS_HD);
5472 supportsOtherSurround = true;
5473 }
5474
5475 // Add support for IEC61937 if any raw surround supported.
5476 // The HAL could do this but add it here, just in case.
5477 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5478 formats.add(AUDIO_FORMAT_IEC61937);
5479 supportsIEC61937 = true;
5480 }
Phil Burk09bc4612016-02-24 15:58:15 -08005481 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005482}
5483
5484// Modify the list of channel masks supported.
5485void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5486 ChannelsVector &channelMasks = *channelMasksPtr;
5487 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5488 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5489
5490 // If NEVER, then remove support for channelMasks > stereo.
5491 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5492 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5493 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5494 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5495 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5496 channelMasks.removeAt(maskIndex);
5497 } else {
5498 maskIndex++;
5499 }
5500 }
5501 // If ALWAYS, then make sure we at least support 5.1
5502 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5503 bool supports5dot1 = false;
5504 // Are there any channel masks that can be considered "surround"?
5505 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5506 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5507 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5508 supports5dot1 = true;
5509 break;
5510 }
5511 }
5512 // If not then add 5.1 support.
5513 if (!supports5dot1) {
5514 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5515 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5516 }
Phil Burk09bc4612016-02-24 15:58:15 -08005517 }
5518}
5519
Phil Burk00eeb322016-03-31 12:41:00 -07005520void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5521 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005522 AudioProfileVector &profiles)
5523{
5524 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005525
François Gaffie112b0af2015-11-19 16:13:25 +01005526 // Format MUST be checked first to update the list of AudioProfile
5527 if (profiles.hasDynamicFormat()) {
5528 reply = mpClientInterface->getParameters(ioHandle,
5529 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk0709b0a2016-03-31 12:54:57 -07005530 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005531 AudioParameter repliedParameters(reply);
5532 if (repliedParameters.get(
5533 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005534 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5535 return;
5536 }
Phil Burk09bc4612016-02-24 15:58:15 -08005537 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005538 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005539 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005540 }
Phil Burk09bc4612016-02-24 15:58:15 -08005541 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005542 }
5543 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5544
Eric Laurent20eb3a42016-01-26 18:39:17 -08005545 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005546 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005547 ChannelsVector channelMasks;
5548 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005549 AudioParameter requestedParameters;
5550 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5551
5552 if (profiles.hasDynamicRateFor(format)) {
5553 reply = mpClientInterface->getParameters(ioHandle,
5554 requestedParameters.toString() + ";" +
5555 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5556 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005557 AudioParameter repliedParameters(reply);
5558 if (repliedParameters.get(
5559 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5560 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005561 }
5562 }
5563 if (profiles.hasDynamicChannelsFor(format)) {
5564 reply = mpClientInterface->getParameters(ioHandle,
5565 requestedParameters.toString() + ";" +
5566 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5567 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005568 AudioParameter repliedParameters(reply);
5569 if (repliedParameters.get(
5570 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5571 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005572 if (device == AUDIO_DEVICE_OUT_HDMI) {
5573 filterSurroundChannelMasks(&channelMasks);
5574 }
François Gaffie112b0af2015-11-19 16:13:25 +01005575 }
5576 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005577 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005578 }
5579}
Eric Laurentd60560a2015-04-10 11:31:20 -07005580
Eric Laurente552edb2014-03-10 17:42:56 -07005581}; // namespace android