blob: 8744de85720c7235508b35737fa0888b244a35d5 [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
345 // Check if the device is currently connected
346 sp<DeviceDescriptor> devDesc =
347 mHwModules.getDeviceDescriptor(device, device_address, device_name);
348 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
349 if (index < 0) {
350 // Nothing to do: device is not connected
351 return NO_ERROR;
352 }
353
354 // Toggle the device state: UNAVAILABLE -> AVAILABLE
355 // This will force reading again the device configuration
356 status = setDeviceConnectionState(device,
357 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
358 device_address, device_name);
359 if (status != NO_ERROR) {
360 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
361 status);
362 return status;
363 }
364
365 status = setDeviceConnectionState(device,
366 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
367 device_address, device_name);
368 if (status != NO_ERROR) {
369 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
370 status);
371 return status;
372 }
373
374 return NO_ERROR;
375}
376
Eric Laurentdc462862016-07-19 12:29:53 -0700377uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700378{
379 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700380 status_t status;
381 audio_patch_handle_t afPatchHandle;
382 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700383 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700384
Eric Laurent87ffa392015-05-22 10:32:38 -0700385 if(!hasPrimaryOutput()) {
Eric Laurentdc462862016-07-19 12:29:53 -0700386 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700387 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800388 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700389 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
390
391 // release existing RX patch if any
392 if (mCallRxPatch != 0) {
393 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
394 mCallRxPatch.clear();
395 }
396 // release TX patch if any
397 if (mCallTxPatch != 0) {
398 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
399 mCallTxPatch.clear();
400 }
401
402 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
403 // via setOutputDevice() on primary output.
404 // Otherwise, create two audio patches for TX and RX path.
405 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700406 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700407 // If the TX device is also on the primary HW module, setOutputDevice() will take care
408 // of it due to legacy implementation. If not, create a patch.
409 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
410 == AUDIO_DEVICE_NONE) {
411 createTxPatch = true;
412 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700413 } else { // create RX path audio patch
414 struct audio_patch patch;
415
416 patch.num_sources = 1;
417 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700418 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
419 ALOG_ASSERT(!deviceList.isEmpty(),
420 "updateCallRouting() selected device not in output device list");
421 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
422 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
423 ALOG_ASSERT(!deviceList.isEmpty(),
424 "updateCallRouting() no telephony RX device");
425 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
426
427 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
428 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
429
430 // request to reuse existing output stream if one is already opened to reach the RX device
431 SortedVector<audio_io_handle_t> outputs =
432 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700433 audio_io_handle_t output = selectOutput(outputs,
434 AUDIO_OUTPUT_FLAG_NONE,
435 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700437 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700438 ALOG_ASSERT(!outputDesc->isDuplicated(),
439 "updateCallRouting() RX device output is duplicated");
440 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700441 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 patch.num_sources = 2;
443 }
444
445 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700446 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700447 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
448 status);
449 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100450 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700451 mCallRxPatch->mAfPatchHandle = afPatchHandle;
452 mCallRxPatch->mUid = mUidCached;
453 }
454 createTxPatch = true;
455 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700456 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700458
Eric Laurentc2730ba2014-07-20 15:47:07 -0700459 patch.num_sources = 1;
460 patch.num_sinks = 1;
461 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
462 ALOG_ASSERT(!deviceList.isEmpty(),
463 "updateCallRouting() selected device not in input device list");
464 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
465 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
466 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
467 ALOG_ASSERT(!deviceList.isEmpty(),
468 "updateCallRouting() no telephony TX device");
469 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
470 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
471
472 SortedVector<audio_io_handle_t> outputs =
473 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700474 audio_io_handle_t output = selectOutput(outputs,
475 AUDIO_OUTPUT_FLAG_NONE,
476 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700477 // request to reuse existing output stream if one is already opened to reach the TX
478 // path output device
479 if (output != AUDIO_IO_HANDLE_NONE) {
480 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
481 ALOG_ASSERT(!outputDesc->isDuplicated(),
482 "updateCallRouting() RX device output is duplicated");
483 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700484 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700485 patch.num_sources = 2;
486 }
487
Eric Laurentc0a889f2015-10-14 14:36:34 -0700488 // terminate active capture if on the same HW module as the call TX source device
489 // FIXME: would be better to refine to only inputs whose profile connects to the
490 // call TX device but this information is not in the audio patch and logic here must be
491 // symmetric to the one in startInput()
Eric Laurent232f26f2016-02-17 18:06:27 -0800492 audio_io_handle_t activeInput = mInputs.getActiveInput();
493 if (activeInput != 0) {
494 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
495 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
496 //FIXME: consider all active sessions
497 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
498 audio_session_t activeSession = activeSessions.keyAt(0);
499 stopInput(activeInput, activeSession);
500 releaseInput(activeInput, activeSession);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700501 }
502 }
503
Eric Laurentc2730ba2014-07-20 15:47:07 -0700504 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700505 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
507 status);
508 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100509 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700510 mCallTxPatch->mAfPatchHandle = afPatchHandle;
511 mCallTxPatch->mUid = mUidCached;
512 }
513 }
Eric Laurentdc462862016-07-19 12:29:53 -0700514
515 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700516}
517
Eric Laurente0720872014-03-11 09:30:41 -0700518void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700519{
520 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100521 // store previous phone state for management of sonification strategy below
522 int oldState = mEngine->getPhoneState();
523
524 if (mEngine->setPhoneState(state) != NO_ERROR) {
525 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700526 return;
527 }
François Gaffie2110e042015-03-24 08:41:51 +0100528 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700529 // if leaving call state, handle special case of active streams
530 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700531 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700532 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800533 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700534 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700535 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800536
Eric Laurent63dea1d2015-07-02 17:10:28 -0700537 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800538 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700539 }
540
François Gaffie2110e042015-03-24 08:41:51 +0100541 /**
542 * Switching to or from incall state or switching between telephony and VoIP lead to force
543 * routing command.
544 */
545 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
546 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700547
548 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700549 checkA2dpSuspend();
550 checkOutputForAllStrategies();
551 updateDevicesAndOutputs();
552
Eric Laurente552edb2014-03-10 17:42:56 -0700553 int delayMs = 0;
554 if (isStateInCall(state)) {
555 nsecs_t sysTime = systemTime();
556 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700558 // mute media and sonification strategies and delay device switch by the largest
559 // latency of any output where either strategy is active.
560 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100561 if ((isStrategyActive(desc, STRATEGY_MEDIA,
562 SONIFICATION_HEADSET_MUSIC_DELAY,
563 sysTime) ||
564 isStrategyActive(desc, STRATEGY_SONIFICATION,
565 SONIFICATION_HEADSET_MUSIC_DELAY,
566 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700567 (delayMs < (int)desc->latency()*2)) {
568 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700569 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700570 setStrategyMute(STRATEGY_MEDIA, true, desc);
571 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700572 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700573 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
574 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700575 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
576 }
577 }
578
Eric Laurent87ffa392015-05-22 10:32:38 -0700579 if (hasPrimaryOutput()) {
580 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
581 // the device returned is not necessarily reachable via this output
582 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
583 // force routing command to audio hardware when ending call
584 // even if no device change is needed
585 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
586 rxDevice = mPrimaryOutput->device();
587 }
Eric Laurente552edb2014-03-10 17:42:56 -0700588
Eric Laurent87ffa392015-05-22 10:32:38 -0700589 if (state == AUDIO_MODE_IN_CALL) {
590 updateCallRouting(rxDevice, delayMs);
591 } else if (oldState == AUDIO_MODE_IN_CALL) {
592 if (mCallRxPatch != 0) {
593 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
594 mCallRxPatch.clear();
595 }
596 if (mCallTxPatch != 0) {
597 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
598 mCallTxPatch.clear();
599 }
600 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
601 } else {
602 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700603 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604 }
Eric Laurente552edb2014-03-10 17:42:56 -0700605 // if entering in call state, handle special case of active streams
606 // pertaining to sonification strategy see handleIncallSonification()
607 if (isStateInCall(state)) {
608 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800609 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700610 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700611 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700612
613 // force reevaluating accessibility routing when call starts
614 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700615 }
616
617 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700618 if (state == AUDIO_MODE_RINGTONE &&
619 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700620 mLimitRingtoneVolume = true;
621 } else {
622 mLimitRingtoneVolume = false;
623 }
624}
625
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700626audio_mode_t AudioPolicyManager::getPhoneState() {
627 return mEngine->getPhoneState();
628}
629
Eric Laurente0720872014-03-11 09:30:41 -0700630void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700631 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700632{
François Gaffie2110e042015-03-24 08:41:51 +0100633 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700634
François Gaffie2110e042015-03-24 08:41:51 +0100635 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
636 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
637 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700638 }
François Gaffie2110e042015-03-24 08:41:51 +0100639 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
640 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
641 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700642
643 // check for device and output changes triggered by new force usage
644 checkA2dpSuspend();
645 checkOutputForAllStrategies();
646 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800647
Eric Laurentdc462862016-07-19 12:29:53 -0700648 //FIXME: workaround for truncated touch sounds
649 // to be removed when the problem is handled by system UI
650 uint32_t delayMs = 0;
651 uint32_t waitMs = 0;
652 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
653 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
654 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700655 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700656 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700657 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658 }
Eric Laurente552edb2014-03-10 17:42:56 -0700659 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700660 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
661 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
662 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700663 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
664 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 }
Eric Laurente552edb2014-03-10 17:42:56 -0700666 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700667 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700668 }
669 }
670
Eric Laurent232f26f2016-02-17 18:06:27 -0800671 audio_io_handle_t activeInput = mInputs.getActiveInput();
672 if (activeInput != 0) {
673 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
674 audio_devices_t newDevice = getNewInputDevice(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700675 // Force new input selection if the new device can not be reached via current input
Eric Laurent232f26f2016-02-17 18:06:27 -0800676 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
677 setInputDevice(activeInput, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700678 } else {
Eric Laurent232f26f2016-02-17 18:06:27 -0800679 closeInput(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700680 }
Eric Laurente552edb2014-03-10 17:42:56 -0700681 }
Eric Laurente552edb2014-03-10 17:42:56 -0700682}
683
Eric Laurente0720872014-03-11 09:30:41 -0700684void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700685{
686 ALOGV("setSystemProperty() property %s, value %s", property, value);
687}
688
689// Find a direct output profile compatible with the parameters passed, even if the input flags do
690// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800691sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700692 audio_devices_t device,
693 uint32_t samplingRate,
694 audio_format_t format,
695 audio_channel_mask_t channelMask,
696 audio_output_flags_t flags)
697{
Eric Laurent861a6282015-05-18 15:40:16 -0700698 // only retain flags that will drive the direct output profile selection
699 // if explicitly requested
700 static const uint32_t kRelevantFlags =
701 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
702 flags =
703 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
704
705 sp<IOProfile> profile;
706
Eric Laurente552edb2014-03-10 17:42:56 -0700707 for (size_t i = 0; i < mHwModules.size(); i++) {
708 if (mHwModules[i]->mHandle == 0) {
709 continue;
710 }
711 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700712 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
713 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700714 samplingRate, NULL /*updatedSamplingRate*/,
715 format, NULL /*updatedFormat*/,
716 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700717 flags)) {
718 continue;
719 }
720 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100721 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700722 continue;
723 }
724 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100725 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700726 continue;
727 }
728 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100729 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700730 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700731 }
Eric Laurente552edb2014-03-10 17:42:56 -0700732 }
733 }
Eric Laurent861a6282015-05-18 15:40:16 -0700734 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700735}
736
Eric Laurente0720872014-03-11 09:30:41 -0700737audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100738 uint32_t samplingRate,
739 audio_format_t format,
740 audio_channel_mask_t channelMask,
741 audio_output_flags_t flags,
742 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700743{
Eric Laurent3b73df72014-03-11 09:06:29 -0700744 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700745 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
746 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
747 device, stream, samplingRate, format, channelMask, flags);
748
Eric Laurente83b55d2014-11-14 10:06:21 -0800749 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
750 stream, samplingRate,format, channelMask,
751 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700752}
753
Eric Laurente83b55d2014-11-14 10:06:21 -0800754status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
755 audio_io_handle_t *output,
756 audio_session_t session,
757 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700758 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800759 uint32_t samplingRate,
760 audio_format_t format,
761 audio_channel_mask_t channelMask,
762 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700763 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800764 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700765{
Eric Laurente83b55d2014-11-14 10:06:21 -0800766 audio_attributes_t attributes;
767 if (attr != NULL) {
768 if (!isValidAttributes(attr)) {
769 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
770 attr->usage, attr->content_type, attr->flags,
771 attr->tags);
772 return BAD_VALUE;
773 }
774 attributes = *attr;
775 } else {
776 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
777 ALOGE("getOutputForAttr(): invalid stream type");
778 return BAD_VALUE;
779 }
780 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700781 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700782 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800783 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100784 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800785 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100786 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800787 }
François Gaffie036e1e92015-03-19 10:16:24 +0100788 *stream = streamTypefromAttributesInt(&attributes);
789 *output = desc->mIoHandle;
790 ALOGV("getOutputForAttr() returns output %d", *output);
791 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800792 }
793 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
794 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
795 return BAD_VALUE;
796 }
797
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700798 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
799 " session %d selectedDeviceId %d",
800 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
801 session, selectedDeviceId);
802
803 *stream = streamTypefromAttributesInt(&attributes);
804
805 // Explicit routing?
806 sp<DeviceDescriptor> deviceDesc;
807 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
808 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
809 deviceDesc = mAvailableOutputDevices[i];
810 break;
811 }
812 }
813 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700814
Eric Laurente83b55d2014-11-14 10:06:21 -0800815 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700816 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700817
Eric Laurente83b55d2014-11-14 10:06:21 -0800818 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700819 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
820 }
821
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700822 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700823 device, samplingRate, format, channelMask, flags);
824
Eric Laurente83b55d2014-11-14 10:06:21 -0800825 *output = getOutputForDevice(device, session, *stream,
826 samplingRate, format, channelMask,
827 flags, offloadInfo);
828 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700829 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800830 return INVALID_OPERATION;
831 }
Paul McLeanaa981192015-03-21 09:55:15 -0700832
Eric Laurente83b55d2014-11-14 10:06:21 -0800833 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700834}
835
836audio_io_handle_t AudioPolicyManager::getOutputForDevice(
837 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800838 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700839 audio_stream_type_t stream,
840 uint32_t samplingRate,
841 audio_format_t format,
842 audio_channel_mask_t channelMask,
843 audio_output_flags_t flags,
844 const audio_offload_info_t *offloadInfo)
845{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700846 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700847 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848
Eric Laurente552edb2014-03-10 17:42:56 -0700849#ifdef AUDIO_POLICY_TEST
850 if (mCurOutput != 0) {
851 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
852 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
853
854 if (mTestOutputs[mCurOutput] == 0) {
855 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700856 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
857 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700858 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700859 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700860 outputDesc->mFlags =
861 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700862 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700863 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
864 config.sample_rate = mTestSamplingRate;
865 config.channel_mask = mTestChannels;
866 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700867 if (offloadInfo != NULL) {
868 config.offload_info = *offloadInfo;
869 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700870 status = mpClientInterface->openOutput(0,
871 &mTestOutputs[mCurOutput],
872 &config,
873 &outputDesc->mDevice,
874 String8(""),
875 &outputDesc->mLatency,
876 outputDesc->mFlags);
877 if (status == NO_ERROR) {
878 outputDesc->mSamplingRate = config.sample_rate;
879 outputDesc->mFormat = config.format;
880 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700881 AudioParameter outputCmd = AudioParameter();
882 outputCmd.addInt(String8("set_id"),mCurOutput);
883 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
884 addOutput(mTestOutputs[mCurOutput], outputDesc);
885 }
886 }
887 return mTestOutputs[mCurOutput];
888 }
889#endif //AUDIO_POLICY_TEST
890
891 // open a direct output if required by specified parameters
892 //force direct flag if offload flag is set: offloading implies a direct output stream
893 // and all common behaviors are driven by checking only the direct flag
894 // this should normally be set appropriately in the policy configuration file
895 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700896 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700897 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700898 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
899 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
900 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 // only allow deep buffering for music stream type
902 if (stream != AUDIO_STREAM_MUSIC) {
903 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700904 } else if (/* stream == AUDIO_STREAM_MUSIC && */
905 flags == AUDIO_OUTPUT_FLAG_NONE &&
906 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
907 // use DEEP_BUFFER as default output for music stream type
908 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800909 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700910 if (stream == AUDIO_STREAM_TTS) {
911 flags = AUDIO_OUTPUT_FLAG_TTS;
912 }
Eric Laurente552edb2014-03-10 17:42:56 -0700913
Eric Laurentb732cf52014-09-24 19:08:21 -0700914 sp<IOProfile> profile;
915
916 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700917 // and not explicitly requested
918 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800919 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700920 audio_channel_count_from_out_mask(channelMask) <= 2) {
921 goto non_direct_output;
922 }
923
Andy Hung2ddee192015-12-18 17:34:44 -0800924 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
925 // This prevents creating an offloaded track and tearing it down immediately after start
926 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700927 // FIXME: We should check the audio session here but we do not have it in this context.
928 // This may prevent offloading in rare situations where effects are left active by apps
929 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700930
Eric Laurente552edb2014-03-10 17:42:56 -0700931 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800932 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700933 profile = getProfileForDirectOutput(device,
934 samplingRate,
935 format,
936 channelMask,
937 (audio_output_flags_t)flags);
938 }
939
Eric Laurent1c333e22014-05-20 10:48:17 -0700940 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700941 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700942
943 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700944 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700945 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
946 outputDesc = desc;
947 // reuse direct output if currently open and configured with same parameters
948 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800949 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700950 (channelMask == outputDesc->mChannelMask)) {
951 outputDesc->mDirectOpenCount++;
952 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
953 return mOutputs.keyAt(i);
954 }
955 }
956 }
957 // close direct output if currently open and configured with different parameters
958 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700959 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700960 }
Eric Laurent861a6282015-05-18 15:40:16 -0700961
962 // if the selected profile is offloaded and no offload info was specified,
963 // create a default one
964 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100965 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700966 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
967 defaultOffloadInfo.sample_rate = samplingRate;
968 defaultOffloadInfo.channel_mask = channelMask;
969 defaultOffloadInfo.format = format;
970 defaultOffloadInfo.stream_type = stream;
971 defaultOffloadInfo.bit_rate = 0;
972 defaultOffloadInfo.duration_us = -1;
973 defaultOffloadInfo.has_video = true; // conservative
974 defaultOffloadInfo.is_streaming = true; // likely
975 offloadInfo = &defaultOffloadInfo;
976 }
977
Eric Laurentc75307b2015-03-17 15:29:32 -0700978 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700979 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700980 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700981 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700982 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
983 config.sample_rate = samplingRate;
984 config.channel_mask = channelMask;
985 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700986 if (offloadInfo != NULL) {
987 config.offload_info = *offloadInfo;
988 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700989 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700990 &output,
991 &config,
992 &outputDesc->mDevice,
993 String8(""),
994 &outputDesc->mLatency,
995 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700996
997 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700998 if (status != NO_ERROR ||
999 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001000 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001001 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001002 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1003 "format %d %d, channelMask %04x %04x", output, samplingRate,
1004 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1005 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001006 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001007 mpClientInterface->closeOutput(output);
1008 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001009 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001010 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001011 goto non_direct_output;
1012 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001013 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001014 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001015 outputDesc->mSamplingRate = config.sample_rate;
1016 outputDesc->mChannelMask = config.channel_mask;
1017 outputDesc->mFormat = config.format;
1018 outputDesc->mRefCount[stream] = 0;
1019 outputDesc->mStopTime[stream] = 0;
1020 outputDesc->mDirectOpenCount = 1;
1021
Eric Laurente552edb2014-03-10 17:42:56 -07001022 audio_io_handle_t srcOutput = getOutputForEffect();
1023 addOutput(output, outputDesc);
1024 audio_io_handle_t dstOutput = getOutputForEffect();
1025 if (dstOutput == output) {
1026 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1027 }
1028 mPreviousOutputs = mOutputs;
1029 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001030 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001031 return output;
1032 }
1033
Eric Laurentb732cf52014-09-24 19:08:21 -07001034non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001035
1036 // A request for HW A/V sync cannot fallback to a mixed output because time
1037 // stamps are embedded in audio data
1038 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1039 return AUDIO_IO_HANDLE_NONE;
1040 }
1041
Eric Laurente552edb2014-03-10 17:42:56 -07001042 // ignoring channel mask due to downmix capability in mixer
1043
1044 // open a non direct output
1045
1046 // for non direct outputs, only PCM is supported
1047 if (audio_is_linear_pcm(format)) {
1048 // get which output is suitable for the specified stream. The actual
1049 // routing change will happen when startOutput() will be called
1050 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1051
Eric Laurent8838a382014-09-08 16:44:28 -07001052 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1053 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1054 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001055 }
1056 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1057 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1058
Paul McLeanaa981192015-03-21 09:55:15 -07001059 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001060
1061 return output;
1062}
1063
Eric Laurente0720872014-03-11 09:30:41 -07001064audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001065 audio_output_flags_t flags,
1066 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001067{
1068 // select one output among several that provide a path to a particular device or set of
1069 // devices (the list was previously build by getOutputsForDevice()).
1070 // The priority is as follows:
1071 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001072 // 2: the output with the bit depth the closest to the requested one
1073 // 3: the primary output
1074 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001075
1076 if (outputs.size() == 0) {
1077 return 0;
1078 }
1079 if (outputs.size() == 1) {
1080 return outputs[0];
1081 }
1082
1083 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001084 audio_io_handle_t outputForFlags = 0;
1085 audio_io_handle_t outputForPrimary = 0;
1086 audio_io_handle_t outputForFormat = 0;
1087 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1088 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001089
1090 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001091 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001092 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001093 // if a valid format is specified, skip output if not compatible
1094 if (format != AUDIO_FORMAT_INVALID) {
1095 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001096 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001097 continue;
1098 }
1099 } else if (!audio_is_linear_pcm(format)) {
1100 continue;
1101 }
Eric Laurente6930022016-02-11 10:20:40 -08001102 if (AudioPort::isBetterFormatMatch(
1103 outputDesc->mFormat, bestFormat, format)) {
1104 outputForFormat = outputs[i];
1105 bestFormat = outputDesc->mFormat;
1106 }
Eric Laurent8838a382014-09-08 16:44:28 -07001107 }
1108
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001109 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001110 if (commonFlags >= maxCommonFlags) {
1111 if (commonFlags == maxCommonFlags) {
1112 if (AudioPort::isBetterFormatMatch(
1113 outputDesc->mFormat, bestFormatForFlags, format)) {
1114 outputForFlags = outputs[i];
1115 bestFormatForFlags = outputDesc->mFormat;
1116 }
1117 } else {
1118 outputForFlags = outputs[i];
1119 maxCommonFlags = commonFlags;
1120 bestFormatForFlags = outputDesc->mFormat;
1121 }
Eric Laurente552edb2014-03-10 17:42:56 -07001122 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1123 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001124 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001125 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001126 }
1127 }
1128 }
1129
Eric Laurente6930022016-02-11 10:20:40 -08001130 if (outputForFlags != 0) {
1131 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001132 }
Eric Laurente6930022016-02-11 10:20:40 -08001133 if (outputForFormat != 0) {
1134 return outputForFormat;
1135 }
1136 if (outputForPrimary != 0) {
1137 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001138 }
1139
1140 return outputs[0];
1141}
1142
Eric Laurente0720872014-03-11 09:30:41 -07001143status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001144 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001145 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001146{
Paul McLeanaa981192015-03-21 09:55:15 -07001147 ALOGV("startOutput() output %d, stream %d, session %d",
1148 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001149 ssize_t index = mOutputs.indexOfKey(output);
1150 if (index < 0) {
1151 ALOGW("startOutput() unknown output %d", output);
1152 return BAD_VALUE;
1153 }
1154
Eric Laurentc75307b2015-03-17 15:29:32 -07001155 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1156
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001157 // Routing?
1158 mOutputRoutes.incRouteActivity(session);
1159
Eric Laurentc75307b2015-03-17 15:29:32 -07001160 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001161 AudioMix *policyMix = NULL;
1162 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001163 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001164 policyMix = outputDesc->mPolicyMix;
1165 address = policyMix->mDeviceAddress.string();
1166 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1167 newDevice = policyMix->mDeviceType;
1168 } else {
1169 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1170 }
Eric Laurent493404d2015-04-21 15:07:36 -07001171 } else if (mOutputRoutes.hasRouteChanged(session)) {
1172 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001173 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001174 } else {
1175 newDevice = AUDIO_DEVICE_NONE;
1176 }
1177
1178 uint32_t delayMs = 0;
1179
Eric Laurentc40d9692016-04-13 19:14:13 -07001180 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001181
1182 if (status != NO_ERROR) {
1183 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001184 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001185 }
1186 // Automatically enable the remote submix input when output is started on a re routing mix
1187 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001188 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1189 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001190 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1191 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001192 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001193 "remote-submix");
1194 }
1195
1196 if (delayMs != 0) {
1197 usleep(delayMs * 1000);
1198 }
1199
1200 return status;
1201}
1202
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001203status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001204 audio_stream_type_t stream,
1205 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001206 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001207 uint32_t *delayMs)
1208{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001209 // cannot start playback of STREAM_TTS if any other output is being used
1210 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001211
1212 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001213 if (stream == AUDIO_STREAM_TTS) {
1214 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001215 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001216 return INVALID_OPERATION;
1217 } else {
1218 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1219 }
1220 } else {
1221 // some playback other than beacon starts
1222 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1223 }
1224
Eric Laurent77305a62016-07-25 16:39:22 -07001225 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001226 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001227 bool force = !outputDesc->isActive() &&
1228 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001229
Eric Laurente552edb2014-03-10 17:42:56 -07001230 // increment usage count for this stream on the requested output:
1231 // NOTE that the usage count is the same for duplicated output and hardware output which is
1232 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1233 outputDesc->changeRefCount(stream, 1);
1234
Eric Laurent493404d2015-04-21 15:07:36 -07001235 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001236 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001237 if (device == AUDIO_DEVICE_NONE) {
1238 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001239 }
Eric Laurente552edb2014-03-10 17:42:56 -07001240 routing_strategy strategy = getStrategy(stream);
1241 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001242 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1243 (beaconMuteLatency > 0);
1244 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001245 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001246 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001247 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001248 // force a device change if any other output is:
1249 // - managed by the same hw module
1250 // - has a current device selection that differs from selected device.
1251 // - supports currently selected device
1252 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001253 // In this case, the audio HAL must receive the new device selection so that it can
1254 // change the device currently selected by the other active output.
1255 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001256 desc->device() != device &&
1257 desc->supportedDevices() & device &&
1258 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001259 force = true;
1260 }
1261 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001262 // a notification so that audio focus effect can propagate, or that a mute/unmute
1263 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001264 uint32_t latency = desc->latency();
1265 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1266 waitMs = latency;
1267 }
1268 }
1269 }
Eric Laurentdc462862016-07-19 12:29:53 -07001270 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001271
1272 // handle special case for sonification while in call
1273 if (isInCall()) {
1274 handleIncallSonification(stream, true, false);
1275 }
1276
1277 // apply volume rules for current stream and device if necessary
1278 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001279 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001280 outputDesc,
1281 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001282
1283 // update the outputs if starting an output with a stream that can affect notification
1284 // routing
1285 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001286
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001287 // force reevaluating accessibility routing when ringtone or alarm starts
1288 if (strategy == STRATEGY_SONIFICATION) {
1289 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1290 }
Eric Laurentdc462862016-07-19 12:29:53 -07001291
1292 if (waitMs > muteWaitMs) {
1293 *delayMs = waitMs - muteWaitMs;
1294 }
Eric Laurente552edb2014-03-10 17:42:56 -07001295 }
Eric Laurentdc462862016-07-19 12:29:53 -07001296
Eric Laurente552edb2014-03-10 17:42:56 -07001297 return NO_ERROR;
1298}
1299
1300
Eric Laurente0720872014-03-11 09:30:41 -07001301status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001302 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001303 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001304{
1305 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1306 ssize_t index = mOutputs.indexOfKey(output);
1307 if (index < 0) {
1308 ALOGW("stopOutput() unknown output %d", output);
1309 return BAD_VALUE;
1310 }
1311
Eric Laurentc75307b2015-03-17 15:29:32 -07001312 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001313
Eric Laurentc75307b2015-03-17 15:29:32 -07001314 if (outputDesc->mRefCount[stream] == 1) {
1315 // Automatically disable the remote submix input when output is stopped on a
1316 // re routing mix of type MIX_TYPE_RECORDERS
1317 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1318 outputDesc->mPolicyMix != NULL &&
1319 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1320 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1321 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001322 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001323 "remote-submix");
1324 }
1325 }
1326
1327 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001328 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001329 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001330 int activityCount = mOutputRoutes.decRouteActivity(session);
1331 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1332
1333 if (forceDeviceUpdate) {
1334 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1335 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001336 }
1337
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001338 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001339}
1340
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001341status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001342 audio_stream_type_t stream,
1343 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001344{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001345 // always handle stream stop, check which stream type is stopping
1346 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1347
Eric Laurente552edb2014-03-10 17:42:56 -07001348 // handle special case for sonification while in call
1349 if (isInCall()) {
1350 handleIncallSonification(stream, false, false);
1351 }
1352
1353 if (outputDesc->mRefCount[stream] > 0) {
1354 // decrement usage count of this stream on the output
1355 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001356
Eric Laurente552edb2014-03-10 17:42:56 -07001357 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001358 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001359 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001360 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001361 // delay the device switch by twice the latency because stopOutput() is executed when
1362 // the track stop() command is received and at that time the audio track buffer can
1363 // still contain data that needs to be drained. The latency only covers the audio HAL
1364 // and kernel buffers. Also the latency does not always include additional delay in the
1365 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001366 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001367
1368 // force restoring the device selection on other active outputs if it differs from the
1369 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001370 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001371 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001372 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001374 desc->isActive() &&
1375 outputDesc->sharesHwModuleWith(desc) &&
1376 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001377 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1378 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001379 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001380 newDevice2,
1381 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001382 delayMs);
1383 // re-apply device specific volume if not done by setOutputDevice()
1384 if (!force) {
1385 applyStreamVolumes(desc, newDevice2, delayMs);
1386 }
Eric Laurente552edb2014-03-10 17:42:56 -07001387 }
1388 }
1389 // update the outputs if stopping one with a stream that can affect notification routing
1390 handleNotificationRoutingForStream(stream);
1391 }
1392 return NO_ERROR;
1393 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001394 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001395 return INVALID_OPERATION;
1396 }
1397}
1398
Eric Laurente83b55d2014-11-14 10:06:21 -08001399void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001400 audio_stream_type_t stream __unused,
1401 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001402{
1403 ALOGV("releaseOutput() %d", output);
1404 ssize_t index = mOutputs.indexOfKey(output);
1405 if (index < 0) {
1406 ALOGW("releaseOutput() releasing unknown output %d", output);
1407 return;
1408 }
1409
1410#ifdef AUDIO_POLICY_TEST
1411 int testIndex = testOutputIndex(output);
1412 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001413 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001414 if (outputDesc->isActive()) {
1415 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001416 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001417 mTestOutputs[testIndex] = 0;
1418 }
1419 return;
1420 }
1421#endif //AUDIO_POLICY_TEST
1422
Paul McLeanaa981192015-03-21 09:55:15 -07001423 // Routing
1424 mOutputRoutes.removeRoute(session);
1425
Eric Laurentc75307b2015-03-17 15:29:32 -07001426 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001427 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001428 if (desc->mDirectOpenCount <= 0) {
1429 ALOGW("releaseOutput() invalid open count %d for output %d",
1430 desc->mDirectOpenCount, output);
1431 return;
1432 }
1433 if (--desc->mDirectOpenCount == 0) {
1434 closeOutput(output);
1435 // If effects where present on the output, audioflinger moved them to the primary
1436 // output by default: move them back to the appropriate output.
1437 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001438 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001439 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1440 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001441 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001442 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001443 }
1444 }
1445}
1446
1447
Eric Laurentcaf7f482014-11-25 17:50:47 -08001448status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1449 audio_io_handle_t *input,
1450 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001451 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001452 uint32_t samplingRate,
1453 audio_format_t format,
1454 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001455 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001456 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001457 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001458{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001459 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1460 "session %d, flags %#x",
1461 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001462
Eric Laurentcaf7f482014-11-25 17:50:47 -08001463 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001464 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001465 audio_devices_t device;
1466 // handle legacy remote submix case where the address was not always specified
1467 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001468 audio_source_t inputSource = attr->source;
1469 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001470 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001471
Eric Laurentc447ded2015-01-06 08:47:05 -08001472 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1473 inputSource = AUDIO_SOURCE_MIC;
1474 }
1475 halInputSource = inputSource;
1476
Paul McLean466dc8e2015-04-17 13:15:36 -06001477 // Explicit routing?
1478 sp<DeviceDescriptor> deviceDesc;
1479 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1480 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1481 deviceDesc = mAvailableInputDevices[i];
1482 break;
1483 }
1484 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001485 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001486
Eric Laurentc447ded2015-01-06 08:47:05 -08001487 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001488 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001489 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001490 if (ret != NO_ERROR) {
1491 return ret;
1492 }
1493 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001494 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1495 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001496 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001497 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001498 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001499 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001500 return BAD_VALUE;
1501 }
Eric Laurentc722f302014-12-10 11:21:49 -08001502 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001503 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001504 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1505 // there is an external policy, but this input is attached to a mix of recorders,
1506 // meaning it receives audio injected into the framework, so the recorder doesn't
1507 // know about it and is therefore considered "legacy"
1508 *inputType = API_INPUT_LEGACY;
1509 } else {
1510 // recording a mix of players defined by an external policy, we're rerouting for
1511 // an external policy
1512 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1513 }
Eric Laurentc722f302014-12-10 11:21:49 -08001514 } else if (audio_is_remote_submix_device(device)) {
1515 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001516 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001517 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1518 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001519 } else {
1520 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001521 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001522
Eric Laurent599c7582015-12-07 18:05:55 -08001523 }
1524
1525 *input = getInputForDevice(device, address, session, uid, inputSource,
1526 samplingRate, format, channelMask, flags,
1527 policyMix);
1528 if (*input == AUDIO_IO_HANDLE_NONE) {
1529 mInputRoutes.removeRoute(session);
1530 return INVALID_OPERATION;
1531 }
1532 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1533 return NO_ERROR;
1534}
1535
1536
1537audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1538 String8 address,
1539 audio_session_t session,
1540 uid_t uid,
1541 audio_source_t inputSource,
1542 uint32_t samplingRate,
1543 audio_format_t format,
1544 audio_channel_mask_t channelMask,
1545 audio_input_flags_t flags,
1546 AudioMix *policyMix)
1547{
1548 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1549 audio_source_t halInputSource = inputSource;
1550 bool isSoundTrigger = false;
1551
1552 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1553 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1554 if (index >= 0) {
1555 input = mSoundTriggerSessions.valueFor(session);
1556 isSoundTrigger = true;
1557 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1558 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1559 } else {
1560 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001561 }
1562 }
1563
Andy Hungf129b032015-04-07 13:45:50 -07001564 // find a compatible input profile (not necessarily identical in parameters)
1565 sp<IOProfile> profile;
1566 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001567 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001568 audio_format_t profileFormat = format;
1569 audio_channel_mask_t profileChannelMask = channelMask;
1570 audio_input_flags_t profileFlags = flags;
1571 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001572 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001573 profileSamplingRate, profileFormat, profileChannelMask,
1574 profileFlags);
1575 if (profile != 0) {
1576 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001577 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1578 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001579 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1580 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1581 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001582 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1583 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001584 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001585 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001586 }
Eric Laurente552edb2014-03-10 17:42:56 -07001587 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001588 // Pick input sampling rate if not specified by client
1589 if (samplingRate == 0) {
1590 samplingRate = profileSamplingRate;
1591 }
Eric Laurente552edb2014-03-10 17:42:56 -07001592
Eric Laurent322b4d22015-04-03 15:57:54 -07001593 if (profile->getModuleHandle() == 0) {
1594 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001595 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001596 }
1597
Eric Laurent599c7582015-12-07 18:05:55 -08001598 sp<AudioSession> audioSession = new AudioSession(session,
1599 inputSource,
1600 format,
1601 samplingRate,
1602 channelMask,
1603 flags,
1604 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001605 isSoundTrigger,
1606 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001607
Eric Laurent232f26f2016-02-17 18:06:27 -08001608// TODO enable input reuse
1609#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001610 // reuse an open input if possible
1611 for (size_t i = 0; i < mInputs.size(); i++) {
1612 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent232f26f2016-02-17 18:06:27 -08001613 // reuse input if it shares the same profile and same sound trigger attribute
1614 if (profile == desc->mProfile &&
1615 isSoundTrigger == desc->isSoundTrigger()) {
Eric Laurent599c7582015-12-07 18:05:55 -08001616
1617 sp<AudioSession> as = desc->getAudioSession(session);
1618 if (as != 0) {
1619 // do not allow unmatching properties on same session
1620 if (as->matches(audioSession)) {
1621 as->changeOpenCount(1);
1622 } else {
1623 ALOGW("getInputForDevice() record with different attributes"
1624 " exists for session %d", session);
Eric Laurent232f26f2016-02-17 18:06:27 -08001625 return input;
Eric Laurent599c7582015-12-07 18:05:55 -08001626 }
1627 } else {
1628 desc->addAudioSession(session, audioSession);
1629 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001630 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1631 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001632 }
1633 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001634#endif
Eric Laurent599c7582015-12-07 18:05:55 -08001635
Eric Laurentcf2c0212014-07-25 16:20:43 -07001636 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001637 config.sample_rate = profileSamplingRate;
1638 config.channel_mask = profileChannelMask;
1639 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001640
Eric Laurent322b4d22015-04-03 15:57:54 -07001641 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001642 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001643 &config,
1644 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001645 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001646 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001647 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001648
1649 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001650 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001651 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001652 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001653 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001654 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1655 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001656 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001657 if (input != AUDIO_IO_HANDLE_NONE) {
1658 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001659 }
Eric Laurent599c7582015-12-07 18:05:55 -08001660 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
1662
Eric Laurent1f2f2232014-06-02 12:01:23 -07001663 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001664 inputDesc->mSamplingRate = profileSamplingRate;
1665 inputDesc->mFormat = profileFormat;
1666 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001667 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001668 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001669 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001670
Eric Laurent599c7582015-12-07 18:05:55 -08001671 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001672 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001673
Eric Laurent599c7582015-12-07 18:05:55 -08001674 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001675}
1676
Eric Laurent4dc68062014-07-28 17:26:49 -07001677status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurent232f26f2016-02-17 18:06:27 -08001678 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001679{
1680 ALOGV("startInput() input %d", input);
1681 ssize_t index = mInputs.indexOfKey(input);
1682 if (index < 0) {
1683 ALOGW("startInput() unknown input %d", input);
1684 return BAD_VALUE;
1685 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001686 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001687
Eric Laurent599c7582015-12-07 18:05:55 -08001688 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1689 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001690 ALOGW("startInput() unknown session %d on input %d", session, input);
1691 return BAD_VALUE;
1692 }
1693
Eric Laurent232f26f2016-02-17 18:06:27 -08001694 // virtual input devices are compatible with other input devices
1695 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001696
Eric Laurent232f26f2016-02-17 18:06:27 -08001697 // for a non-virtual input device, check if there is another (non-virtual) active input
1698 audio_io_handle_t activeInput = mInputs.getActiveInput();
1699 if (activeInput != 0 && activeInput != input) {
Eric Laurente552edb2014-03-10 17:42:56 -07001700
Eric Laurent232f26f2016-02-17 18:06:27 -08001701 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1702 // otherwise the active input continues and the new input cannot be started.
1703 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1704 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
1705 !activeDesc->hasPreemptedSession(session)) {
1706 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1707 //FIXME: consider all active sessions
1708 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1709 audio_session_t activeSession = activeSessions.keyAt(0);
1710 SortedVector<audio_session_t> sessions =
1711 activeDesc->getPreemptedSessions();
1712 sessions.add(activeSession);
1713 inputDesc->setPreemptedSessions(sessions);
1714 stopInput(activeInput, activeSession);
1715 releaseInput(activeInput, activeSession);
1716 } else {
1717 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1718 return INVALID_OPERATION;
1719 }
1720 }
1721
1722 // Do not allow capture if an active voice call is using a software patch and
1723 // the call TX source device is on the same HW module.
1724 // FIXME: would be better to refine to only inputs whose profile connects to the
1725 // call TX device but this information is not in the audio patch
1726 if (mCallTxPatch != 0 &&
1727 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1728 return INVALID_OPERATION;
1729 }
1730 }
Eric Laurent313d1e72016-01-29 09:56:57 -08001731
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001732 // Routing?
1733 mInputRoutes.incRouteActivity(session);
1734
Eric Laurent232f26f2016-02-17 18:06:27 -08001735 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
1736 // if input maps to a dynamic policy with an activity listener, notify of state change
1737 if ((inputDesc->mPolicyMix != NULL)
1738 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001739 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001740 MIX_STATE_MIXING);
1741 }
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001742
Eric Laurent271a93e2016-09-29 14:47:06 -07001743 // indicate active capture to sound trigger service if starting capture from a mic on
1744 // primary HW module
1745 audio_devices_t device = getNewInputDevice(input);
1746 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1747 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1748 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurent232f26f2016-02-17 18:06:27 -08001749 SoundTrigger::setCaptureState(true);
1750 }
Eric Laurent271a93e2016-09-29 14:47:06 -07001751 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001752
Eric Laurent232f26f2016-02-17 18:06:27 -08001753 // automatically enable the remote submix output when input is started if not
1754 // used by a policy mix of type MIX_TYPE_RECORDERS
1755 // For remote submix (a virtual device), we open only one input per capture request.
1756 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1757 String8 address = String8("");
1758 if (inputDesc->mPolicyMix == NULL) {
1759 address = String8("0");
1760 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001761 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurentc722f302014-12-10 11:21:49 -08001762 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001763 if (address != "") {
1764 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1765 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1766 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001767 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001768 }
Eric Laurente552edb2014-03-10 17:42:56 -07001769 }
1770
Eric Laurent599c7582015-12-07 18:05:55 -08001771 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001772
Eric Laurent232f26f2016-02-17 18:06:27 -08001773 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001774 return NO_ERROR;
1775}
1776
Eric Laurent4dc68062014-07-28 17:26:49 -07001777status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1778 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001779{
1780 ALOGV("stopInput() input %d", input);
1781 ssize_t index = mInputs.indexOfKey(input);
1782 if (index < 0) {
1783 ALOGW("stopInput() unknown input %d", input);
1784 return BAD_VALUE;
1785 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001786 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001787
Eric Laurent599c7582015-12-07 18:05:55 -08001788 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001789 if (index < 0) {
1790 ALOGW("stopInput() unknown session %d on input %d", session, input);
1791 return BAD_VALUE;
1792 }
1793
Eric Laurent599c7582015-12-07 18:05:55 -08001794 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001795 ALOGW("stopInput() input %d already stopped", input);
1796 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001797 }
1798
Eric Laurent599c7582015-12-07 18:05:55 -08001799 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001800
1801 // Routing?
1802 mInputRoutes.decRouteActivity(session);
1803
Eric Laurent232f26f2016-02-17 18:06:27 -08001804 if (!inputDesc->isActive()) {
1805 // if input maps to a dynamic policy with an activity listener, notify of state change
1806 if ((inputDesc->mPolicyMix != NULL)
1807 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001808 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001809 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001810 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001811
1812 // automatically disable the remote submix output when input is stopped if not
1813 // used by a policy mix of type MIX_TYPE_RECORDERS
1814 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1815 String8 address = String8("");
1816 if (inputDesc->mPolicyMix == NULL) {
1817 address = String8("0");
1818 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001819 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurent232f26f2016-02-17 18:06:27 -08001820 }
1821 if (address != "") {
1822 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1823 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1824 address, "remote-submix");
1825 }
1826 }
1827
Eric Laurent271a93e2016-09-29 14:47:06 -07001828 audio_devices_t device = inputDesc->mDevice;
Eric Laurent232f26f2016-02-17 18:06:27 -08001829 resetInputDevice(input);
1830
Eric Laurent271a93e2016-09-29 14:47:06 -07001831 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1832 // primary HW module
1833 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1834 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1835 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurent232f26f2016-02-17 18:06:27 -08001836 SoundTrigger::setCaptureState(false);
1837 }
1838 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001839 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001840 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001841}
1842
Eric Laurent4dc68062014-07-28 17:26:49 -07001843void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1844 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001845{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001846
Eric Laurente552edb2014-03-10 17:42:56 -07001847 ALOGV("releaseInput() %d", input);
1848 ssize_t index = mInputs.indexOfKey(input);
1849 if (index < 0) {
1850 ALOGW("releaseInput() releasing unknown input %d", input);
1851 return;
1852 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001853
1854 // Routing
1855 mInputRoutes.removeRoute(session);
1856
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001857 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1858 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001859
Eric Laurent599c7582015-12-07 18:05:55 -08001860 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001861 if (index < 0) {
1862 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1863 return;
1864 }
Eric Laurent599c7582015-12-07 18:05:55 -08001865
1866 if (audioSession->openCount() == 0) {
1867 ALOGW("releaseInput() invalid open count %d on session %d",
1868 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001869 return;
1870 }
Eric Laurent599c7582015-12-07 18:05:55 -08001871
1872 if (audioSession->changeOpenCount(-1) == 0) {
1873 inputDesc->removeAudioSession(session);
1874 }
1875
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001876 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001877 ALOGV("releaseInput() exit > 0");
1878 return;
1879 }
1880
Eric Laurent05b90f82014-08-27 15:32:29 -07001881 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001882 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001883 ALOGV("releaseInput() exit");
1884}
1885
Eric Laurentd4692962014-05-05 18:13:44 -07001886void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001887 bool patchRemoved = false;
1888
Eric Laurentd4692962014-05-05 18:13:44 -07001889 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001890 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001891 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001892 if (patch_index >= 0) {
1893 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001894 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001895 mAudioPatches.removeItemsAt(patch_index);
1896 patchRemoved = true;
1897 }
Eric Laurentd4692962014-05-05 18:13:44 -07001898 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1899 }
1900 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001901 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001902 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001903
1904 if (patchRemoved) {
1905 mpClientInterface->onAudioPatchListUpdate();
1906 }
Eric Laurentd4692962014-05-05 18:13:44 -07001907}
1908
Eric Laurente0720872014-03-11 09:30:41 -07001909void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001910 int indexMin,
1911 int indexMax)
1912{
1913 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001914 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001915
1916 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001917 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1918 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001919 continue;
1920 }
1921 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001922 }
Eric Laurente552edb2014-03-10 17:42:56 -07001923}
1924
Eric Laurente0720872014-03-11 09:30:41 -07001925status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001926 int index,
1927 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001928{
1929
François Gaffied1ab2bd2015-12-02 18:20:06 +01001930 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1931 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001932 return BAD_VALUE;
1933 }
1934 if (!audio_is_output_device(device)) {
1935 return BAD_VALUE;
1936 }
1937
1938 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001939 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001940
Eric Laurent1fd372e2016-04-06 14:23:53 -07001941 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001942 stream, device, index);
1943
Eric Laurent28d09f02016-03-08 10:43:05 -08001944 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001945 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1946 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001947 continue;
1948 }
1949 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1950 }
Eric Laurente552edb2014-03-10 17:42:56 -07001951
Eric Laurent1fd372e2016-04-06 14:23:53 -07001952 // update volume on all outputs and streams matching the following:
1953 // - The requested stream (or a stream matching for volume control) is active on the output
1954 // - The device (or devices) selected by the strategy corresponding to this stream includes
1955 // the requested device
1956 // - For non default requested device, currently selected device on the output is either the
1957 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001958 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1959 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001960 status_t status = NO_ERROR;
1961 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001962 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1963 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001964 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1965 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001966 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001967 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001968 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1969 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001970 continue;
1971 }
Eric Laurent794fde22016-03-11 09:50:45 -08001972 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07001973 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
1974 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
1975 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001976 continue;
1977 }
Eric Laurente76f29c2016-09-14 17:17:53 -07001978 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001979 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001980 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07001981 applyVolume = (curDevice & curStreamDevice) != 0;
1982 } else {
1983 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
1984 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07001985 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001986
Eric Laurente76f29c2016-09-14 17:17:53 -07001987 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07001988 //FIXME: workaround for truncated touch sounds
1989 // delayed volume change for system stream to be removed when the problem is
1990 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08001991 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07001992 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
1993 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08001994 if (volStatus != NO_ERROR) {
1995 status = volStatus;
1996 }
1997 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001998 }
Eric Laurente552edb2014-03-10 17:42:56 -07001999 }
2000 return status;
2001}
2002
Eric Laurente0720872014-03-11 09:30:41 -07002003status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002004 int *index,
2005 audio_devices_t device)
2006{
2007 if (index == NULL) {
2008 return BAD_VALUE;
2009 }
2010 if (!audio_is_output_device(device)) {
2011 return BAD_VALUE;
2012 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002013 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002014 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002015 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002016 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2017 }
François Gaffiedfd74092015-03-19 12:10:59 +01002018 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002019
François Gaffied1ab2bd2015-12-02 18:20:06 +01002020 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002021 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2022 return NO_ERROR;
2023}
2024
Eric Laurente0720872014-03-11 09:30:41 -07002025audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002026 const SortedVector<audio_io_handle_t>& outputs)
2027{
2028 // select one output among several suitable for global effects.
2029 // The priority is as follows:
2030 // 1: An offloaded output. If the effect ends up not being offloadable,
2031 // AudioFlinger will invalidate the track and the offloaded output
2032 // will be closed causing the effect to be moved to a PCM output.
2033 // 2: A deep buffer output
2034 // 3: the first output in the list
2035
2036 if (outputs.size() == 0) {
2037 return 0;
2038 }
2039
2040 audio_io_handle_t outputOffloaded = 0;
2041 audio_io_handle_t outputDeepBuffer = 0;
2042
2043 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002044 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002045 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002046 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2047 outputOffloaded = outputs[i];
2048 }
2049 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2050 outputDeepBuffer = outputs[i];
2051 }
2052 }
2053
2054 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2055 outputOffloaded, outputDeepBuffer);
2056 if (outputOffloaded != 0) {
2057 return outputOffloaded;
2058 }
2059 if (outputDeepBuffer != 0) {
2060 return outputDeepBuffer;
2061 }
2062
2063 return outputs[0];
2064}
2065
Eric Laurente0720872014-03-11 09:30:41 -07002066audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002067{
2068 // apply simple rule where global effects are attached to the same output as MUSIC streams
2069
Eric Laurent3b73df72014-03-11 09:06:29 -07002070 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002071 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2072 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2073
2074 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2075 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2076 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2077
2078 return output;
2079}
2080
Eric Laurente0720872014-03-11 09:30:41 -07002081status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002082 audio_io_handle_t io,
2083 uint32_t strategy,
2084 int session,
2085 int id)
2086{
2087 ssize_t index = mOutputs.indexOfKey(io);
2088 if (index < 0) {
2089 index = mInputs.indexOfKey(io);
2090 if (index < 0) {
2091 ALOGW("registerEffect() unknown io %d", io);
2092 return INVALID_OPERATION;
2093 }
2094 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002095 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002096}
2097
Eric Laurentc75307b2015-03-17 15:29:32 -07002098bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2099{
Eric Laurent28d09f02016-03-08 10:43:05 -08002100 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002101 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2102 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002103 continue;
2104 }
2105 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2106 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002107 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002108}
2109
2110bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2111{
2112 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2113}
2114
Eric Laurente0720872014-03-11 09:30:41 -07002115bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002116{
2117 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002118 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002119 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002120 return true;
2121 }
2122 }
2123 return false;
2124}
2125
Eric Laurent275e8e92014-11-30 15:14:47 -08002126// Register a list of custom mixes with their attributes and format.
2127// When a mix is registered, corresponding input and output profiles are
2128// added to the remote submix hw module. The profile contains only the
2129// parameters (sampling rate, format...) specified by the mix.
2130// The corresponding input remote submix device is also connected.
2131//
2132// When a remote submix device is connected, the address is checked to select the
2133// appropriate profile and the corresponding input or output stream is opened.
2134//
2135// When capture starts, getInputForAttr() will:
2136// - 1 look for a mix matching the address passed in attribtutes tags if any
2137// - 2 if none found, getDeviceForInputSource() will:
2138// - 2.1 look for a mix matching the attributes source
2139// - 2.2 if none found, default to device selection by policy rules
2140// At this time, the corresponding output remote submix device is also connected
2141// and active playback use cases can be transferred to this mix if needed when reconnecting
2142// after AudioTracks are invalidated
2143//
2144// When playback starts, getOutputForAttr() will:
2145// - 1 look for a mix matching the address passed in attribtutes tags if any
2146// - 2 if none found, look for a mix matching the attributes usage
2147// - 3 if none found, default to device and output selection by policy rules.
2148
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002149status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002150{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002151 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2152 status_t res = NO_ERROR;
2153
2154 sp<HwModule> rSubmixModule;
2155 // examine each mix's route type
2156 for (size_t i = 0; i < mixes.size(); i++) {
2157 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2158 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2159 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002160 break;
2161 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002162 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2163 // Loop back through "remote submix"
2164 if (rSubmixModule == 0) {
2165 for (size_t j = 0; i < mHwModules.size(); j++) {
2166 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2167 && mHwModules[j]->mHandle != 0) {
2168 rSubmixModule = mHwModules[j];
2169 break;
2170 }
2171 }
2172 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002173
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002174 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002175
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002176 if (rSubmixModule == 0) {
2177 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2178 res = INVALID_OPERATION;
2179 break;
2180 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002181
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002182 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002183
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002184 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002185 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002186 res = INVALID_OPERATION;
2187 break;
2188 }
2189 audio_config_t outputConfig = mixes[i].mFormat;
2190 audio_config_t inputConfig = mixes[i].mFormat;
2191 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2192 // stereo and let audio flinger do the channel conversion if needed.
2193 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2194 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2195 rSubmixModule->addOutputProfile(address, &outputConfig,
2196 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2197 rSubmixModule->addInputProfile(address, &inputConfig,
2198 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002199
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002200 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2201 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2202 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2203 address.string(), "remote-submix");
2204 } else {
2205 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2206 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2207 address.string(), "remote-submix");
2208 }
2209 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002210 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002211 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002212 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2213 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002214
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002215 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002216 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2217 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2218 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2219 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2220 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2221 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002222 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2223 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002224 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2225 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002226 } else {
2227 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002228 }
2229 break;
2230 }
2231 }
2232
2233 if (res != NO_ERROR) {
2234 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002235 i, device, address.string());
2236 res = INVALID_OPERATION;
2237 break;
2238 } else if (!foundOutput) {
2239 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2240 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002241 res = INVALID_OPERATION;
2242 break;
2243 }
Eric Laurentc722f302014-12-10 11:21:49 -08002244 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002245 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002246 if (res != NO_ERROR) {
2247 unregisterPolicyMixes(mixes);
2248 }
2249 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002250}
2251
2252status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2253{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002254 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002255 status_t res = NO_ERROR;
2256 sp<HwModule> rSubmixModule;
2257 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002258 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002259 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002260
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002261 if (rSubmixModule == 0) {
2262 for (size_t j = 0; i < mHwModules.size(); j++) {
2263 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2264 && mHwModules[j]->mHandle != 0) {
2265 rSubmixModule = mHwModules[j];
2266 break;
2267 }
2268 }
2269 }
2270 if (rSubmixModule == 0) {
2271 res = INVALID_OPERATION;
2272 continue;
2273 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002274
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002275 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002276
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002277 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2278 res = INVALID_OPERATION;
2279 continue;
2280 }
2281
2282 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2283 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2284 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2285 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2286 address.string(), "remote-submix");
2287 }
2288 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2289 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2290 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2291 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2292 address.string(), "remote-submix");
2293 }
2294 rSubmixModule->removeOutputProfile(address);
2295 rSubmixModule->removeInputProfile(address);
2296
2297 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2298 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2299 res = INVALID_OPERATION;
2300 continue;
2301 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002302 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002303 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002304 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002305}
2306
Eric Laurente552edb2014-03-10 17:42:56 -07002307
Eric Laurente0720872014-03-11 09:30:41 -07002308status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002309{
2310 const size_t SIZE = 256;
2311 char buffer[SIZE];
2312 String8 result;
2313
2314 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2315 result.append(buffer);
2316
Eric Laurent87ffa392015-05-22 10:32:38 -07002317 snprintf(buffer, SIZE, " Primary Output: %d\n",
2318 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002319 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002320 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002321 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002322 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002323 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002324 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002325 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002326 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002327 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002328 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002329 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002330 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002331 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002332 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002333 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002334 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002335 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002336 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2337 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2338 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002339 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2340 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002341 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2342 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002343
François Gaffie2110e042015-03-24 08:41:51 +01002344 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002345
François Gaffie112b0af2015-11-19 16:13:25 +01002346 mAvailableOutputDevices.dump(fd, String8("Available output"));
2347 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002348 mHwModules.dump(fd);
2349 mOutputs.dump(fd);
2350 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002351 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002352 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002353 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002354
2355 return NO_ERROR;
2356}
2357
2358// This function checks for the parameters which can be offloaded.
2359// This can be enhanced depending on the capability of the DSP and policy
2360// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002361bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002362{
2363 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002364 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002365 offloadInfo.sample_rate, offloadInfo.channel_mask,
2366 offloadInfo.format,
2367 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2368 offloadInfo.has_video);
2369
Andy Hung2ddee192015-12-18 17:34:44 -08002370 if (mMasterMono) {
2371 return false; // no offloading if mono is set.
2372 }
2373
Eric Laurente552edb2014-03-10 17:42:56 -07002374 // Check if offload has been disabled
2375 char propValue[PROPERTY_VALUE_MAX];
2376 if (property_get("audio.offload.disable", propValue, "0")) {
2377 if (atoi(propValue) != 0) {
2378 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2379 return false;
2380 }
2381 }
2382
2383 // Check if stream type is music, then only allow offload as of now.
2384 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2385 {
2386 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2387 return false;
2388 }
2389
2390 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002391 const bool allowOffloadWithVideo =
2392 property_get_bool("audio.offload.video", false /* default_value */);
2393 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002394 ALOGV("isOffloadSupported: has_video == true, returning false");
2395 return false;
2396 }
2397
2398 //If duration is less than minimum value defined in property, return false
2399 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2400 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2401 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2402 return false;
2403 }
2404 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2405 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2406 return false;
2407 }
2408
2409 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2410 // creating an offloaded track and tearing it down immediately after start when audioflinger
2411 // detects there is an active non offloadable effect.
2412 // FIXME: We should check the audio session here but we do not have it in this context.
2413 // This may prevent offloading in rare situations where effects are left active by apps
2414 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002415 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002416 return false;
2417 }
2418
2419 // See if there is a profile to support this.
2420 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002421 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002422 offloadInfo.sample_rate,
2423 offloadInfo.format,
2424 offloadInfo.channel_mask,
2425 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002426 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2427 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002428}
2429
Eric Laurent6a94d692014-05-20 11:18:06 -07002430status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2431 audio_port_type_t type,
2432 unsigned int *num_ports,
2433 struct audio_port *ports,
2434 unsigned int *generation)
2435{
2436 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2437 generation == NULL) {
2438 return BAD_VALUE;
2439 }
2440 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2441 if (ports == NULL) {
2442 *num_ports = 0;
2443 }
2444
2445 size_t portsWritten = 0;
2446 size_t portsMax = *num_ports;
2447 *num_ports = 0;
2448 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002449 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2450 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002451 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002452 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2453 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2454 continue;
2455 }
2456 if (portsWritten < portsMax) {
2457 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2458 }
2459 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002460 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002461 }
2462 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002463 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2464 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2465 continue;
2466 }
2467 if (portsWritten < portsMax) {
2468 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2469 }
2470 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002471 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002472 }
2473 }
2474 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2475 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2476 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2477 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2478 }
2479 *num_ports += mInputs.size();
2480 }
2481 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002482 size_t numOutputs = 0;
2483 for (size_t i = 0; i < mOutputs.size(); i++) {
2484 if (!mOutputs[i]->isDuplicated()) {
2485 numOutputs++;
2486 if (portsWritten < portsMax) {
2487 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2488 }
2489 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002490 }
Eric Laurent84c70242014-06-23 08:46:27 -07002491 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002492 }
2493 }
2494 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002495 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002496 return NO_ERROR;
2497}
2498
2499status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2500{
2501 return NO_ERROR;
2502}
2503
Eric Laurent6a94d692014-05-20 11:18:06 -07002504status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2505 audio_patch_handle_t *handle,
2506 uid_t uid)
2507{
2508 ALOGV("createAudioPatch()");
2509
2510 if (handle == NULL || patch == NULL) {
2511 return BAD_VALUE;
2512 }
2513 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2514
Eric Laurent874c42872014-08-08 15:13:39 -07002515 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2516 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2517 return BAD_VALUE;
2518 }
2519 // only one source per audio patch supported for now
2520 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002521 return INVALID_OPERATION;
2522 }
Eric Laurent874c42872014-08-08 15:13:39 -07002523
2524 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002525 return INVALID_OPERATION;
2526 }
Eric Laurent874c42872014-08-08 15:13:39 -07002527 for (size_t i = 0; i < patch->num_sinks; i++) {
2528 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2529 return INVALID_OPERATION;
2530 }
2531 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002532
2533 sp<AudioPatch> patchDesc;
2534 ssize_t index = mAudioPatches.indexOfKey(*handle);
2535
Eric Laurent6a94d692014-05-20 11:18:06 -07002536 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2537 patch->sources[0].role,
2538 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002539#if LOG_NDEBUG == 0
2540 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002541 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002542 patch->sinks[i].role,
2543 patch->sinks[i].type);
2544 }
2545#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002546
2547 if (index >= 0) {
2548 patchDesc = mAudioPatches.valueAt(index);
2549 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2550 mUidCached, patchDesc->mUid, uid);
2551 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2552 return INVALID_OPERATION;
2553 }
2554 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002555 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002556 }
2557
2558 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002559 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002560 if (outputDesc == NULL) {
2561 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2562 return BAD_VALUE;
2563 }
Eric Laurent84c70242014-06-23 08:46:27 -07002564 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2565 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002566 if (patchDesc != 0) {
2567 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2568 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2569 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2570 return BAD_VALUE;
2571 }
2572 }
Eric Laurent874c42872014-08-08 15:13:39 -07002573 DeviceVector devices;
2574 for (size_t i = 0; i < patch->num_sinks; i++) {
2575 // Only support mix to devices connection
2576 // TODO add support for mix to mix connection
2577 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2578 ALOGV("createAudioPatch() source mix but sink is not a device");
2579 return INVALID_OPERATION;
2580 }
2581 sp<DeviceDescriptor> devDesc =
2582 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2583 if (devDesc == 0) {
2584 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2585 return BAD_VALUE;
2586 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002587
François Gaffie53615e22015-03-19 09:24:12 +01002588 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002589 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002590 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002591 NULL, // updatedSamplingRate
2592 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002593 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002594 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002595 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002596 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002597 ALOGV("createAudioPatch() profile not supported for device %08x",
2598 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002599 return INVALID_OPERATION;
2600 }
2601 devices.add(devDesc);
2602 }
2603 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002604 return INVALID_OPERATION;
2605 }
Eric Laurent874c42872014-08-08 15:13:39 -07002606
Eric Laurent6a94d692014-05-20 11:18:06 -07002607 // TODO: reconfigure output format and channels here
2608 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002609 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002610 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002611 index = mAudioPatches.indexOfKey(*handle);
2612 if (index >= 0) {
2613 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2614 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2615 }
2616 patchDesc = mAudioPatches.valueAt(index);
2617 patchDesc->mUid = uid;
2618 ALOGV("createAudioPatch() success");
2619 } else {
2620 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2621 return INVALID_OPERATION;
2622 }
2623 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2624 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2625 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002626 // only one sink supported when connecting an input device to a mix
2627 if (patch->num_sinks > 1) {
2628 return INVALID_OPERATION;
2629 }
François Gaffie53615e22015-03-19 09:24:12 +01002630 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002631 if (inputDesc == NULL) {
2632 return BAD_VALUE;
2633 }
2634 if (patchDesc != 0) {
2635 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2636 return BAD_VALUE;
2637 }
2638 }
2639 sp<DeviceDescriptor> devDesc =
2640 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2641 if (devDesc == 0) {
2642 return BAD_VALUE;
2643 }
2644
François Gaffie53615e22015-03-19 09:24:12 +01002645 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002646 devDesc->mAddress,
2647 patch->sinks[0].sample_rate,
2648 NULL, /*updatedSampleRate*/
2649 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002650 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002651 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002652 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002653 // FIXME for the parameter type,
2654 // and the NONE
2655 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002656 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002657 return INVALID_OPERATION;
2658 }
2659 // TODO: reconfigure output format and channels here
2660 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002661 devDesc->type(), inputDesc->mIoHandle);
2662 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002663 index = mAudioPatches.indexOfKey(*handle);
2664 if (index >= 0) {
2665 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2666 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2667 }
2668 patchDesc = mAudioPatches.valueAt(index);
2669 patchDesc->mUid = uid;
2670 ALOGV("createAudioPatch() success");
2671 } else {
2672 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2673 return INVALID_OPERATION;
2674 }
2675 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2676 // device to device connection
2677 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002678 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002679 return BAD_VALUE;
2680 }
2681 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002682 sp<DeviceDescriptor> srcDeviceDesc =
2683 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002684 if (srcDeviceDesc == 0) {
2685 return BAD_VALUE;
2686 }
Eric Laurent874c42872014-08-08 15:13:39 -07002687
Eric Laurent6a94d692014-05-20 11:18:06 -07002688 //update source and sink with our own data as the data passed in the patch may
2689 // be incomplete.
2690 struct audio_patch newPatch = *patch;
2691 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002692
Eric Laurent874c42872014-08-08 15:13:39 -07002693 for (size_t i = 0; i < patch->num_sinks; i++) {
2694 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2695 ALOGV("createAudioPatch() source device but one sink is not a device");
2696 return INVALID_OPERATION;
2697 }
2698
2699 sp<DeviceDescriptor> sinkDeviceDesc =
2700 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2701 if (sinkDeviceDesc == 0) {
2702 return BAD_VALUE;
2703 }
2704 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2705
Eric Laurent3bcf8592015-04-03 12:13:24 -07002706 // create a software bridge in PatchPanel if:
2707 // - source and sink devices are on differnt HW modules OR
2708 // - audio HAL version is < 3.0
Eric Laurent232f26f2016-02-17 18:06:27 -08002709 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002710 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002711 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002712 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002713 return INVALID_OPERATION;
2714 }
Eric Laurent874c42872014-08-08 15:13:39 -07002715 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002716 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002717 // if the sink device is reachable via an opened output stream, request to go via
2718 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002719 audio_io_handle_t output = selectOutput(outputs,
2720 AUDIO_OUTPUT_FLAG_NONE,
2721 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002722 if (output != AUDIO_IO_HANDLE_NONE) {
2723 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2724 if (outputDesc->isDuplicated()) {
2725 return INVALID_OPERATION;
2726 }
2727 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002728 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002729 newPatch.num_sources = 2;
2730 }
Eric Laurent83b88082014-06-20 18:31:16 -07002731 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002732 }
2733 // TODO: check from routing capabilities in config file and other conflicting patches
2734
2735 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2736 if (index >= 0) {
2737 afPatchHandle = patchDesc->mAfPatchHandle;
2738 }
2739
2740 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2741 &afPatchHandle,
2742 0);
2743 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2744 status, afPatchHandle);
2745 if (status == NO_ERROR) {
2746 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002747 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002748 addAudioPatch(patchDesc->mHandle, patchDesc);
2749 } else {
2750 patchDesc->mPatch = newPatch;
2751 }
2752 patchDesc->mAfPatchHandle = afPatchHandle;
2753 *handle = patchDesc->mHandle;
2754 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002755 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 } else {
2757 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2758 status);
2759 return INVALID_OPERATION;
2760 }
2761 } else {
2762 return BAD_VALUE;
2763 }
2764 } else {
2765 return BAD_VALUE;
2766 }
2767 return NO_ERROR;
2768}
2769
2770status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2771 uid_t uid)
2772{
2773 ALOGV("releaseAudioPatch() patch %d", handle);
2774
2775 ssize_t index = mAudioPatches.indexOfKey(handle);
2776
2777 if (index < 0) {
2778 return BAD_VALUE;
2779 }
2780 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2781 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2782 mUidCached, patchDesc->mUid, uid);
2783 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2784 return INVALID_OPERATION;
2785 }
2786
2787 struct audio_patch *patch = &patchDesc->mPatch;
2788 patchDesc->mUid = mUidCached;
2789 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002790 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002791 if (outputDesc == NULL) {
2792 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2793 return BAD_VALUE;
2794 }
2795
Eric Laurentc75307b2015-03-17 15:29:32 -07002796 setOutputDevice(outputDesc,
2797 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 true,
2799 0,
2800 NULL);
2801 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2802 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002803 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002804 if (inputDesc == NULL) {
2805 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2806 return BAD_VALUE;
2807 }
2808 setInputDevice(inputDesc->mIoHandle,
Eric Laurent232f26f2016-02-17 18:06:27 -08002809 getNewInputDevice(inputDesc->mIoHandle),
Eric Laurent6a94d692014-05-20 11:18:06 -07002810 true,
2811 NULL);
2812 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2814 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2815 status, patchDesc->mAfPatchHandle);
2816 removeAudioPatch(patchDesc->mHandle);
2817 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002818 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002819 } else {
2820 return BAD_VALUE;
2821 }
2822 } else {
2823 return BAD_VALUE;
2824 }
2825 return NO_ERROR;
2826}
2827
2828status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2829 struct audio_patch *patches,
2830 unsigned int *generation)
2831{
François Gaffie53615e22015-03-19 09:24:12 +01002832 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 return BAD_VALUE;
2834 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002836 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002837}
2838
Eric Laurente1715a42014-05-20 11:30:42 -07002839status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002840{
Eric Laurente1715a42014-05-20 11:30:42 -07002841 ALOGV("setAudioPortConfig()");
2842
2843 if (config == NULL) {
2844 return BAD_VALUE;
2845 }
2846 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2847 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002848 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2849 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002850 }
2851
Eric Laurenta121f902014-06-03 13:32:54 -07002852 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002853 if (config->type == AUDIO_PORT_TYPE_MIX) {
2854 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002855 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002856 if (outputDesc == NULL) {
2857 return BAD_VALUE;
2858 }
Eric Laurent84c70242014-06-23 08:46:27 -07002859 ALOG_ASSERT(!outputDesc->isDuplicated(),
2860 "setAudioPortConfig() called on duplicated output %d",
2861 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002862 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002863 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002864 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002865 if (inputDesc == NULL) {
2866 return BAD_VALUE;
2867 }
Eric Laurenta121f902014-06-03 13:32:54 -07002868 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002869 } else {
2870 return BAD_VALUE;
2871 }
2872 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2873 sp<DeviceDescriptor> deviceDesc;
2874 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2875 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2876 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2877 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2878 } else {
2879 return BAD_VALUE;
2880 }
2881 if (deviceDesc == NULL) {
2882 return BAD_VALUE;
2883 }
Eric Laurenta121f902014-06-03 13:32:54 -07002884 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002885 } else {
2886 return BAD_VALUE;
2887 }
2888
Eric Laurenta121f902014-06-03 13:32:54 -07002889 struct audio_port_config backupConfig;
2890 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2891 if (status == NO_ERROR) {
2892 struct audio_port_config newConfig;
2893 audioPortConfig->toAudioPortConfig(&newConfig, config);
2894 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002895 }
Eric Laurenta121f902014-06-03 13:32:54 -07002896 if (status != NO_ERROR) {
2897 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002898 }
Eric Laurente1715a42014-05-20 11:30:42 -07002899
2900 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002901}
2902
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002903void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2904{
Eric Laurentd60560a2015-04-10 11:31:20 -07002905 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002906 clearAudioPatches(uid);
2907 clearSessionRoutes(uid);
2908}
2909
Eric Laurent6a94d692014-05-20 11:18:06 -07002910void AudioPolicyManager::clearAudioPatches(uid_t uid)
2911{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002912 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002913 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2914 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002915 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002916 }
2917 }
2918}
2919
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002920void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2921 audio_io_handle_t ouptutToSkip)
2922{
2923 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2924 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2925 for (size_t j = 0; j < mOutputs.size(); j++) {
2926 if (mOutputs.keyAt(j) == ouptutToSkip) {
2927 continue;
2928 }
2929 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2930 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2931 continue;
2932 }
2933 // If the default device for this strategy is on another output mix,
2934 // invalidate all tracks in this strategy to force re connection.
2935 // Otherwise select new device on the output mix.
2936 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002937 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002938 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2939 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2940 }
2941 }
2942 } else {
2943 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2944 setOutputDevice(outputDesc, newDevice, false);
2945 }
2946 }
2947}
2948
2949void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2950{
2951 // remove output routes associated with this uid
2952 SortedVector<routing_strategy> affectedStrategies;
2953 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2954 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2955 if (route->mUid == uid) {
2956 mOutputRoutes.removeItemsAt(i);
2957 if (route->mDeviceDescriptor != 0) {
2958 affectedStrategies.add(getStrategy(route->mStreamType));
2959 }
2960 }
2961 }
2962 // reroute outputs if necessary
2963 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2964 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2965 }
2966
2967 // remove input routes associated with this uid
2968 SortedVector<audio_source_t> affectedSources;
2969 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2970 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2971 if (route->mUid == uid) {
2972 mInputRoutes.removeItemsAt(i);
2973 if (route->mDeviceDescriptor != 0) {
2974 affectedSources.add(route->mSource);
2975 }
2976 }
2977 }
2978 // reroute inputs if necessary
2979 SortedVector<audio_io_handle_t> inputsToClose;
2980 for (size_t i = 0; i < mInputs.size(); i++) {
2981 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002982 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002983 inputsToClose.add(inputDesc->mIoHandle);
2984 }
2985 }
2986 for (size_t i = 0; i < inputsToClose.size(); i++) {
2987 closeInput(inputsToClose[i]);
2988 }
2989}
2990
Eric Laurentd60560a2015-04-10 11:31:20 -07002991void AudioPolicyManager::clearAudioSources(uid_t uid)
2992{
2993 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2994 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2995 if (sourceDesc->mUid == uid) {
2996 stopAudioSource(mAudioSources.keyAt(i));
2997 }
2998 }
2999}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003000
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003001status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3002 audio_io_handle_t *ioHandle,
3003 audio_devices_t *device)
3004{
Glenn Kasteneeecb982016-02-26 10:44:04 -08003005 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3006 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003007 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003008
François Gaffiedf372692015-03-19 10:43:27 +01003009 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003010}
3011
Eric Laurentd60560a2015-04-10 11:31:20 -07003012status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3013 const audio_attributes_t *attributes,
3014 audio_io_handle_t *handle,
3015 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003016{
Eric Laurentd60560a2015-04-10 11:31:20 -07003017 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3018 if (source == NULL || attributes == NULL || handle == NULL) {
3019 return BAD_VALUE;
3020 }
3021
3022 *handle = AUDIO_IO_HANDLE_NONE;
3023
3024 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3025 source->type != AUDIO_PORT_TYPE_DEVICE) {
3026 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3027 return INVALID_OPERATION;
3028 }
3029
3030 sp<DeviceDescriptor> srcDeviceDesc =
3031 mAvailableInputDevices.getDevice(source->ext.device.type,
3032 String8(source->ext.device.address));
3033 if (srcDeviceDesc == 0) {
3034 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3035 return BAD_VALUE;
3036 }
3037 sp<AudioSourceDescriptor> sourceDesc =
3038 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3039
3040 struct audio_patch dummyPatch;
3041 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3042 sourceDesc->mPatchDesc = patchDesc;
3043
3044 status_t status = connectAudioSource(sourceDesc);
3045 if (status == NO_ERROR) {
3046 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3047 *handle = sourceDesc->getHandle();
3048 }
3049 return status;
3050}
3051
3052status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3053{
3054 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3055
3056 // make sure we only have one patch per source.
3057 disconnectAudioSource(sourceDesc);
3058
3059 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003060 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003061 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3062
3063 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3064 sp<DeviceDescriptor> sinkDeviceDesc =
3065 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3066
3067 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3068 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3069
3070 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3071 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003072 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003073 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3074 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3075 // create patch between src device and output device
3076 // create Hwoutput and add to mHwOutputs
3077 } else {
3078 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3079 audio_io_handle_t output =
3080 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3081 if (output == AUDIO_IO_HANDLE_NONE) {
3082 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3083 return INVALID_OPERATION;
3084 }
3085 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3086 if (outputDesc->isDuplicated()) {
3087 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3088 return INVALID_OPERATION;
3089 }
3090 // create a special patch with no sink and two sources:
3091 // - the second source indicates to PatchPanel through which output mix this patch should
3092 // be connected as well as the stream type for volume control
3093 // - the sink is defined by whatever output device is currently selected for the output
3094 // though which this patch is routed.
3095 patch->num_sinks = 0;
3096 patch->num_sources = 2;
3097 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3098 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3099 patch->sources[1].ext.mix.usecase.stream = stream;
3100 status_t status = mpClientInterface->createAudioPatch(patch,
3101 &afPatchHandle,
3102 0);
3103 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3104 status, afPatchHandle);
3105 if (status != NO_ERROR) {
3106 ALOGW("%s patch panel could not connect device patch, error %d",
3107 __FUNCTION__, status);
3108 return INVALID_OPERATION;
3109 }
3110 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003111 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003112
3113 if (status != NO_ERROR) {
3114 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3115 return status;
3116 }
3117 sourceDesc->mSwOutput = outputDesc;
3118 if (delayMs != 0) {
3119 usleep(delayMs * 1000);
3120 }
3121 }
3122
3123 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3124 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3125
3126 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003127}
3128
Eric Laurent493404d2015-04-21 15:07:36 -07003129status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003130{
Eric Laurentd60560a2015-04-10 11:31:20 -07003131 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3132 ALOGV("%s handle %d", __FUNCTION__, handle);
3133 if (sourceDesc == 0) {
3134 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3135 return BAD_VALUE;
3136 }
3137 status_t status = disconnectAudioSource(sourceDesc);
3138
3139 mAudioSources.removeItem(handle);
3140 return status;
3141}
3142
Andy Hung2ddee192015-12-18 17:34:44 -08003143status_t AudioPolicyManager::setMasterMono(bool mono)
3144{
3145 if (mMasterMono == mono) {
3146 return NO_ERROR;
3147 }
3148 mMasterMono = mono;
3149 // if enabling mono we close all offloaded devices, which will invalidate the
3150 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3151 // for recreating the new AudioTrack as non-offloaded PCM.
3152 //
3153 // If disabling mono, we leave all tracks as is: we don't know which clients
3154 // and tracks are able to be recreated as offloaded. The next "song" should
3155 // play back offloaded.
3156 if (mMasterMono) {
3157 Vector<audio_io_handle_t> offloaded;
3158 for (size_t i = 0; i < mOutputs.size(); ++i) {
3159 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3160 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3161 offloaded.push(desc->mIoHandle);
3162 }
3163 }
3164 for (size_t i = 0; i < offloaded.size(); ++i) {
3165 closeOutput(offloaded[i]);
3166 }
3167 }
3168 // update master mono for all remaining outputs
3169 for (size_t i = 0; i < mOutputs.size(); ++i) {
3170 updateMono(mOutputs.keyAt(i));
3171 }
3172 return NO_ERROR;
3173}
3174
3175status_t AudioPolicyManager::getMasterMono(bool *mono)
3176{
3177 *mono = mMasterMono;
3178 return NO_ERROR;
3179}
3180
Eric Laurentd60560a2015-04-10 11:31:20 -07003181status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3182{
3183 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3184
3185 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3186 if (patchDesc == 0) {
3187 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3188 sourceDesc->mPatchDesc->mHandle);
3189 return BAD_VALUE;
3190 }
3191 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3192
Eric Laurent28d09f02016-03-08 10:43:05 -08003193 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003194 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3195 if (swOutputDesc != 0) {
3196 stopSource(swOutputDesc, stream, false);
3197 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3198 } else {
3199 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3200 if (hwOutputDesc != 0) {
3201 // release patch between src device and output device
3202 // close Hwoutput and remove from mHwOutputs
3203 } else {
3204 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3205 }
3206 }
3207 return NO_ERROR;
3208}
3209
3210sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3211 audio_io_handle_t output, routing_strategy strategy)
3212{
3213 sp<AudioSourceDescriptor> source;
3214 for (size_t i = 0; i < mAudioSources.size(); i++) {
3215 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3216 routing_strategy sourceStrategy =
3217 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3218 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3219 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3220 source = sourceDesc;
3221 break;
3222 }
3223 }
3224 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003225}
3226
Eric Laurente552edb2014-03-10 17:42:56 -07003227// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003228// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003229// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003230uint32_t AudioPolicyManager::nextAudioPortGeneration()
3231{
3232 return android_atomic_inc(&mAudioPortGeneration);
3233}
3234
Eric Laurente0720872014-03-11 09:30:41 -07003235AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003236 :
3237#ifdef AUDIO_POLICY_TEST
3238 Thread(false),
3239#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003240 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003241 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003242 mAudioPortGeneration(1),
3243 mBeaconMuteRefCount(0),
3244 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003245 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003246 mTtsOutputAvailable(false),
3247 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003248{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003249 mUidCached = getuid();
3250 mpClientInterface = clientInterface;
3251
3252 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3253 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3254 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3255 bool speakerDrcEnabled = false;
3256
3257#ifdef USE_XML_AUDIO_POLICY_CONF
3258 mVolumeCurves = new VolumeCurvesCollection();
3259 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3260 mDefaultOutputDevice, speakerDrcEnabled,
3261 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3262 PolicySerializer serializer;
3263 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3264#else
3265 mVolumeCurves = new StreamDescriptorCollection();
3266 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3267 mDefaultOutputDevice, speakerDrcEnabled);
3268 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3269 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3270#endif
3271 ALOGE("could not load audio policy configuration file, setting defaults");
3272 config.setDefault();
3273 }
3274 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3275 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3276
3277 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003278 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3279 if (!engineInstance) {
3280 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3281 return;
3282 }
3283 // Retrieve the Policy Manager Interface
3284 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3285 if (mEngine == NULL) {
3286 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3287 return;
3288 }
3289 mEngine->setObserver(this);
3290 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003291 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003292 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3293
Eric Laurent3a4311c2014-03-17 12:00:47 -07003294 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003295 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003296 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3297 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003298 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003299 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003300 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003301 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003302 continue;
3303 }
3304 // open all output streams needed to access attached devices
3305 // except for direct output streams that are only opened when they are actually
3306 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003307 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003308 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3309 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003310 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003311
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003312 if (!outProfile->hasSupportedDevices()) {
3313 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003314 continue;
3315 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003316 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003317 mTtsOutputAvailable = true;
3318 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003319
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003320 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003321 continue;
3322 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003323 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003324 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3325 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003326 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003327 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003328 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003329 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003330 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003331 if ((profileType & outputDeviceTypes) == 0) {
3332 continue;
3333 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003334 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3335 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003336 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3337 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3338 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3339 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003340
3341 outputDesc->mDevice = profileType;
3342 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3343 config.sample_rate = outputDesc->mSamplingRate;
3344 config.channel_mask = outputDesc->mChannelMask;
3345 config.format = outputDesc->mFormat;
3346 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003347 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003348 &output,
3349 &config,
3350 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003351 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003352 &outputDesc->mLatency,
3353 outputDesc->mFlags);
3354
3355 if (status != NO_ERROR) {
3356 ALOGW("Cannot open output stream for device %08x on hw module %s",
3357 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003358 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003359 } else {
3360 outputDesc->mSamplingRate = config.sample_rate;
3361 outputDesc->mChannelMask = config.channel_mask;
3362 outputDesc->mFormat = config.format;
3363
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003364 for (size_t k = 0; k < supportedDevices.size(); k++) {
3365 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003366 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003367 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3368 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003369 }
3370 }
3371 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003372 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003373 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003374 }
3375 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003376 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003377 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003378 true,
3379 0,
3380 NULL,
3381 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003382 }
Eric Laurente552edb2014-03-10 17:42:56 -07003383 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003384 // open input streams needed to access attached devices to validate
3385 // mAvailableInputDevices list
3386 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3387 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003388 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003389
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003390 if (!inProfile->hasSupportedDevices()) {
3391 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003392 continue;
3393 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003394 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003395 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003396 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3397
Eric Laurentd78f1532014-09-16 16:38:20 -07003398 if ((profileType & inputDeviceTypes) == 0) {
3399 continue;
3400 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003401 sp<AudioInputDescriptor> inputDesc =
3402 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003403
Eric Laurentd78f1532014-09-16 16:38:20 -07003404 inputDesc->mDevice = profileType;
3405
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003406 // find the address
3407 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3408 // the inputs vector must be of size 1, but we don't want to crash here
3409 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3410 : String8("");
3411 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3412 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3413
Eric Laurentd78f1532014-09-16 16:38:20 -07003414 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3415 config.sample_rate = inputDesc->mSamplingRate;
3416 config.channel_mask = inputDesc->mChannelMask;
3417 config.format = inputDesc->mFormat;
3418 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003419 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003420 &input,
3421 &config,
3422 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003423 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003424 AUDIO_SOURCE_MIC,
3425 AUDIO_INPUT_FLAG_NONE);
3426
3427 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003428 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3429 for (size_t k = 0; k < supportedDevices.size(); k++) {
3430 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003431 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003432 if (index >= 0) {
3433 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3434 if (!devDesc->isAttached()) {
3435 devDesc->attach(mHwModules[i]);
3436 devDesc->importAudioPort(inProfile);
3437 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003438 }
3439 }
3440 mpClientInterface->closeInput(input);
3441 } else {
3442 ALOGW("Cannot open input stream for device %08x on hw module %s",
3443 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003444 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003445 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003446 }
3447 }
3448 // make sure all attached devices have been allocated a unique ID
3449 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003450 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003451 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003452 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3453 continue;
3454 }
François Gaffie2110e042015-03-24 08:41:51 +01003455 // The device is now validated and can be appended to the available devices of the engine
3456 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3457 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003458 i++;
3459 }
3460 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003461 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003462 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003463 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3464 continue;
3465 }
François Gaffie2110e042015-03-24 08:41:51 +01003466 // The device is now validated and can be appended to the available devices of the engine
3467 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3468 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003469 i++;
3470 }
3471 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003472 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003473 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003474 }
Eric Laurente552edb2014-03-10 17:42:56 -07003475
3476 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3477
3478 updateDevicesAndOutputs();
3479
3480#ifdef AUDIO_POLICY_TEST
3481 if (mPrimaryOutput != 0) {
3482 AudioParameter outputCmd = AudioParameter();
3483 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003484 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003485
3486 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3487 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003488 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3489 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003490 mTestLatencyMs = 0;
3491 mCurOutput = 0;
3492 mDirectOutput = false;
3493 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3494 mTestOutputs[i] = 0;
3495 }
3496
3497 const size_t SIZE = 256;
3498 char buffer[SIZE];
3499 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3500 run(buffer, ANDROID_PRIORITY_AUDIO);
3501 }
3502#endif //AUDIO_POLICY_TEST
3503}
3504
Eric Laurente0720872014-03-11 09:30:41 -07003505AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003506{
3507#ifdef AUDIO_POLICY_TEST
3508 exit();
3509#endif //AUDIO_POLICY_TEST
3510 for (size_t i = 0; i < mOutputs.size(); i++) {
3511 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003512 }
3513 for (size_t i = 0; i < mInputs.size(); i++) {
3514 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003515 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003516 mAvailableOutputDevices.clear();
3517 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003518 mOutputs.clear();
3519 mInputs.clear();
3520 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003521}
3522
Eric Laurente0720872014-03-11 09:30:41 -07003523status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003524{
Eric Laurent87ffa392015-05-22 10:32:38 -07003525 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003526}
3527
3528#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003529bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003530{
3531 ALOGV("entering threadLoop()");
3532 while (!exitPending())
3533 {
3534 String8 command;
3535 int valueInt;
3536 String8 value;
3537
3538 Mutex::Autolock _l(mLock);
3539 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3540
3541 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3542 AudioParameter param = AudioParameter(command);
3543
3544 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3545 valueInt != 0) {
3546 ALOGV("Test command %s received", command.string());
3547 String8 target;
3548 if (param.get(String8("target"), target) != NO_ERROR) {
3549 target = "Manager";
3550 }
3551 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3552 param.remove(String8("test_cmd_policy_output"));
3553 mCurOutput = valueInt;
3554 }
3555 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3556 param.remove(String8("test_cmd_policy_direct"));
3557 if (value == "false") {
3558 mDirectOutput = false;
3559 } else if (value == "true") {
3560 mDirectOutput = true;
3561 }
3562 }
3563 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3564 param.remove(String8("test_cmd_policy_input"));
3565 mTestInput = valueInt;
3566 }
3567
3568 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3569 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003570 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003571 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003572 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003573 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003574 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003575 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003576 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003577 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003578 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003579 if (target == "Manager") {
3580 mTestFormat = format;
3581 } else if (mTestOutputs[mCurOutput] != 0) {
3582 AudioParameter outputParam = AudioParameter();
3583 outputParam.addInt(String8("format"), format);
3584 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3585 }
3586 }
3587 }
3588 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3589 param.remove(String8("test_cmd_policy_channels"));
3590 int channels = 0;
3591
3592 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003593 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003594 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003595 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003596 }
3597 if (channels != 0) {
3598 if (target == "Manager") {
3599 mTestChannels = channels;
3600 } else if (mTestOutputs[mCurOutput] != 0) {
3601 AudioParameter outputParam = AudioParameter();
3602 outputParam.addInt(String8("channels"), channels);
3603 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3604 }
3605 }
3606 }
3607 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3608 param.remove(String8("test_cmd_policy_sampleRate"));
3609 if (valueInt >= 0 && valueInt <= 96000) {
3610 int samplingRate = valueInt;
3611 if (target == "Manager") {
3612 mTestSamplingRate = samplingRate;
3613 } else if (mTestOutputs[mCurOutput] != 0) {
3614 AudioParameter outputParam = AudioParameter();
3615 outputParam.addInt(String8("sampling_rate"), samplingRate);
3616 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3617 }
3618 }
3619 }
3620
3621 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3622 param.remove(String8("test_cmd_policy_reopen"));
3623
Eric Laurentc75307b2015-03-17 15:29:32 -07003624 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003625
Eric Laurentc75307b2015-03-17 15:29:32 -07003626 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003627
Eric Laurentc75307b2015-03-17 15:29:32 -07003628 removeOutput(mPrimaryOutput->mIoHandle);
3629 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3630 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003631 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003632 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3633 config.sample_rate = outputDesc->mSamplingRate;
3634 config.channel_mask = outputDesc->mChannelMask;
3635 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003636 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003637 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003638 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003639 &config,
3640 &outputDesc->mDevice,
3641 String8(""),
3642 &outputDesc->mLatency,
3643 outputDesc->mFlags);
3644 if (status != NO_ERROR) {
3645 ALOGE("Failed to reopen hardware output stream, "
3646 "samplingRate: %d, format %d, channels %d",
3647 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003648 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003649 outputDesc->mSamplingRate = config.sample_rate;
3650 outputDesc->mChannelMask = config.channel_mask;
3651 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003652 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003653 AudioParameter outputCmd = AudioParameter();
3654 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003655 mpClientInterface->setParameters(handle, outputCmd.toString());
3656 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003657 }
3658 }
3659
3660
3661 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3662 }
3663 }
3664 return false;
3665}
3666
Eric Laurente0720872014-03-11 09:30:41 -07003667void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003668{
3669 {
3670 AutoMutex _l(mLock);
3671 requestExit();
3672 mWaitWorkCV.signal();
3673 }
3674 requestExitAndWait();
3675}
3676
Eric Laurente0720872014-03-11 09:30:41 -07003677int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003678{
3679 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3680 if (output == mTestOutputs[i]) return i;
3681 }
3682 return 0;
3683}
3684#endif //AUDIO_POLICY_TEST
3685
3686// ---
3687
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003688void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003689{
François Gaffie98cc1912015-03-18 17:52:40 +01003690 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003691 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003692 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003693 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003694}
3695
François Gaffie53615e22015-03-19 09:24:12 +01003696void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3697{
3698 mOutputs.removeItem(output);
3699}
3700
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003701void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003702{
François Gaffie98cc1912015-03-18 17:52:40 +01003703 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003704 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003705 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003706}
Eric Laurente552edb2014-03-10 17:42:56 -07003707
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003708void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003709 const audio_devices_t device /*in*/,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003710 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003711 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003712 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003713 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003714 if (devDesc != 0) {
3715 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3716 desc->mIoHandle, address.string());
3717 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003718 }
3719}
3720
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003721status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003722 audio_policy_dev_state_t state,
3723 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003724 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003725{
François Gaffie53615e22015-03-19 09:24:12 +01003726 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003727 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003728
3729 if (audio_device_is_digital(device)) {
3730 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003731 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003732 }
Eric Laurente552edb2014-03-10 17:42:56 -07003733
Eric Laurent3b73df72014-03-11 09:06:29 -07003734 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003735 // first list already open outputs that can be routed to this device
3736 for (size_t i = 0; i < mOutputs.size(); i++) {
3737 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003738 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003739 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003740 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3741 outputs.add(mOutputs.keyAt(i));
3742 } else {
3743 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003744 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003745 }
Eric Laurente552edb2014-03-10 17:42:56 -07003746 }
3747 }
3748 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003749 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003750 for (size_t i = 0; i < mHwModules.size(); i++)
3751 {
3752 if (mHwModules[i]->mHandle == 0) {
3753 continue;
3754 }
3755 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3756 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003757 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003758 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003759 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003760 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003761 profiles.add(profile);
3762 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3763 }
Eric Laurente552edb2014-03-10 17:42:56 -07003764 }
3765 }
3766 }
3767
Eric Laurent7b279bb2015-12-14 10:18:23 -08003768 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003769
Eric Laurente552edb2014-03-10 17:42:56 -07003770 if (profiles.isEmpty() && outputs.isEmpty()) {
3771 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3772 return BAD_VALUE;
3773 }
3774
3775 // open outputs for matching profiles if needed. Direct outputs are also opened to
3776 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3777 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003778 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003779
3780 // nothing to do if one output is already opened for this profile
3781 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003782 for (j = 0; j < outputs.size(); j++) {
3783 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003784 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003785 // matching profile: save the sample rates, format and channel masks supported
3786 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003787 if (audio_device_is_digital(device)) {
3788 devDesc->importAudioPort(profile);
3789 }
Eric Laurente552edb2014-03-10 17:42:56 -07003790 break;
3791 }
3792 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003793 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003794 continue;
3795 }
3796
Eric Laurent83b88082014-06-20 18:31:16 -07003797 ALOGV("opening output for device %08x with params %s profile %p",
3798 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003799 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003800 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003801 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3802 config.sample_rate = desc->mSamplingRate;
3803 config.channel_mask = desc->mChannelMask;
3804 config.format = desc->mFormat;
3805 config.offload_info.sample_rate = desc->mSamplingRate;
3806 config.offload_info.channel_mask = desc->mChannelMask;
3807 config.offload_info.format = desc->mFormat;
3808 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003809 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003810 &output,
3811 &config,
3812 &desc->mDevice,
3813 address,
3814 &desc->mLatency,
3815 desc->mFlags);
3816 if (status == NO_ERROR) {
3817 desc->mSamplingRate = config.sample_rate;
3818 desc->mChannelMask = config.channel_mask;
3819 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003820
Eric Laurentd4692962014-05-05 18:13:44 -07003821 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003822 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003823 char *param = audio_device_address_to_parameter(device, address);
3824 mpClientInterface->setParameters(output, String8(param));
3825 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003826 }
Phil Burk00eeb322016-03-31 12:41:00 -07003827 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003828 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003829 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003830 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003831 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003832 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003833 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003834 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003835 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003836 config.offload_info.sample_rate = config.sample_rate;
3837 config.offload_info.channel_mask = config.channel_mask;
3838 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003839 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003840 &output,
3841 &config,
3842 &desc->mDevice,
3843 address,
3844 &desc->mLatency,
3845 desc->mFlags);
3846 if (status == NO_ERROR) {
3847 desc->mSamplingRate = config.sample_rate;
3848 desc->mChannelMask = config.channel_mask;
3849 desc->mFormat = config.format;
3850 } else {
3851 output = AUDIO_IO_HANDLE_NONE;
3852 }
Eric Laurentd4692962014-05-05 18:13:44 -07003853 }
3854
Eric Laurentcf2c0212014-07-25 16:20:43 -07003855 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003856 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003857 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003858 sp<AudioPolicyMix> policyMix;
3859 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003860 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3861 address.string());
3862 }
François Gaffie036e1e92015-03-19 10:16:24 +01003863 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003864 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003865
Eric Laurent87ffa392015-05-22 10:32:38 -07003866 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3867 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003868 // no duplicated output for direct outputs and
3869 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003870 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003871
Eric Laurentd4692962014-05-05 18:13:44 -07003872 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003873 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003874
Eric Laurentd4692962014-05-05 18:13:44 -07003875 //TODO: configure audio effect output stage here
3876
3877 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003878 duplicatedOutput =
3879 mpClientInterface->openDuplicateOutput(output,
3880 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003881 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003882 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003883 sp<SwAudioOutputDescriptor> dupOutputDesc =
3884 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3885 dupOutputDesc->mOutput1 = mPrimaryOutput;
3886 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003887 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3888 dupOutputDesc->mFormat = desc->mFormat;
3889 dupOutputDesc->mChannelMask = desc->mChannelMask;
3890 dupOutputDesc->mLatency = desc->mLatency;
3891 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003892 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003893 } else {
3894 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003895 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003896 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003897 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003898 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003899 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003900 }
Eric Laurente552edb2014-03-10 17:42:56 -07003901 }
3902 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003903 } else {
3904 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003905 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003906 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003907 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003908 profiles.removeAt(profile_index);
3909 profile_index--;
3910 } else {
3911 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003912 // Load digital format info only for digital devices
3913 if (audio_device_is_digital(device)) {
3914 devDesc->importAudioPort(profile);
3915 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003916
François Gaffie53615e22015-03-19 09:24:12 +01003917 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003918 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3919 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003920 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003921 NULL/*patch handle*/, address.string());
3922 }
Eric Laurente552edb2014-03-10 17:42:56 -07003923 ALOGV("checkOutputsForDevice(): adding output %d", output);
3924 }
3925 }
3926
3927 if (profiles.isEmpty()) {
3928 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3929 return BAD_VALUE;
3930 }
Eric Laurentd4692962014-05-05 18:13:44 -07003931 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003932 // check if one opened output is not needed any more after disconnecting one device
3933 for (size_t i = 0; i < mOutputs.size(); i++) {
3934 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003935 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003936 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003937 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003938 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003939 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003940 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003941 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3942 mOutputs.keyAt(i));
3943 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003944 }
Eric Laurente552edb2014-03-10 17:42:56 -07003945 }
3946 }
Eric Laurentd4692962014-05-05 18:13:44 -07003947 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003948 for (size_t i = 0; i < mHwModules.size(); i++)
3949 {
3950 if (mHwModules[i]->mHandle == 0) {
3951 continue;
3952 }
3953 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3954 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003955 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003956 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003957 ALOGV("checkOutputsForDevice(): "
3958 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003959 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003960 }
3961 }
3962 }
3963 }
3964 return NO_ERROR;
3965}
3966
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003967status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003968 audio_policy_dev_state_t state,
3969 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003970 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003971{
Paul McLean9080a4c2015-06-18 08:24:02 -07003972 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003973 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003974
3975 if (audio_device_is_digital(device)) {
3976 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003977 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003978 }
3979
Eric Laurentd4692962014-05-05 18:13:44 -07003980 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3981 // first list already open inputs that can be routed to this device
3982 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3983 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003984 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003985 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3986 inputs.add(mInputs.keyAt(input_index));
3987 }
3988 }
3989
3990 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003991 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003992 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3993 {
3994 if (mHwModules[module_idx]->mHandle == 0) {
3995 continue;
3996 }
3997 for (size_t profile_index = 0;
3998 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3999 profile_index++)
4000 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004001 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4002
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004003 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004004 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004005 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004006 profiles.add(profile);
4007 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4008 profile_index, module_idx);
4009 }
Eric Laurentd4692962014-05-05 18:13:44 -07004010 }
4011 }
4012 }
4013
4014 if (profiles.isEmpty() && inputs.isEmpty()) {
4015 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4016 return BAD_VALUE;
4017 }
4018
4019 // open inputs for matching profiles if needed. Direct inputs are also opened to
4020 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4021 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4022
Eric Laurent1c333e22014-05-20 10:48:17 -07004023 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004024 // nothing to do if one input is already opened for this profile
4025 size_t input_index;
4026 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4027 desc = mInputs.valueAt(input_index);
4028 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004029 if (audio_device_is_digital(device)) {
4030 devDesc->importAudioPort(profile);
4031 }
Eric Laurentd4692962014-05-05 18:13:44 -07004032 break;
4033 }
4034 }
4035 if (input_index != mInputs.size()) {
4036 continue;
4037 }
4038
4039 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4040 desc = new AudioInputDescriptor(profile);
4041 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004042 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4043 config.sample_rate = desc->mSamplingRate;
4044 config.channel_mask = desc->mChannelMask;
4045 config.format = desc->mFormat;
4046 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004047 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004048 &input,
4049 &config,
4050 &desc->mDevice,
4051 address,
4052 AUDIO_SOURCE_MIC,
4053 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004054
Eric Laurentcf2c0212014-07-25 16:20:43 -07004055 if (status == NO_ERROR) {
4056 desc->mSamplingRate = config.sample_rate;
4057 desc->mChannelMask = config.channel_mask;
4058 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004059
Eric Laurentd4692962014-05-05 18:13:44 -07004060 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004061 char *param = audio_device_address_to_parameter(device, address);
4062 mpClientInterface->setParameters(input, String8(param));
4063 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004064 }
Phil Burk00eeb322016-03-31 12:41:00 -07004065 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004066 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004067 ALOGW("checkInputsForDevice() direct input missing param");
4068 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004069 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004070 }
4071
4072 if (input != 0) {
4073 addInput(input, desc);
4074 }
4075 } // endif input != 0
4076
Eric Laurentcf2c0212014-07-25 16:20:43 -07004077 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004078 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004079 profiles.removeAt(profile_index);
4080 profile_index--;
4081 } else {
4082 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004083 if (audio_device_is_digital(device)) {
4084 devDesc->importAudioPort(profile);
4085 }
Eric Laurentd4692962014-05-05 18:13:44 -07004086 ALOGV("checkInputsForDevice(): adding input %d", input);
4087 }
4088 } // end scan profiles
4089
4090 if (profiles.isEmpty()) {
4091 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4092 return BAD_VALUE;
4093 }
4094 } else {
4095 // Disconnect
4096 // check if one opened input is not needed any more after disconnecting one device
4097 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4098 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004099 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004100 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4101 mInputs.keyAt(input_index));
4102 inputs.add(mInputs.keyAt(input_index));
4103 }
4104 }
4105 // Clear any profiles associated with the disconnected device.
4106 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4107 if (mHwModules[module_index]->mHandle == 0) {
4108 continue;
4109 }
4110 for (size_t profile_index = 0;
4111 profile_index < mHwModules[module_index]->mInputProfiles.size();
4112 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004113 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004114 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004115 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004116 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004117 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004118 }
4119 }
4120 }
4121 } // end disconnect
4122
4123 return NO_ERROR;
4124}
4125
4126
Eric Laurente0720872014-03-11 09:30:41 -07004127void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004128{
4129 ALOGV("closeOutput(%d)", output);
4130
Eric Laurentc75307b2015-03-17 15:29:32 -07004131 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004132 if (outputDesc == NULL) {
4133 ALOGW("closeOutput() unknown output %d", output);
4134 return;
4135 }
François Gaffie036e1e92015-03-19 10:16:24 +01004136 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004137
Eric Laurente552edb2014-03-10 17:42:56 -07004138 // look for duplicated outputs connected to the output being removed.
4139 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004140 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004141 if (dupOutputDesc->isDuplicated() &&
4142 (dupOutputDesc->mOutput1 == outputDesc ||
4143 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004144 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004145 if (dupOutputDesc->mOutput1 == outputDesc) {
4146 outputDesc2 = dupOutputDesc->mOutput2;
4147 } else {
4148 outputDesc2 = dupOutputDesc->mOutput1;
4149 }
4150 // As all active tracks on duplicated output will be deleted,
4151 // and as they were also referenced on the other output, the reference
4152 // count for their stream type must be adjusted accordingly on
4153 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004154 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004155 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004156 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004157 }
4158 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4159 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4160
4161 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004162 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004163 }
4164 }
4165
Eric Laurent05b90f82014-08-27 15:32:29 -07004166 nextAudioPortGeneration();
4167
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004168 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004169 if (index >= 0) {
4170 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004171 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004172 mAudioPatches.removeItemsAt(index);
4173 mpClientInterface->onAudioPatchListUpdate();
4174 }
4175
Eric Laurente552edb2014-03-10 17:42:56 -07004176 AudioParameter param;
4177 param.add(String8("closing"), String8("true"));
4178 mpClientInterface->setParameters(output, param.toString());
4179
4180 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004181 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004182 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004183}
4184
4185void AudioPolicyManager::closeInput(audio_io_handle_t input)
4186{
4187 ALOGV("closeInput(%d)", input);
4188
4189 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4190 if (inputDesc == NULL) {
4191 ALOGW("closeInput() unknown input %d", input);
4192 return;
4193 }
4194
Eric Laurent6a94d692014-05-20 11:18:06 -07004195 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004196
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004197 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004198 if (index >= 0) {
4199 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004200 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004201 mAudioPatches.removeItemsAt(index);
4202 mpClientInterface->onAudioPatchListUpdate();
4203 }
4204
4205 mpClientInterface->closeInput(input);
4206 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004207}
4208
Eric Laurentc75307b2015-03-17 15:29:32 -07004209SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4210 audio_devices_t device,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004211 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004212{
4213 SortedVector<audio_io_handle_t> outputs;
4214
4215 ALOGVV("getOutputsForDevice() device %04x", device);
4216 for (size_t i = 0; i < openOutputs.size(); i++) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -08004217 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004218 i, openOutputs.valueAt(i)->isDuplicated(),
4219 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004220 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4221 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4222 outputs.add(openOutputs.keyAt(i));
4223 }
4224 }
4225 return outputs;
4226}
4227
Eric Laurente0720872014-03-11 09:30:41 -07004228bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004229 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004230{
4231 if (outputs1.size() != outputs2.size()) {
4232 return false;
4233 }
4234 for (size_t i = 0; i < outputs1.size(); i++) {
4235 if (outputs1[i] != outputs2[i]) {
4236 return false;
4237 }
4238 }
4239 return true;
4240}
4241
Eric Laurente0720872014-03-11 09:30:41 -07004242void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004243{
4244 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4245 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4246 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4247 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4248
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004249 // also take into account external policy-related changes: add all outputs which are
4250 // associated with policies in the "before" and "after" output vectors
4251 ALOGVV("checkOutputForStrategy(): policy related outputs");
4252 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004253 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004254 if (desc != 0 && desc->mPolicyMix != NULL) {
4255 srcOutputs.add(desc->mIoHandle);
4256 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4257 }
4258 }
4259 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004260 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004261 if (desc != 0 && desc->mPolicyMix != NULL) {
4262 dstOutputs.add(desc->mIoHandle);
4263 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4264 }
4265 }
4266
Eric Laurente552edb2014-03-10 17:42:56 -07004267 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4268 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4269 strategy, srcOutputs[0], dstOutputs[0]);
4270 // mute strategy while moving tracks from one output to another
4271 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004273 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004274 setStrategyMute(strategy, true, desc);
4275 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004276 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004277 sp<AudioSourceDescriptor> source =
4278 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4279 if (source != 0){
4280 connectAudioSource(source);
4281 }
Eric Laurente552edb2014-03-10 17:42:56 -07004282 }
4283
4284 // Move effects associated to this strategy from previous output to new output
4285 if (strategy == STRATEGY_MEDIA) {
4286 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4287 SortedVector<audio_io_handle_t> moved;
4288 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004289 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4290 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4291 effectDesc->mIo != fxOutput) {
4292 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004293 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4294 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004295 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004296 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004297 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004298 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004299 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004300 }
4301 }
4302 }
4303 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004304 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004305 if (getStrategy((audio_stream_type_t)i) == strategy) {
4306 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004307 }
4308 }
4309 }
4310}
4311
Eric Laurente0720872014-03-11 09:30:41 -07004312void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004313{
François Gaffie2110e042015-03-24 08:41:51 +01004314 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004315 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004316 checkOutputForStrategy(STRATEGY_PHONE);
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_SONIFICATION);
4320 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004321 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004322 checkOutputForStrategy(STRATEGY_MEDIA);
4323 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004324 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004325}
4326
Eric Laurente0720872014-03-11 09:30:41 -07004327void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004328{
François Gaffie53615e22015-03-19 09:24:12 +01004329 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004330 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004331 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004332 return;
4333 }
4334
Eric Laurent3a4311c2014-03-17 12:00:47 -07004335 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004336 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4337 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4338 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004339 // suspend A2DP output if:
4340 // (NOT already suspended) &&
4341 // ((SCO device is connected &&
4342 // (forced usage for communication || for record is SCO))) ||
4343 // (phone state is ringing || in call)
4344 //
4345 // restore A2DP output if:
4346 // (Already suspended) &&
4347 // ((SCO device is NOT connected ||
4348 // (forced usage NOT for communication && NOT for record is SCO))) &&
4349 // (phone state is NOT ringing && NOT in call)
4350 //
4351 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004352 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004353 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4354 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4355 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4356 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004357
4358 mpClientInterface->restoreOutput(a2dpOutput);
4359 mA2dpSuspended = false;
4360 }
4361 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004362 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004363 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4364 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4365 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4366 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004367
4368 mpClientInterface->suspendOutput(a2dpOutput);
4369 mA2dpSuspended = true;
4370 }
4371 }
4372}
4373
Eric Laurentc75307b2015-03-17 15:29:32 -07004374audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4375 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004376{
4377 audio_devices_t device = AUDIO_DEVICE_NONE;
4378
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004379 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004380 if (index >= 0) {
4381 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4382 if (patchDesc->mUid != mUidCached) {
4383 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004384 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004385 return outputDesc->device();
4386 }
4387 }
4388
Eric Laurente552edb2014-03-10 17:42:56 -07004389 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004390 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004391 // use device for strategy enforced audible
4392 // 2: we are in call or the strategy phone is active on the output:
4393 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004394 // 3: the strategy for enforced audible is active but not enforced on the output:
4395 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004396 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004397 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004398 // 5: the strategy accessibility is active on the output:
4399 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004400 // 6: the strategy "respectful" sonification is active on the output:
4401 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004402 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004403 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004404 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004405 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004406 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004407 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004408 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004409 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004410 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4411 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004412 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004413 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004414 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004415 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004416 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004417 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004418 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4419 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004420 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004421 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004422 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004423 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004424 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004425 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004426 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004427 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004428 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004429 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004430 }
4431
Eric Laurent1c333e22014-05-20 10:48:17 -07004432 ALOGV("getNewOutputDevice() selected device %x", device);
4433 return device;
4434}
4435
Eric Laurent232f26f2016-02-17 18:06:27 -08004436audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
Eric Laurent1c333e22014-05-20 10:48:17 -07004437{
Eric Laurent232f26f2016-02-17 18:06:27 -08004438 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004439
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004440 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 if (index >= 0) {
4442 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4443 if (patchDesc->mUid != mUidCached) {
4444 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004445 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 return inputDesc->mDevice;
4447 }
4448 }
4449
Eric Laurent232f26f2016-02-17 18:06:27 -08004450 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004451
Eric Laurente552edb2014-03-10 17:42:56 -07004452 return device;
4453}
4454
Eric Laurent794fde22016-03-11 09:50:45 -08004455bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4456 audio_stream_type_t stream2) {
4457 return ((stream1 == stream2) ||
4458 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4459 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004460}
4461
Eric Laurente0720872014-03-11 09:30:41 -07004462uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004463 return (uint32_t)getStrategy(stream);
4464}
4465
Eric Laurente0720872014-03-11 09:30:41 -07004466audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004467 // By checking the range of stream before calling getStrategy, we avoid
4468 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4469 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004470 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004471 return AUDIO_DEVICE_NONE;
4472 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004473 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004474 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4475 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004476 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004477 }
Eric Laurent794fde22016-03-11 09:50:45 -08004478 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004479 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004480 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004481 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4482 for (size_t i = 0; i < outputs.size(); i++) {
4483 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004484 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004485 curDevices |= outputDesc->device();
4486 }
4487 }
4488 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004489 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004490
4491 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4492 and doesn't really need to.*/
4493 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4494 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4495 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4496 }
Eric Laurente552edb2014-03-10 17:42:56 -07004497 return devices;
4498}
4499
François Gaffie2110e042015-03-24 08:41:51 +01004500routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4501{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004502 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004503 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004504}
4505
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004506uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4507 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004508 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4509 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4510 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004511 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4512 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4513 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004514 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004515 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004516}
4517
Eric Laurente0720872014-03-11 09:30:41 -07004518void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004519 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004520 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004521 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4522 updateDevicesAndOutputs();
4523 break;
4524 default:
4525 break;
4526 }
4527}
4528
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004529uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004530
4531 // skip beacon mute management if a dedicated TTS output is available
4532 if (mTtsOutputAvailable) {
4533 return 0;
4534 }
4535
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004536 switch(event) {
4537 case STARTING_OUTPUT:
4538 mBeaconMuteRefCount++;
4539 break;
4540 case STOPPING_OUTPUT:
4541 if (mBeaconMuteRefCount > 0) {
4542 mBeaconMuteRefCount--;
4543 }
4544 break;
4545 case STARTING_BEACON:
4546 mBeaconPlayingRefCount++;
4547 break;
4548 case STOPPING_BEACON:
4549 if (mBeaconPlayingRefCount > 0) {
4550 mBeaconPlayingRefCount--;
4551 }
4552 break;
4553 }
4554
4555 if (mBeaconMuteRefCount > 0) {
4556 // any playback causes beacon to be muted
4557 return setBeaconMute(true);
4558 } else {
4559 // no other playback: unmute when beacon starts playing, mute when it stops
4560 return setBeaconMute(mBeaconPlayingRefCount == 0);
4561 }
4562}
4563
4564uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4565 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4566 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4567 // keep track of muted state to avoid repeating mute/unmute operations
4568 if (mBeaconMuted != mute) {
4569 // mute/unmute AUDIO_STREAM_TTS on all outputs
4570 ALOGV("\t muting %d", mute);
4571 uint32_t maxLatency = 0;
4572 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004573 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004574 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004575 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004576 0 /*delay*/, AUDIO_DEVICE_NONE);
4577 const uint32_t latency = desc->latency() * 2;
4578 if (latency > maxLatency) {
4579 maxLatency = latency;
4580 }
4581 }
4582 mBeaconMuted = mute;
4583 return maxLatency;
4584 }
4585 return 0;
4586}
4587
Eric Laurente0720872014-03-11 09:30:41 -07004588audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004589 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004590{
Paul McLeanaa981192015-03-21 09:55:15 -07004591 // Routing
4592 // see if we have an explicit route
4593 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4594 // (getStrategy(stream)).
4595 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4596 // and activity count is non-zero
4597 // the device = the device from the descriptor in the RouteMap, and exit.
4598 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4599 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004600 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4601 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004602 return route->mDeviceDescriptor->type();
4603 }
4604 }
4605
Eric Laurente552edb2014-03-10 17:42:56 -07004606 if (fromCache) {
4607 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4608 strategy, mDeviceForStrategy[strategy]);
4609 return mDeviceForStrategy[strategy];
4610 }
François Gaffie2110e042015-03-24 08:41:51 +01004611 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004612}
4613
Eric Laurente0720872014-03-11 09:30:41 -07004614void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004615{
4616 for (int i = 0; i < NUM_STRATEGIES; i++) {
4617 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4618 }
4619 mPreviousOutputs = mOutputs;
4620}
4621
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004622uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004623 audio_devices_t prevDevice,
4624 uint32_t delayMs)
4625{
4626 // mute/unmute strategies using an incompatible device combination
4627 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4628 // if unmuting, unmute only after the specified delay
4629 if (outputDesc->isDuplicated()) {
4630 return 0;
4631 }
4632
4633 uint32_t muteWaitMs = 0;
4634 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004635 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004636
4637 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4638 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004639 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004640 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4641 bool doMute = false;
4642
4643 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4644 doMute = true;
4645 outputDesc->mStrategyMutedByDevice[i] = true;
4646 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4647 doMute = true;
4648 outputDesc->mStrategyMutedByDevice[i] = false;
4649 }
Eric Laurent99401132014-05-07 19:48:15 -07004650 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004651 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004652 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004653 // skip output if it does not share any device with current output
4654 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4655 == AUDIO_DEVICE_NONE) {
4656 continue;
4657 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -08004658 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004659 mute ? "muting" : "unmuting", i, curDevice);
4660 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004661 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004662 if (mute) {
4663 // FIXME: should not need to double latency if volume could be applied
4664 // immediately by the audioflinger mixer. We must account for the delay
4665 // between now and the next time the audioflinger thread for this output
4666 // will process a buffer (which corresponds to one buffer size,
4667 // usually 1/2 or 1/4 of the latency).
4668 if (muteWaitMs < desc->latency() * 2) {
4669 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004670 }
4671 }
4672 }
4673 }
4674 }
4675 }
4676
Eric Laurent99401132014-05-07 19:48:15 -07004677 // temporary mute output if device selection changes to avoid volume bursts due to
4678 // different per device volumes
4679 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004680 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4681 // temporary mute duration is conservatively set to 4 times the reported latency
4682 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4683 if (muteWaitMs < tempMuteWaitMs) {
4684 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004685 }
Eric Laurentdc462862016-07-19 12:29:53 -07004686
Eric Laurent99401132014-05-07 19:48:15 -07004687 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004688 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004689 // make sure that we do not start the temporary mute period too early in case of
4690 // delayed device change
4691 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004692 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004693 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004694 }
4695 }
4696 }
4697
Eric Laurente552edb2014-03-10 17:42:56 -07004698 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4699 if (muteWaitMs > delayMs) {
4700 muteWaitMs -= delayMs;
4701 usleep(muteWaitMs * 1000);
4702 return muteWaitMs;
4703 }
4704 return 0;
4705}
4706
Eric Laurentc75307b2015-03-17 15:29:32 -07004707uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004708 audio_devices_t device,
4709 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004711 audio_patch_handle_t *patchHandle,
4712 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004713{
Eric Laurentc75307b2015-03-17 15:29:32 -07004714 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004715 AudioParameter param;
4716 uint32_t muteWaitMs;
4717
4718 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004719 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4720 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004721 return muteWaitMs;
4722 }
4723 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4724 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004725 if ((device != AUDIO_DEVICE_NONE) &&
4726 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004727 return 0;
4728 }
4729
4730 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004731 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004732
4733 audio_devices_t prevDevice = outputDesc->mDevice;
4734
Paul McLeanaa981192015-03-21 09:55:15 -07004735 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004736
4737 if (device != AUDIO_DEVICE_NONE) {
4738 outputDesc->mDevice = device;
4739 }
4740 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4741
4742 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004743 // the requested device is AUDIO_DEVICE_NONE
4744 // OR the requested device is the same as current device
4745 // AND force is not specified
4746 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004747 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004748 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4749 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004750 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004751 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004752 return muteWaitMs;
4753 }
4754
4755 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004756
Eric Laurente552edb2014-03-10 17:42:56 -07004757 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004758 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004759 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004760 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004761 DeviceVector deviceList;
4762 if ((address == NULL) || (strlen(address) == 0)) {
4763 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4764 } else {
4765 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4766 }
4767
Eric Laurent1c333e22014-05-20 10:48:17 -07004768 if (!deviceList.isEmpty()) {
4769 struct audio_patch patch;
4770 outputDesc->toAudioPortConfig(&patch.sources[0]);
4771 patch.num_sources = 1;
4772 patch.num_sinks = 0;
4773 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4774 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004775 patch.num_sinks++;
4776 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004777 ssize_t index;
4778 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4779 index = mAudioPatches.indexOfKey(*patchHandle);
4780 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004781 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004782 }
4783 sp< AudioPatch> patchDesc;
4784 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4785 if (index >= 0) {
4786 patchDesc = mAudioPatches.valueAt(index);
4787 afPatchHandle = patchDesc->mAfPatchHandle;
4788 }
4789
Eric Laurent1c333e22014-05-20 10:48:17 -07004790 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004791 &afPatchHandle,
4792 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004793 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4794 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004795 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004798 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 addAudioPatch(patchDesc->mHandle, patchDesc);
4800 } else {
4801 patchDesc->mPatch = patch;
4802 }
4803 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 if (patchHandle) {
4805 *patchHandle = patchDesc->mHandle;
4806 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004807 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004809 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004810 }
4811 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004812
4813 // inform all input as well
4814 for (size_t i = 0; i < mInputs.size(); i++) {
4815 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004816 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004817 AudioParameter inputCmd = AudioParameter();
4818 ALOGV("%s: inform input %d of device:%d", __func__,
4819 inputDescriptor->mIoHandle, device);
4820 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4821 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4822 inputCmd.toString(),
4823 delayMs);
4824 }
4825 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004826 }
Eric Laurente552edb2014-03-10 17:42:56 -07004827
4828 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004829 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004830
4831 return muteWaitMs;
4832}
4833
Eric Laurentc75307b2015-03-17 15:29:32 -07004834status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004835 int delayMs,
4836 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004837{
Eric Laurent6a94d692014-05-20 11:18:06 -07004838 ssize_t index;
4839 if (patchHandle) {
4840 index = mAudioPatches.indexOfKey(*patchHandle);
4841 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004842 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004843 }
4844 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004845 return INVALID_OPERATION;
4846 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004847 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4848 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004849 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004850 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 removeAudioPatch(patchDesc->mHandle);
4852 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004853 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004854 return status;
4855}
4856
4857status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4858 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004859 bool force,
4860 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004861{
4862 status_t status = NO_ERROR;
4863
Eric Laurent1f2f2232014-06-02 12:01:23 -07004864 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004865 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4866 inputDesc->mDevice = device;
4867
4868 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4869 if (!deviceList.isEmpty()) {
4870 struct audio_patch patch;
4871 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004872 // AUDIO_SOURCE_HOTWORD is for internal use only:
4873 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004874 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004875 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004876 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4877 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004878 patch.num_sinks = 1;
4879 //only one input device for now
4880 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004881 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 ssize_t index;
4883 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4884 index = mAudioPatches.indexOfKey(*patchHandle);
4885 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004886 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 }
4888 sp< AudioPatch> patchDesc;
4889 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4890 if (index >= 0) {
4891 patchDesc = mAudioPatches.valueAt(index);
4892 afPatchHandle = patchDesc->mAfPatchHandle;
4893 }
4894
Eric Laurent1c333e22014-05-20 10:48:17 -07004895 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004897 0);
4898 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004901 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004902 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004903 addAudioPatch(patchDesc->mHandle, patchDesc);
4904 } else {
4905 patchDesc->mPatch = patch;
4906 }
4907 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 if (patchHandle) {
4909 *patchHandle = patchDesc->mHandle;
4910 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004911 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004913 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004914 }
4915 }
4916 }
4917 return status;
4918}
4919
Eric Laurent6a94d692014-05-20 11:18:06 -07004920status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4921 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004922{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004923 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004924 ssize_t index;
4925 if (patchHandle) {
4926 index = mAudioPatches.indexOfKey(*patchHandle);
4927 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004928 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 }
4930 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004931 return INVALID_OPERATION;
4932 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4934 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004935 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004936 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 removeAudioPatch(patchDesc->mHandle);
4938 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004939 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004940 return status;
4941}
4942
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004943sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004944 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004945 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004946 audio_format_t& format,
4947 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004948 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004949{
4950 // Choose an input profile based on the requested capture parameters: select the first available
4951 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004952 //
4953 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4954 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004955
4956 for (size_t i = 0; i < mHwModules.size(); i++)
4957 {
4958 if (mHwModules[i]->mHandle == 0) {
4959 continue;
4960 }
4961 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4962 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004963 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004964 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004965 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004966 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004967 format,
4968 &format /*updatedFormat*/,
4969 channelMask,
4970 &channelMask /*updatedChannelMask*/,
4971 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004972
Eric Laurente552edb2014-03-10 17:42:56 -07004973 return profile;
4974 }
4975 }
4976 }
4977 return NULL;
4978}
4979
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004980
4981audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004982 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004983{
François Gaffie036e1e92015-03-19 10:16:24 +01004984 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4985 audio_devices_t selectedDeviceFromMix =
4986 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004987
François Gaffie036e1e92015-03-19 10:16:24 +01004988 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4989 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004990 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004991 return getDeviceForInputSource(inputSource);
4992}
4993
4994audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4995{
Paul McLean466dc8e2015-04-17 13:15:36 -06004996 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4997 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004998 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004999 return route->mDeviceDescriptor->type();
5000 }
5001 }
5002
5003 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005004}
5005
Eric Laurente0720872014-03-11 09:30:41 -07005006float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005007 int index,
5008 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005009{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005010 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005011
5012 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5013 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5014 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5015 // the ringtone volume
5016 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5017 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5018 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5019 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5020 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5021 }
5022
Eric Laurente552edb2014-03-10 17:42:56 -07005023 // if a headset is connected, apply the following rules to ring tones and notifications
5024 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005025 // - always attenuate notifications volume by 6dB
5026 // - attenuate ring tones volume by 6dB unless music is not playing and
5027 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005028 // - if music is playing, always limit the volume to current music volume,
5029 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005030 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005031 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5032 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5033 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5034 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5035 ((stream_strategy == STRATEGY_SONIFICATION)
5036 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005037 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005038 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005039 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005040 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005041 // when the phone is ringing we must consider that music could have been paused just before
5042 // by the music application and behave as if music was active if the last music track was
5043 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005044 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005045 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005046 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005047 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005048 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005049 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5050 musicDevice),
5051 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005052 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5053 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005054 if (volumeDB > minVolDB) {
5055 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005056 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005057 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005058 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5059 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5060 // on A2DP, also ensure notification volume is not too low compared to media when
5061 // intended to be played
5062 if ((volumeDB > -96.0f) &&
5063 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5064 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5065 stream, device,
5066 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5067 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5068 }
5069 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005070 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5071 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005072 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005073 }
5074 }
5075
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005076 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005077}
5078
Eric Laurente0720872014-03-11 09:30:41 -07005079status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005080 int index,
5081 const sp<AudioOutputDescriptor>& outputDesc,
5082 audio_devices_t device,
5083 int delayMs,
5084 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005085{
Eric Laurente552edb2014-03-10 17:42:56 -07005086 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005087 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005088 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005089 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005090 return NO_ERROR;
5091 }
François Gaffie2110e042015-03-24 08:41:51 +01005092 audio_policy_forced_cfg_t forceUseForComm =
5093 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005094 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005095 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5096 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005097 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005098 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005099 return INVALID_OPERATION;
5100 }
5101
Eric Laurentc75307b2015-03-17 15:29:32 -07005102 if (device == AUDIO_DEVICE_NONE) {
5103 device = outputDesc->device();
5104 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005105
Eric Laurentffbc80f2015-03-18 18:30:19 -07005106 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005107 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005108 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005109 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005110
Eric Laurentffbc80f2015-03-18 18:30:19 -07005111 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005112
Eric Laurent3b73df72014-03-11 09:06:29 -07005113 if (stream == AUDIO_STREAM_VOICE_CALL ||
5114 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005115 float voiceVolume;
5116 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005117 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005118 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005119 } else {
5120 voiceVolume = 1.0;
5121 }
5122
Eric Laurent18fba842016-03-31 14:41:26 -07005123 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005124 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5125 mLastVoiceVolume = voiceVolume;
5126 }
5127 }
5128
5129 return NO_ERROR;
5130}
5131
Eric Laurentc75307b2015-03-17 15:29:32 -07005132void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5133 audio_devices_t device,
5134 int delayMs,
5135 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005136{
Eric Laurentc75307b2015-03-17 15:29:32 -07005137 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005138
Eric Laurent794fde22016-03-11 09:50:45 -08005139 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005140 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005141 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005142 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005143 device,
5144 delayMs,
5145 force);
5146 }
5147}
5148
Eric Laurente0720872014-03-11 09:30:41 -07005149void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005150 bool on,
5151 const sp<AudioOutputDescriptor>& outputDesc,
5152 int delayMs,
5153 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005154{
Eric Laurent72249d52015-06-08 11:12:15 -07005155 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5156 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005157 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005158 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005159 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005160 }
5161 }
5162}
5163
Eric Laurente0720872014-03-11 09:30:41 -07005164void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005165 bool on,
5166 const sp<AudioOutputDescriptor>& outputDesc,
5167 int delayMs,
5168 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005169{
Eric Laurente552edb2014-03-10 17:42:56 -07005170 if (device == AUDIO_DEVICE_NONE) {
5171 device = outputDesc->device();
5172 }
5173
Eric Laurentc75307b2015-03-17 15:29:32 -07005174 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5175 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005176
5177 if (on) {
5178 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005179 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005180 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005181 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005182 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005183 }
5184 }
5185 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5186 outputDesc->mMuteCount[stream]++;
5187 } else {
5188 if (outputDesc->mMuteCount[stream] == 0) {
5189 ALOGV("setStreamMute() unmuting non muted stream!");
5190 return;
5191 }
5192 if (--outputDesc->mMuteCount[stream] == 0) {
5193 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005194 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005196 device,
5197 delayMs);
5198 }
5199 }
5200}
5201
Eric Laurente0720872014-03-11 09:30:41 -07005202void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005203 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005204{
Eric Laurent87ffa392015-05-22 10:32:38 -07005205 if(!hasPrimaryOutput()) {
5206 return;
5207 }
5208
Eric Laurente552edb2014-03-10 17:42:56 -07005209 // if the stream pertains to sonification strategy and we are in call we must
5210 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5211 // in the device used for phone strategy and play the tone if the selected device does not
5212 // interfere with the device used for phone strategy
5213 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5214 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005215 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005216 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5217 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005218 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005219 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5220 stream, starting, outputDesc->mDevice, stateChange);
5221 if (outputDesc->mRefCount[stream]) {
5222 int muteCount = 1;
5223 if (stateChange) {
5224 muteCount = outputDesc->mRefCount[stream];
5225 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005226 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005227 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5228 for (int i = 0; i < muteCount; i++) {
5229 setStreamMute(stream, starting, mPrimaryOutput);
5230 }
5231 } else {
5232 ALOGV("handleIncallSonification() high visibility");
5233 if (outputDesc->device() &
5234 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5235 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5236 for (int i = 0; i < muteCount; i++) {
5237 setStreamMute(stream, starting, mPrimaryOutput);
5238 }
5239 }
5240 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005241 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5242 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005243 } else {
5244 mpClientInterface->stopTone();
5245 }
5246 }
5247 }
5248 }
5249}
5250
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005251audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5252{
5253 // flags to stream type mapping
5254 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5255 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5256 }
5257 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5258 return AUDIO_STREAM_BLUETOOTH_SCO;
5259 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005260 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5261 return AUDIO_STREAM_TTS;
5262 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005263
5264 // usage to stream type mapping
5265 switch (attr->usage) {
5266 case AUDIO_USAGE_MEDIA:
5267 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005268 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5269 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005270 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5271 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005272 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5273 return AUDIO_STREAM_SYSTEM;
5274 case AUDIO_USAGE_VOICE_COMMUNICATION:
5275 return AUDIO_STREAM_VOICE_CALL;
5276
5277 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5278 return AUDIO_STREAM_DTMF;
5279
5280 case AUDIO_USAGE_ALARM:
5281 return AUDIO_STREAM_ALARM;
5282 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5283 return AUDIO_STREAM_RING;
5284
5285 case AUDIO_USAGE_NOTIFICATION:
5286 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5287 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5288 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5289 case AUDIO_USAGE_NOTIFICATION_EVENT:
5290 return AUDIO_STREAM_NOTIFICATION;
5291
5292 case AUDIO_USAGE_UNKNOWN:
5293 default:
5294 return AUDIO_STREAM_MUSIC;
5295 }
5296}
Eric Laurente83b55d2014-11-14 10:06:21 -08005297
François Gaffie53615e22015-03-19 09:24:12 +01005298bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5299{
Eric Laurente83b55d2014-11-14 10:06:21 -08005300 // has flags that map to a strategy?
5301 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5302 return true;
5303 }
5304
5305 // has known usage?
5306 switch (paa->usage) {
5307 case AUDIO_USAGE_UNKNOWN:
5308 case AUDIO_USAGE_MEDIA:
5309 case AUDIO_USAGE_VOICE_COMMUNICATION:
5310 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5311 case AUDIO_USAGE_ALARM:
5312 case AUDIO_USAGE_NOTIFICATION:
5313 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5314 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5315 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5316 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5317 case AUDIO_USAGE_NOTIFICATION_EVENT:
5318 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5319 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5320 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5321 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005322 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005323 break;
5324 default:
5325 return false;
5326 }
5327 return true;
5328}
5329
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07005330bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005331 routing_strategy strategy, uint32_t inPastMs,
5332 nsecs_t sysTime) const
5333{
5334 if ((sysTime == 0) && (inPastMs != 0)) {
5335 sysTime = systemTime();
5336 }
Eric Laurent794fde22016-03-11 09:50:45 -08005337 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005338 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5339 (NUM_STRATEGIES == strategy)) &&
5340 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5341 return true;
5342 }
5343 }
5344 return false;
5345}
5346
François Gaffie2110e042015-03-24 08:41:51 +01005347audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5348{
5349 return mEngine->getForceUse(usage);
5350}
5351
5352bool AudioPolicyManager::isInCall()
5353{
5354 return isStateInCall(mEngine->getPhoneState());
5355}
5356
5357bool AudioPolicyManager::isStateInCall(int state)
5358{
5359 return is_state_in_call(state);
5360}
5361
Eric Laurentd60560a2015-04-10 11:31:20 -07005362void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5363{
5364 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5365 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5366 if (sourceDesc->mDevice->equals(deviceDesc)) {
5367 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5368 stopAudioSource(sourceDesc->getHandle());
5369 }
5370 }
5371
5372 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5373 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5374 bool release = false;
5375 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5376 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5377 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5378 source->ext.device.type == deviceDesc->type()) {
5379 release = true;
5380 }
5381 }
5382 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5383 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5384 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5385 sink->ext.device.type == deviceDesc->type()) {
5386 release = true;
5387 }
5388 }
5389 if (release) {
5390 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5391 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5392 }
5393 }
5394}
5395
Phil Burk09bc4612016-02-24 15:58:15 -08005396// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005397void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5398 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005399 // TODO Set this based on Config properties.
5400 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005401
5402 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5403 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005404 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005405
5406 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005407 bool supportsAC3 = false;
5408 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005409 bool supportsIEC61937 = false;
5410 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5411 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005412 switch (format) {
5413 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005414 supportsAC3 = true;
5415 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005416 case AUDIO_FORMAT_E_AC3:
5417 case AUDIO_FORMAT_DTS:
5418 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005419 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005420 break;
5421 case AUDIO_FORMAT_IEC61937:
5422 supportsIEC61937 = true;
5423 break;
5424 default:
5425 break;
5426 }
5427 }
Phil Burk09bc4612016-02-24 15:58:15 -08005428
5429 // Modify formats based on surround preferences.
5430 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005431 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5432 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5433 // Remove surround sound related formats.
5434 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5435 audio_format_t format = formats[formatIndex];
5436 switch(format) {
5437 case AUDIO_FORMAT_AC3:
5438 case AUDIO_FORMAT_E_AC3:
5439 case AUDIO_FORMAT_DTS:
5440 case AUDIO_FORMAT_DTS_HD:
5441 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005442 formats.removeAt(formatIndex);
5443 break;
5444 default:
5445 formatIndex++; // keep it
5446 break;
5447 }
Phil Burk09bc4612016-02-24 15:58:15 -08005448 }
Phil Burk07ac1142016-03-25 13:39:29 -07005449 supportsAC3 = false;
5450 supportsOtherSurround = false;
5451 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005452 }
Phil Burk07ac1142016-03-25 13:39:29 -07005453 } else { // AUTO or ALWAYS
5454 // Most TVs support AC3 even if they do not report it in the EDID.
5455 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5456 && !supportsAC3) {
5457 formats.add(AUDIO_FORMAT_AC3);
5458 supportsAC3 = true;
5459 }
5460
5461 // If ALWAYS, add support for raw surround formats if all are missing.
5462 // This assumes that if any of these formats are reported by the HAL
5463 // then the report is valid and should not be modified.
5464 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5465 && !supportsOtherSurround) {
5466 formats.add(AUDIO_FORMAT_E_AC3);
5467 formats.add(AUDIO_FORMAT_DTS);
5468 formats.add(AUDIO_FORMAT_DTS_HD);
5469 supportsOtherSurround = true;
5470 }
5471
5472 // Add support for IEC61937 if any raw surround supported.
5473 // The HAL could do this but add it here, just in case.
5474 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5475 formats.add(AUDIO_FORMAT_IEC61937);
5476 supportsIEC61937 = true;
5477 }
Phil Burk09bc4612016-02-24 15:58:15 -08005478 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005479}
5480
5481// Modify the list of channel masks supported.
5482void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5483 ChannelsVector &channelMasks = *channelMasksPtr;
5484 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5485 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5486
5487 // If NEVER, then remove support for channelMasks > stereo.
5488 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5489 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5490 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5491 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5492 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5493 channelMasks.removeAt(maskIndex);
5494 } else {
5495 maskIndex++;
5496 }
5497 }
5498 // If ALWAYS, then make sure we at least support 5.1
5499 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5500 bool supports5dot1 = false;
5501 // Are there any channel masks that can be considered "surround"?
5502 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5503 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5504 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5505 supports5dot1 = true;
5506 break;
5507 }
5508 }
5509 // If not then add 5.1 support.
5510 if (!supports5dot1) {
5511 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5512 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5513 }
Phil Burk09bc4612016-02-24 15:58:15 -08005514 }
5515}
5516
Phil Burk00eeb322016-03-31 12:41:00 -07005517void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5518 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005519 AudioProfileVector &profiles)
5520{
5521 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005522
François Gaffie112b0af2015-11-19 16:13:25 +01005523 // Format MUST be checked first to update the list of AudioProfile
5524 if (profiles.hasDynamicFormat()) {
5525 reply = mpClientInterface->getParameters(ioHandle,
5526 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk0709b0a2016-03-31 12:54:57 -07005527 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005528 AudioParameter repliedParameters(reply);
5529 if (repliedParameters.get(
5530 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005531 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5532 return;
5533 }
Phil Burk09bc4612016-02-24 15:58:15 -08005534 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005535 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005536 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005537 }
Phil Burk09bc4612016-02-24 15:58:15 -08005538 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005539 }
5540 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5541
Eric Laurent20eb3a42016-01-26 18:39:17 -08005542 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005543 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005544 ChannelsVector channelMasks;
5545 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005546 AudioParameter requestedParameters;
5547 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5548
5549 if (profiles.hasDynamicRateFor(format)) {
5550 reply = mpClientInterface->getParameters(ioHandle,
5551 requestedParameters.toString() + ";" +
5552 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5553 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005554 AudioParameter repliedParameters(reply);
5555 if (repliedParameters.get(
5556 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5557 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005558 }
5559 }
5560 if (profiles.hasDynamicChannelsFor(format)) {
5561 reply = mpClientInterface->getParameters(ioHandle,
5562 requestedParameters.toString() + ";" +
5563 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5564 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005565 AudioParameter repliedParameters(reply);
5566 if (repliedParameters.get(
5567 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5568 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005569 if (device == AUDIO_DEVICE_OUT_HDMI) {
5570 filterSurroundChannelMasks(&channelMasks);
5571 }
François Gaffie112b0af2015-11-19 16:13:25 +01005572 }
5573 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005574 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005575 }
5576}
Eric Laurentd60560a2015-04-10 11:31:20 -07005577
Eric Laurente552edb2014-03-10 17:42:56 -07005578}; // namespace android