blob: 43c1b0adc1a8c6a700444db421b52a2ca1adb903 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070036#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080037#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070038#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070039#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070040#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurentdc462862016-07-19 12:29:53 -070052//FIXME: workaround for truncated touch sounds
53// to be removed when the problem is handled by system UI
54#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070055// ----------------------------------------------------------------------------
56// AudioPolicyInterface implementation
57// ----------------------------------------------------------------------------
58
Eric Laurente0720872014-03-11 09:30:41 -070059status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080060 audio_policy_dev_state_t state,
61 const char *device_address,
62 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070063{
Paul McLeane743a472015-01-28 11:07:31 -080064 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080065}
66
François Gaffie44481e72016-04-20 07:49:57 +020067void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
68 audio_policy_dev_state_t state,
69 const String8 &device_address)
70{
71 AudioParameter param(device_address);
72 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070073 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020074 param.addInt(key, device);
75 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
76}
77
Eric Laurentc73ca6e2014-12-12 14:34:22 -080078status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080079 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080080 const char *device_address,
81 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080082{
Paul McLeane743a472015-01-28 11:07:31 -080083 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
84- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070085
86 // connect/disconnect only 1 device at a time
87 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
88
François Gaffie53615e22015-03-19 09:24:12 +010089 sp<DeviceDescriptor> devDesc =
90 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080091
Eric Laurente552edb2014-03-10 17:42:56 -070092 // handle output devices
93 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070094 SortedVector <audio_io_handle_t> outputs;
95
Eric Laurent3a4311c2014-03-17 12:00:47 -070096 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
97
Eric Laurente552edb2014-03-10 17:42:56 -070098 // save a copy of the opened output descriptors before any output is opened or closed
99 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
100 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700101 switch (state)
102 {
103 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800104 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700105 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700106 ALOGW("setDeviceConnectionState() device already connected: %x", device);
107 return INVALID_OPERATION;
108 }
109 ALOGV("setDeviceConnectionState() connecting device %x", device);
110
Eric Laurente552edb2014-03-10 17:42:56 -0700111 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 index = mAvailableOutputDevices.add(devDesc);
113 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100114 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700115 if (module == 0) {
116 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
117 device);
118 mAvailableOutputDevices.remove(devDesc);
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122 } else {
123 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 }
125
François Gaffie44481e72016-04-20 07:49:57 +0200126 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
127 // parameters on newly connected devices (instead of opening the outputs...)
128 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
129
Eric Laurenta1d525f2015-01-29 13:36:45 -0800130 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700131 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200132
133 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
134 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700135 return INVALID_OPERATION;
136 }
François Gaffie2110e042015-03-24 08:41:51 +0100137 // Propagate device availability to Engine
138 mEngine->setDeviceConnectionState(devDesc, state);
139
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700140 // outputs should never be empty here
141 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
142 "checkOutputsForDevice() returned no outputs but status OK");
143 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
144 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800145
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700148 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700150 ALOGW("setDeviceConnectionState() device not connected: %x", device);
151 return INVALID_OPERATION;
152 }
153
Paul McLean5c477aa2014-08-20 16:47:57 -0700154 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
155
Paul McLeane743a472015-01-28 11:07:31 -0800156 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200157 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700158
Eric Laurente552edb2014-03-10 17:42:56 -0700159 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700160 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100163
164 // Propagate device availability to Engine
165 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700166 } break;
167
168 default:
169 ALOGE("setDeviceConnectionState() invalid state: %x", state);
170 return BAD_VALUE;
171 }
172
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
174 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700175 checkA2dpSuspend();
176 checkOutputForAllStrategies();
177 // outputs must be closed after checkOutputForAllStrategies() is executed
178 if (!outputs.isEmpty()) {
179 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // close unused outputs after device disconnection or direct outputs that have been
182 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700183 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700184 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
185 (desc->mDirectOpenCount == 0))) {
186 closeOutput(outputs[i]);
187 }
188 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189 // check again after closing A2DP output to reset mA2dpSuspended if needed
190 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700191 }
192
193 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700194 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700195 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
196 updateCallRouting(newDevice);
197 }
Eric Laurente552edb2014-03-10 17:42:56 -0700198 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
200 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
201 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 // do not force device change on duplicated output because if device is 0, it will
203 // also force a device 0 for the two outputs it is duplicated to which may override
204 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700205 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100206 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700207 // always force when disconnecting (a non-duplicated device)
208 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700209 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700210 }
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
Eric Laurentd60560a2015-04-10 11:31:20 -0700213 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
214 cleanUpForDevice(devDesc);
215 }
216
Eric Laurent72aa32f2014-05-30 18:51:48 -0700217 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700218 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700219 } // end if is output device
220
Eric Laurente552edb2014-03-10 17:42:56 -0700221 // handle input devices
222 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700223 SortedVector <audio_io_handle_t> inputs;
224
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700226 switch (state)
227 {
228 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700231 ALOGW("setDeviceConnectionState() device already connected: %d", device);
232 return INVALID_OPERATION;
233 }
François Gaffie53615e22015-03-19 09:24:12 +0100234 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700235 if (module == NULL) {
236 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
237 device);
238 return INVALID_OPERATION;
239 }
François Gaffie44481e72016-04-20 07:49:57 +0200240
241 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
242 // parameters on newly connected devices (instead of opening the inputs...)
243 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
244
Paul McLean9080a4c2015-06-18 08:24:02 -0700245 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200246 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
247 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700248 return INVALID_OPERATION;
249 }
250
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 index = mAvailableInputDevices.add(devDesc);
252 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800253 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 } else {
255 return NO_MEMORY;
256 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800257
François Gaffie2110e042015-03-24 08:41:51 +0100258 // Propagate device availability to Engine
259 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700260 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700261
262 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700263 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700265 ALOGW("setDeviceConnectionState() device not connected: %d", device);
266 return INVALID_OPERATION;
267 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700268
269 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
270
271 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200272 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700273
Paul McLean9080a4c2015-06-18 08:24:02 -0700274 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700276
François Gaffie2110e042015-03-24 08:41:51 +0100277 // Propagate device availability to Engine
278 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700279 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurentd4692962014-05-05 18:13:44 -0700286 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700287 // As the input device list can impact the output device selection, update
288 // getDeviceForStrategy() cache
289 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700290
Eric Laurent87ffa392015-05-22 10:32:38 -0700291 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700292 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
293 updateCallRouting(newDevice);
294 }
295
Eric Laurentd60560a2015-04-10 11:31:20 -0700296 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
297 cleanUpForDevice(devDesc);
298 }
299
Eric Laurentb52c1522014-05-20 11:27:36 -0700300 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700301 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 ALOGW("setDeviceConnectionState() invalid device: %x", device);
305 return BAD_VALUE;
306}
307
Eric Laurente0720872014-03-11 09:30:41 -0700308audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100309 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700310{
Eric Laurent634b7142016-04-20 13:48:02 -0700311 sp<DeviceDescriptor> devDesc =
312 mHwModules.getDeviceDescriptor(device, device_address, "",
313 (strlen(device_address) != 0)/*matchAddress*/);
314
315 if (devDesc == 0) {
316 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
317 device, device_address);
318 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
319 }
François Gaffie53615e22015-03-19 09:24:12 +0100320
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 DeviceVector *deviceVector;
322
Eric Laurente552edb2014-03-10 17:42:56 -0700323 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700325 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 deviceVector = &mAvailableInputDevices;
327 } else {
328 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
329 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700330 }
Eric Laurent634b7142016-04-20 13:48:02 -0700331
332 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
333 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800334}
335
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800336status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
337 const char *device_address,
338 const char *device_name)
339{
340 status_t status;
341
342 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
343 device, device_address, device_name);
344
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
Andy Hunga76c7de2016-12-13 19:14:31 -0800385 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
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 Laurentfb66dd92016-01-28 18:32:03 -0800492 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
493 for (size_t i = 0; i < activeInputs.size(); i++) {
494 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
495 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
496 AudioSessionCollection activeSessions =
497 activeDesc->getAudioSessions(true /*activeOnly*/);
498 for (size_t j = 0; j < activeSessions.size(); j++) {
499 audio_session_t activeSession = activeSessions.keyAt(j);
500 stopInput(activeDesc->mIoHandle, activeSession);
501 releaseInput(activeDesc->mIoHandle, activeSession);
502 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700503 }
504 }
505
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700507 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700508 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
509 status);
510 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100511 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700512 mCallTxPatch->mAfPatchHandle = afPatchHandle;
513 mCallTxPatch->mUid = mUidCached;
514 }
515 }
Eric Laurentdc462862016-07-19 12:29:53 -0700516
517 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700518}
519
Eric Laurente0720872014-03-11 09:30:41 -0700520void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700521{
522 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100523 // store previous phone state for management of sonification strategy below
524 int oldState = mEngine->getPhoneState();
525
526 if (mEngine->setPhoneState(state) != NO_ERROR) {
527 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700528 return;
529 }
François Gaffie2110e042015-03-24 08:41:51 +0100530 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700531 // if leaving call state, handle special case of active streams
532 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700533 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700534 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800535 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700536 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700537 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800538
Eric Laurent63dea1d2015-07-02 17:10:28 -0700539 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800540 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700541 }
542
François Gaffie2110e042015-03-24 08:41:51 +0100543 /**
544 * Switching to or from incall state or switching between telephony and VoIP lead to force
545 * routing command.
546 */
547 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
548 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700549
550 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700551 checkA2dpSuspend();
552 checkOutputForAllStrategies();
553 updateDevicesAndOutputs();
554
Eric Laurente552edb2014-03-10 17:42:56 -0700555 int delayMs = 0;
556 if (isStateInCall(state)) {
557 nsecs_t sysTime = systemTime();
558 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700559 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700560 // mute media and sonification strategies and delay device switch by the largest
561 // latency of any output where either strategy is active.
562 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100563 if ((isStrategyActive(desc, STRATEGY_MEDIA,
564 SONIFICATION_HEADSET_MUSIC_DELAY,
565 sysTime) ||
566 isStrategyActive(desc, STRATEGY_SONIFICATION,
567 SONIFICATION_HEADSET_MUSIC_DELAY,
568 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700569 (delayMs < (int)desc->latency()*2)) {
570 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700571 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 setStrategyMute(STRATEGY_MEDIA, true, desc);
573 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700574 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700575 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
576 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700577 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
578 }
579 }
580
Eric Laurent87ffa392015-05-22 10:32:38 -0700581 if (hasPrimaryOutput()) {
582 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
583 // the device returned is not necessarily reachable via this output
584 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
585 // force routing command to audio hardware when ending call
586 // even if no device change is needed
587 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
588 rxDevice = mPrimaryOutput->device();
589 }
Eric Laurente552edb2014-03-10 17:42:56 -0700590
Eric Laurent87ffa392015-05-22 10:32:38 -0700591 if (state == AUDIO_MODE_IN_CALL) {
592 updateCallRouting(rxDevice, delayMs);
593 } else if (oldState == AUDIO_MODE_IN_CALL) {
594 if (mCallRxPatch != 0) {
595 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
596 mCallRxPatch.clear();
597 }
598 if (mCallTxPatch != 0) {
599 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
600 mCallTxPatch.clear();
601 }
602 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
603 } else {
604 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 }
Eric Laurente552edb2014-03-10 17:42:56 -0700607 // if entering in call state, handle special case of active streams
608 // pertaining to sonification strategy see handleIncallSonification()
609 if (isStateInCall(state)) {
610 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800611 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700612 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700613 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700614
615 // force reevaluating accessibility routing when call starts
616 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700617 }
618
619 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700620 if (state == AUDIO_MODE_RINGTONE &&
621 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700622 mLimitRingtoneVolume = true;
623 } else {
624 mLimitRingtoneVolume = false;
625 }
626}
627
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700628audio_mode_t AudioPolicyManager::getPhoneState() {
629 return mEngine->getPhoneState();
630}
631
Eric Laurente0720872014-03-11 09:30:41 -0700632void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700633 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700634{
François Gaffie2110e042015-03-24 08:41:51 +0100635 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700636
François Gaffie2110e042015-03-24 08:41:51 +0100637 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
638 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
639 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700640 }
François Gaffie2110e042015-03-24 08:41:51 +0100641 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
642 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
643 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700644
645 // check for device and output changes triggered by new force usage
646 checkA2dpSuspend();
647 checkOutputForAllStrategies();
648 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800649
Eric Laurentdc462862016-07-19 12:29:53 -0700650 //FIXME: workaround for truncated touch sounds
651 // to be removed when the problem is handled by system UI
652 uint32_t delayMs = 0;
653 uint32_t waitMs = 0;
654 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
655 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
656 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700657 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700659 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700660 }
Eric Laurente552edb2014-03-10 17:42:56 -0700661 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700662 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
663 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
664 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700665 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
666 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700667 }
Eric Laurente552edb2014-03-10 17:42:56 -0700668 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700669 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700670 }
671 }
672
Eric Laurentfb66dd92016-01-28 18:32:03 -0800673 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
674 for (size_t i = 0; i < activeInputs.size(); i++) {
675 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
676 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700677 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800678 if (activeDesc->mProfile->getSupportedDevices().types() &
679 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
680 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700681 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800682 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700683 }
Eric Laurente552edb2014-03-10 17:42:56 -0700684 }
Eric Laurente552edb2014-03-10 17:42:56 -0700685}
686
Eric Laurente0720872014-03-11 09:30:41 -0700687void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700688{
689 ALOGV("setSystemProperty() property %s, value %s", property, value);
690}
691
692// Find a direct output profile compatible with the parameters passed, even if the input flags do
693// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800694sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700695 audio_devices_t device,
696 uint32_t samplingRate,
697 audio_format_t format,
698 audio_channel_mask_t channelMask,
699 audio_output_flags_t flags)
700{
Eric Laurent861a6282015-05-18 15:40:16 -0700701 // only retain flags that will drive the direct output profile selection
702 // if explicitly requested
703 static const uint32_t kRelevantFlags =
704 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
705 flags =
706 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
707
708 sp<IOProfile> profile;
709
Eric Laurente552edb2014-03-10 17:42:56 -0700710 for (size_t i = 0; i < mHwModules.size(); i++) {
711 if (mHwModules[i]->mHandle == 0) {
712 continue;
713 }
714 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700715 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
716 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700717 samplingRate, NULL /*updatedSamplingRate*/,
718 format, NULL /*updatedFormat*/,
719 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700720 flags)) {
721 continue;
722 }
723 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100724 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700725 continue;
726 }
727 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100728 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 continue;
730 }
731 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100732 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700733 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700734 }
Eric Laurente552edb2014-03-10 17:42:56 -0700735 }
736 }
Eric Laurent861a6282015-05-18 15:40:16 -0700737 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700738}
739
Eric Laurente0720872014-03-11 09:30:41 -0700740audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100741 uint32_t samplingRate,
742 audio_format_t format,
743 audio_channel_mask_t channelMask,
744 audio_output_flags_t flags,
745 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700746{
Eric Laurent3b73df72014-03-11 09:06:29 -0700747 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700748 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
749 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
750 device, stream, samplingRate, format, channelMask, flags);
751
Eric Laurente83b55d2014-11-14 10:06:21 -0800752 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
753 stream, samplingRate,format, channelMask,
754 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700755}
756
Eric Laurente83b55d2014-11-14 10:06:21 -0800757status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
758 audio_io_handle_t *output,
759 audio_session_t session,
760 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700761 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800762 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800763 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700764 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800765 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700766{
Eric Laurente83b55d2014-11-14 10:06:21 -0800767 audio_attributes_t attributes;
768 if (attr != NULL) {
769 if (!isValidAttributes(attr)) {
770 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
771 attr->usage, attr->content_type, attr->flags,
772 attr->tags);
773 return BAD_VALUE;
774 }
775 attributes = *attr;
776 } else {
777 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
778 ALOGE("getOutputForAttr(): invalid stream type");
779 return BAD_VALUE;
780 }
781 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700782 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800783
784 // TODO: check for existing client for this port ID
785 if (*portId == AUDIO_PORT_HANDLE_NONE) {
786 *portId = AudioPort::getNextUniqueId();
787 }
788
Eric Laurentc75307b2015-03-17 15:29:32 -0700789 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800790 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100791 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800792 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100793 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800794 }
François Gaffie036e1e92015-03-19 10:16:24 +0100795 *stream = streamTypefromAttributesInt(&attributes);
796 *output = desc->mIoHandle;
797 ALOGV("getOutputForAttr() returns output %d", *output);
798 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800799 }
800 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
801 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
802 return BAD_VALUE;
803 }
804
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700805 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
806 " session %d selectedDeviceId %d",
807 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
808 session, selectedDeviceId);
809
810 *stream = streamTypefromAttributesInt(&attributes);
811
812 // Explicit routing?
813 sp<DeviceDescriptor> deviceDesc;
814 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
815 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
816 deviceDesc = mAvailableOutputDevices[i];
817 break;
818 }
819 }
820 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700821
Eric Laurente83b55d2014-11-14 10:06:21 -0800822 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700823 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700824
Eric Laurente83b55d2014-11-14 10:06:21 -0800825 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700826 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
827 }
828
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700829 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800830 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700831
Eric Laurente83b55d2014-11-14 10:06:21 -0800832 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800833 config->sample_rate, config->format, config->channel_mask,
834 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800835 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700836 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800837 return INVALID_OPERATION;
838 }
Paul McLeanaa981192015-03-21 09:55:15 -0700839
Eric Laurente83b55d2014-11-14 10:06:21 -0800840 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700841}
842
843audio_io_handle_t AudioPolicyManager::getOutputForDevice(
844 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800845 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846 audio_stream_type_t stream,
847 uint32_t samplingRate,
848 audio_format_t format,
849 audio_channel_mask_t channelMask,
850 audio_output_flags_t flags,
851 const audio_offload_info_t *offloadInfo)
852{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700853 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700854 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700855
Eric Laurente552edb2014-03-10 17:42:56 -0700856#ifdef AUDIO_POLICY_TEST
857 if (mCurOutput != 0) {
858 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
859 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
860
861 if (mTestOutputs[mCurOutput] == 0) {
862 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
864 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700865 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700866 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700867 outputDesc->mFlags =
868 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700869 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700870 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
871 config.sample_rate = mTestSamplingRate;
872 config.channel_mask = mTestChannels;
873 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700874 if (offloadInfo != NULL) {
875 config.offload_info = *offloadInfo;
876 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700877 status = mpClientInterface->openOutput(0,
878 &mTestOutputs[mCurOutput],
879 &config,
880 &outputDesc->mDevice,
881 String8(""),
882 &outputDesc->mLatency,
883 outputDesc->mFlags);
884 if (status == NO_ERROR) {
885 outputDesc->mSamplingRate = config.sample_rate;
886 outputDesc->mFormat = config.format;
887 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700888 AudioParameter outputCmd = AudioParameter();
889 outputCmd.addInt(String8("set_id"),mCurOutput);
890 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
891 addOutput(mTestOutputs[mCurOutput], outputDesc);
892 }
893 }
894 return mTestOutputs[mCurOutput];
895 }
896#endif //AUDIO_POLICY_TEST
897
898 // open a direct output if required by specified parameters
899 //force direct flag if offload flag is set: offloading implies a direct output stream
900 // and all common behaviors are driven by checking only the direct flag
901 // this should normally be set appropriately in the policy configuration file
902 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700903 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700904 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700905 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
906 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
907 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800908 // only allow deep buffering for music stream type
909 if (stream != AUDIO_STREAM_MUSIC) {
910 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700911 } else if (/* stream == AUDIO_STREAM_MUSIC && */
912 flags == AUDIO_OUTPUT_FLAG_NONE &&
913 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
914 // use DEEP_BUFFER as default output for music stream type
915 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800916 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700917 if (stream == AUDIO_STREAM_TTS) {
918 flags = AUDIO_OUTPUT_FLAG_TTS;
919 }
Eric Laurente552edb2014-03-10 17:42:56 -0700920
Eric Laurentb732cf52014-09-24 19:08:21 -0700921 sp<IOProfile> profile;
922
923 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700924 // and not explicitly requested
925 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800926 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700927 audio_channel_count_from_out_mask(channelMask) <= 2) {
928 goto non_direct_output;
929 }
930
Andy Hung2ddee192015-12-18 17:34:44 -0800931 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
932 // This prevents creating an offloaded track and tearing it down immediately after start
933 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700934 // FIXME: We should check the audio session here but we do not have it in this context.
935 // This may prevent offloading in rare situations where effects are left active by apps
936 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700937
Eric Laurente552edb2014-03-10 17:42:56 -0700938 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800939 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700940 profile = getProfileForDirectOutput(device,
941 samplingRate,
942 format,
943 channelMask,
944 (audio_output_flags_t)flags);
945 }
946
Eric Laurent1c333e22014-05-20 10:48:17 -0700947 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700948 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700949
950 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700951 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700952 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
953 outputDesc = desc;
954 // reuse direct output if currently open and configured with same parameters
955 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800956 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700957 (channelMask == outputDesc->mChannelMask)) {
958 outputDesc->mDirectOpenCount++;
959 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
960 return mOutputs.keyAt(i);
961 }
962 }
963 }
964 // close direct output if currently open and configured with different parameters
965 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700966 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
Eric Laurent861a6282015-05-18 15:40:16 -0700968
969 // if the selected profile is offloaded and no offload info was specified,
970 // create a default one
971 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100972 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700973 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
974 defaultOffloadInfo.sample_rate = samplingRate;
975 defaultOffloadInfo.channel_mask = channelMask;
976 defaultOffloadInfo.format = format;
977 defaultOffloadInfo.stream_type = stream;
978 defaultOffloadInfo.bit_rate = 0;
979 defaultOffloadInfo.duration_us = -1;
980 defaultOffloadInfo.has_video = true; // conservative
981 defaultOffloadInfo.is_streaming = true; // likely
982 offloadInfo = &defaultOffloadInfo;
983 }
984
Eric Laurentc75307b2015-03-17 15:29:32 -0700985 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700986 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700987 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700988 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700989 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
990 config.sample_rate = samplingRate;
991 config.channel_mask = channelMask;
992 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700993 if (offloadInfo != NULL) {
994 config.offload_info = *offloadInfo;
995 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700996 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700997 &output,
998 &config,
999 &outputDesc->mDevice,
1000 String8(""),
1001 &outputDesc->mLatency,
1002 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001003
1004 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001005 if (status != NO_ERROR ||
1006 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001007 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001008 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001009 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1010 "format %d %d, channelMask %04x %04x", output, samplingRate,
1011 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1012 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001013 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001014 mpClientInterface->closeOutput(output);
1015 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001016 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001017 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001018 goto non_direct_output;
1019 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001020 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001021 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001022 outputDesc->mSamplingRate = config.sample_rate;
1023 outputDesc->mChannelMask = config.channel_mask;
1024 outputDesc->mFormat = config.format;
1025 outputDesc->mRefCount[stream] = 0;
1026 outputDesc->mStopTime[stream] = 0;
1027 outputDesc->mDirectOpenCount = 1;
1028
Eric Laurente552edb2014-03-10 17:42:56 -07001029 audio_io_handle_t srcOutput = getOutputForEffect();
1030 addOutput(output, outputDesc);
1031 audio_io_handle_t dstOutput = getOutputForEffect();
1032 if (dstOutput == output) {
1033 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1034 }
1035 mPreviousOutputs = mOutputs;
1036 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001037 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001038 return output;
1039 }
1040
Eric Laurentb732cf52014-09-24 19:08:21 -07001041non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001042
1043 // A request for HW A/V sync cannot fallback to a mixed output because time
1044 // stamps are embedded in audio data
1045 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1046 return AUDIO_IO_HANDLE_NONE;
1047 }
1048
Eric Laurente552edb2014-03-10 17:42:56 -07001049 // ignoring channel mask due to downmix capability in mixer
1050
1051 // open a non direct output
1052
1053 // for non direct outputs, only PCM is supported
1054 if (audio_is_linear_pcm(format)) {
1055 // get which output is suitable for the specified stream. The actual
1056 // routing change will happen when startOutput() will be called
1057 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1058
Eric Laurent8838a382014-09-08 16:44:28 -07001059 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1060 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1061 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001062 }
1063 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1064 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1065
Paul McLeanaa981192015-03-21 09:55:15 -07001066 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001067
1068 return output;
1069}
1070
Eric Laurente0720872014-03-11 09:30:41 -07001071audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001072 audio_output_flags_t flags,
1073 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001074{
1075 // select one output among several that provide a path to a particular device or set of
1076 // devices (the list was previously build by getOutputsForDevice()).
1077 // The priority is as follows:
1078 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001079 // 2: the output with the bit depth the closest to the requested one
1080 // 3: the primary output
1081 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001082
1083 if (outputs.size() == 0) {
1084 return 0;
1085 }
1086 if (outputs.size() == 1) {
1087 return outputs[0];
1088 }
1089
1090 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001091 audio_io_handle_t outputForFlags = 0;
1092 audio_io_handle_t outputForPrimary = 0;
1093 audio_io_handle_t outputForFormat = 0;
1094 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1095 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001096
1097 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001098 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001099 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001100 // if a valid format is specified, skip output if not compatible
1101 if (format != AUDIO_FORMAT_INVALID) {
1102 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001103 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001104 continue;
1105 }
1106 } else if (!audio_is_linear_pcm(format)) {
1107 continue;
1108 }
Eric Laurente6930022016-02-11 10:20:40 -08001109 if (AudioPort::isBetterFormatMatch(
1110 outputDesc->mFormat, bestFormat, format)) {
1111 outputForFormat = outputs[i];
1112 bestFormat = outputDesc->mFormat;
1113 }
Eric Laurent8838a382014-09-08 16:44:28 -07001114 }
1115
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001116 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001117 if (commonFlags >= maxCommonFlags) {
1118 if (commonFlags == maxCommonFlags) {
1119 if (AudioPort::isBetterFormatMatch(
1120 outputDesc->mFormat, bestFormatForFlags, format)) {
1121 outputForFlags = outputs[i];
1122 bestFormatForFlags = outputDesc->mFormat;
1123 }
1124 } else {
1125 outputForFlags = outputs[i];
1126 maxCommonFlags = commonFlags;
1127 bestFormatForFlags = outputDesc->mFormat;
1128 }
Eric Laurente552edb2014-03-10 17:42:56 -07001129 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1130 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001131 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001132 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001133 }
1134 }
1135 }
1136
Eric Laurente6930022016-02-11 10:20:40 -08001137 if (outputForFlags != 0) {
1138 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001139 }
Eric Laurente6930022016-02-11 10:20:40 -08001140 if (outputForFormat != 0) {
1141 return outputForFormat;
1142 }
1143 if (outputForPrimary != 0) {
1144 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001145 }
1146
1147 return outputs[0];
1148}
1149
Eric Laurente0720872014-03-11 09:30:41 -07001150status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001151 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001152 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001153{
Paul McLeanaa981192015-03-21 09:55:15 -07001154 ALOGV("startOutput() output %d, stream %d, session %d",
1155 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001156 ssize_t index = mOutputs.indexOfKey(output);
1157 if (index < 0) {
1158 ALOGW("startOutput() unknown output %d", output);
1159 return BAD_VALUE;
1160 }
1161
Eric Laurentc75307b2015-03-17 15:29:32 -07001162 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1163
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001164 // Routing?
1165 mOutputRoutes.incRouteActivity(session);
1166
Eric Laurentc75307b2015-03-17 15:29:32 -07001167 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001168 AudioMix *policyMix = NULL;
1169 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001170 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001171 policyMix = outputDesc->mPolicyMix;
1172 address = policyMix->mDeviceAddress.string();
1173 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1174 newDevice = policyMix->mDeviceType;
1175 } else {
1176 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1177 }
Eric Laurent493404d2015-04-21 15:07:36 -07001178 } else if (mOutputRoutes.hasRouteChanged(session)) {
1179 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001180 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001181 } else {
1182 newDevice = AUDIO_DEVICE_NONE;
1183 }
1184
1185 uint32_t delayMs = 0;
1186
Eric Laurentc40d9692016-04-13 19:14:13 -07001187 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001188
1189 if (status != NO_ERROR) {
1190 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001191 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001192 }
1193 // Automatically enable the remote submix input when output is started on a re routing mix
1194 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001195 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1196 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001197 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1198 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001199 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001200 "remote-submix");
1201 }
1202
1203 if (delayMs != 0) {
1204 usleep(delayMs * 1000);
1205 }
1206
1207 return status;
1208}
1209
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001210status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001211 audio_stream_type_t stream,
1212 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001213 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001214 uint32_t *delayMs)
1215{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001216 // cannot start playback of STREAM_TTS if any other output is being used
1217 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001218
1219 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001220 if (stream == AUDIO_STREAM_TTS) {
1221 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001222 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001223 return INVALID_OPERATION;
1224 } else {
1225 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1226 }
1227 } else {
1228 // some playback other than beacon starts
1229 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1230 }
1231
Eric Laurent77305a62016-07-25 16:39:22 -07001232 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001233 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001234 bool force = !outputDesc->isActive() &&
1235 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001236
Eric Laurente552edb2014-03-10 17:42:56 -07001237 // increment usage count for this stream on the requested output:
1238 // NOTE that the usage count is the same for duplicated output and hardware output which is
1239 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1240 outputDesc->changeRefCount(stream, 1);
1241
Eric Laurent493404d2015-04-21 15:07:36 -07001242 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001243 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001244 if (device == AUDIO_DEVICE_NONE) {
1245 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001246 }
Eric Laurente552edb2014-03-10 17:42:56 -07001247 routing_strategy strategy = getStrategy(stream);
1248 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001249 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1250 (beaconMuteLatency > 0);
1251 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001252 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001253 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001254 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001255 // force a device change if any other output is:
1256 // - managed by the same hw module
1257 // - has a current device selection that differs from selected device.
1258 // - supports currently selected device
1259 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001260 // In this case, the audio HAL must receive the new device selection so that it can
1261 // change the device currently selected by the other active output.
1262 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001263 desc->device() != device &&
1264 desc->supportedDevices() & device &&
1265 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001266 force = true;
1267 }
1268 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001269 // a notification so that audio focus effect can propagate, or that a mute/unmute
1270 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001271 uint32_t latency = desc->latency();
1272 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1273 waitMs = latency;
1274 }
1275 }
1276 }
Eric Laurentdc462862016-07-19 12:29:53 -07001277 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001278
1279 // handle special case for sonification while in call
1280 if (isInCall()) {
1281 handleIncallSonification(stream, true, false);
1282 }
1283
1284 // apply volume rules for current stream and device if necessary
1285 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001286 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001287 outputDesc,
1288 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001289
1290 // update the outputs if starting an output with a stream that can affect notification
1291 // routing
1292 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001293
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001294 // force reevaluating accessibility routing when ringtone or alarm starts
1295 if (strategy == STRATEGY_SONIFICATION) {
1296 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1297 }
Eric Laurentdc462862016-07-19 12:29:53 -07001298
1299 if (waitMs > muteWaitMs) {
1300 *delayMs = waitMs - muteWaitMs;
1301 }
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
Eric Laurentdc462862016-07-19 12:29:53 -07001303
Eric Laurente552edb2014-03-10 17:42:56 -07001304 return NO_ERROR;
1305}
1306
1307
Eric Laurente0720872014-03-11 09:30:41 -07001308status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001309 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001310 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001311{
1312 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1313 ssize_t index = mOutputs.indexOfKey(output);
1314 if (index < 0) {
1315 ALOGW("stopOutput() unknown output %d", output);
1316 return BAD_VALUE;
1317 }
1318
Eric Laurentc75307b2015-03-17 15:29:32 -07001319 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001320
Eric Laurentc75307b2015-03-17 15:29:32 -07001321 if (outputDesc->mRefCount[stream] == 1) {
1322 // Automatically disable the remote submix input when output is stopped on a
1323 // re routing mix of type MIX_TYPE_RECORDERS
1324 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1325 outputDesc->mPolicyMix != NULL &&
1326 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1327 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1328 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001329 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001330 "remote-submix");
1331 }
1332 }
1333
1334 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001335 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001336 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001337 int activityCount = mOutputRoutes.decRouteActivity(session);
1338 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1339
1340 if (forceDeviceUpdate) {
1341 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1342 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001343 }
1344
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001345 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001346}
1347
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001348status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001349 audio_stream_type_t stream,
1350 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001351{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001352 // always handle stream stop, check which stream type is stopping
1353 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1354
Eric Laurente552edb2014-03-10 17:42:56 -07001355 // handle special case for sonification while in call
1356 if (isInCall()) {
1357 handleIncallSonification(stream, false, false);
1358 }
1359
1360 if (outputDesc->mRefCount[stream] > 0) {
1361 // decrement usage count of this stream on the output
1362 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001363
Eric Laurente552edb2014-03-10 17:42:56 -07001364 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001365 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001366 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001367 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001368 // delay the device switch by twice the latency because stopOutput() is executed when
1369 // the track stop() command is received and at that time the audio track buffer can
1370 // still contain data that needs to be drained. The latency only covers the audio HAL
1371 // and kernel buffers. Also the latency does not always include additional delay in the
1372 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001374
1375 // force restoring the device selection on other active outputs if it differs from the
1376 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001377 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001378 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001379 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001380 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001381 desc->isActive() &&
1382 outputDesc->sharesHwModuleWith(desc) &&
1383 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001384 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1385 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001386 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001387 newDevice2,
1388 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001389 delayMs);
1390 // re-apply device specific volume if not done by setOutputDevice()
1391 if (!force) {
1392 applyStreamVolumes(desc, newDevice2, delayMs);
1393 }
Eric Laurente552edb2014-03-10 17:42:56 -07001394 }
1395 }
1396 // update the outputs if stopping one with a stream that can affect notification routing
1397 handleNotificationRoutingForStream(stream);
1398 }
1399 return NO_ERROR;
1400 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001401 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001402 return INVALID_OPERATION;
1403 }
1404}
1405
Eric Laurente83b55d2014-11-14 10:06:21 -08001406void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001407 audio_stream_type_t stream __unused,
1408 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001409{
1410 ALOGV("releaseOutput() %d", output);
1411 ssize_t index = mOutputs.indexOfKey(output);
1412 if (index < 0) {
1413 ALOGW("releaseOutput() releasing unknown output %d", output);
1414 return;
1415 }
1416
1417#ifdef AUDIO_POLICY_TEST
1418 int testIndex = testOutputIndex(output);
1419 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001420 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001421 if (outputDesc->isActive()) {
1422 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001423 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001424 mTestOutputs[testIndex] = 0;
1425 }
1426 return;
1427 }
1428#endif //AUDIO_POLICY_TEST
1429
Paul McLeanaa981192015-03-21 09:55:15 -07001430 // Routing
1431 mOutputRoutes.removeRoute(session);
1432
Eric Laurentc75307b2015-03-17 15:29:32 -07001433 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001434 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001435 if (desc->mDirectOpenCount <= 0) {
1436 ALOGW("releaseOutput() invalid open count %d for output %d",
1437 desc->mDirectOpenCount, output);
1438 return;
1439 }
1440 if (--desc->mDirectOpenCount == 0) {
1441 closeOutput(output);
1442 // If effects where present on the output, audioflinger moved them to the primary
1443 // output by default: move them back to the appropriate output.
1444 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001445 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001446 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1447 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001448 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001449 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001450 }
1451 }
1452}
1453
1454
Eric Laurentcaf7f482014-11-25 17:50:47 -08001455status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1456 audio_io_handle_t *input,
1457 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001458 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001459 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001460 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001461 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001462 input_type_t *inputType,
1463 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001464{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001465 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1466 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001467 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001468
Eric Laurentcaf7f482014-11-25 17:50:47 -08001469 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001470 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001471
Eric Laurent275e8e92014-11-30 15:14:47 -08001472 audio_devices_t device;
1473 // handle legacy remote submix case where the address was not always specified
1474 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001475 audio_source_t inputSource = attr->source;
1476 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001477 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001478
Eric Laurentc447ded2015-01-06 08:47:05 -08001479 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1480 inputSource = AUDIO_SOURCE_MIC;
1481 }
1482 halInputSource = inputSource;
1483
Eric Laurent20b9ef02016-12-05 11:03:16 -08001484 // TODO: check for existing client for this port ID
1485 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1486 *portId = AudioPort::getNextUniqueId();
1487 }
1488
Paul McLean466dc8e2015-04-17 13:15:36 -06001489 // Explicit routing?
1490 sp<DeviceDescriptor> deviceDesc;
1491 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1492 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1493 deviceDesc = mAvailableInputDevices[i];
1494 break;
1495 }
1496 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001497 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001498
Eric Laurentc447ded2015-01-06 08:47:05 -08001499 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001500 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001501 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001502 if (ret != NO_ERROR) {
1503 return ret;
1504 }
1505 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001506 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1507 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001508 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001509 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001510 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001511 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001512 return BAD_VALUE;
1513 }
Eric Laurentc722f302014-12-10 11:21:49 -08001514 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001515 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001516 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1517 // there is an external policy, but this input is attached to a mix of recorders,
1518 // meaning it receives audio injected into the framework, so the recorder doesn't
1519 // know about it and is therefore considered "legacy"
1520 *inputType = API_INPUT_LEGACY;
1521 } else {
1522 // recording a mix of players defined by an external policy, we're rerouting for
1523 // an external policy
1524 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1525 }
Eric Laurentc722f302014-12-10 11:21:49 -08001526 } else if (audio_is_remote_submix_device(device)) {
1527 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001528 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001529 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1530 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001531 } else {
1532 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001533 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001534
Eric Laurent599c7582015-12-07 18:05:55 -08001535 }
1536
1537 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001538 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001539 policyMix);
1540 if (*input == AUDIO_IO_HANDLE_NONE) {
1541 mInputRoutes.removeRoute(session);
1542 return INVALID_OPERATION;
1543 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001544
Eric Laurent599c7582015-12-07 18:05:55 -08001545 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1546 return NO_ERROR;
1547}
1548
1549
1550audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1551 String8 address,
1552 audio_session_t session,
1553 uid_t uid,
1554 audio_source_t inputSource,
1555 uint32_t samplingRate,
1556 audio_format_t format,
1557 audio_channel_mask_t channelMask,
1558 audio_input_flags_t flags,
1559 AudioMix *policyMix)
1560{
1561 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1562 audio_source_t halInputSource = inputSource;
1563 bool isSoundTrigger = false;
1564
1565 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1566 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1567 if (index >= 0) {
1568 input = mSoundTriggerSessions.valueFor(session);
1569 isSoundTrigger = true;
1570 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1571 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1572 } else {
1573 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001574 }
1575 }
1576
Andy Hungf129b032015-04-07 13:45:50 -07001577 // find a compatible input profile (not necessarily identical in parameters)
1578 sp<IOProfile> profile;
1579 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001580 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001581 audio_format_t profileFormat = format;
1582 audio_channel_mask_t profileChannelMask = channelMask;
1583 audio_input_flags_t profileFlags = flags;
1584 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001585 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001586 profileSamplingRate, profileFormat, profileChannelMask,
1587 profileFlags);
1588 if (profile != 0) {
1589 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001590 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1591 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001592 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1593 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1594 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001595 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1596 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001597 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001598 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001599 }
Eric Laurente552edb2014-03-10 17:42:56 -07001600 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001601 // Pick input sampling rate if not specified by client
1602 if (samplingRate == 0) {
1603 samplingRate = profileSamplingRate;
1604 }
Eric Laurente552edb2014-03-10 17:42:56 -07001605
Eric Laurent322b4d22015-04-03 15:57:54 -07001606 if (profile->getModuleHandle() == 0) {
1607 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001608 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001609 }
1610
Eric Laurent599c7582015-12-07 18:05:55 -08001611 sp<AudioSession> audioSession = new AudioSession(session,
1612 inputSource,
1613 format,
1614 samplingRate,
1615 channelMask,
1616 flags,
1617 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001618 isSoundTrigger,
1619 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001620
Eric Laurentfb66dd92016-01-28 18:32:03 -08001621
Eric Laurent599c7582015-12-07 18:05:55 -08001622 // reuse an open input if possible
1623 for (size_t i = 0; i < mInputs.size(); i++) {
1624 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001625 // reuse input if:
1626 // - it shares the same profile
1627 // AND
1628 // - it is not a reroute submix input
1629 // AND
1630 // - it is: not used for sound trigger
1631 // OR
1632 // used for sound trigger and all clients use the same session ID
1633 //
1634 if ((profile == desc->mProfile) &&
1635 (isSoundTrigger == desc->isSoundTrigger()) &&
1636 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001637
1638 sp<AudioSession> as = desc->getAudioSession(session);
1639 if (as != 0) {
1640 // do not allow unmatching properties on same session
1641 if (as->matches(audioSession)) {
1642 as->changeOpenCount(1);
1643 } else {
1644 ALOGW("getInputForDevice() record with different attributes"
1645 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001646 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001647 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001648 } else if (isSoundTrigger) {
1649 break;
1650 }
1651 // force close input if current source is now the highest priority request on this input
1652 // and current input properties are not exactly as requested.
1653 if ((desc->mSamplingRate != samplingRate ||
1654 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001655 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001656 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1657 source_priority(inputSource))) {
1658 ALOGV("%s: ", __FUNCTION__);
1659 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1660 for (size_t j = 0; j < sessions.size(); j++) {
1661 audio_session_t currentSession = sessions.keyAt(j);
1662 stopInput(desc->mIoHandle, currentSession);
1663 releaseInput(desc->mIoHandle, currentSession);
1664 }
1665 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001666 } else {
1667 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001668 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1669 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001670 }
Eric Laurent599c7582015-12-07 18:05:55 -08001671 }
1672 }
Eric Laurent599c7582015-12-07 18:05:55 -08001673
Eric Laurentcf2c0212014-07-25 16:20:43 -07001674 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001675 config.sample_rate = profileSamplingRate;
1676 config.channel_mask = profileChannelMask;
1677 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001678
Eric Laurent322b4d22015-04-03 15:57:54 -07001679 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001680 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001681 &config,
1682 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001683 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001684 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001685 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001686
1687 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001688 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001689 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001690 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001691 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001692 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1693 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001694 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001695 if (input != AUDIO_IO_HANDLE_NONE) {
1696 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001697 }
Eric Laurent599c7582015-12-07 18:05:55 -08001698 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001699 }
1700
Eric Laurent1f2f2232014-06-02 12:01:23 -07001701 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001702 inputDesc->mSamplingRate = profileSamplingRate;
1703 inputDesc->mFormat = profileFormat;
1704 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001705 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001706 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001707 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001708
Eric Laurent599c7582015-12-07 18:05:55 -08001709 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001710 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001711
Eric Laurent599c7582015-12-07 18:05:55 -08001712 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001713}
1714
Eric Laurentfb66dd92016-01-28 18:32:03 -08001715bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1716 const sp<AudioSession>& audioSession)
1717{
1718 // Do not allow capture if an active voice call is using a software patch and
1719 // the call TX source device is on the same HW module.
1720 // FIXME: would be better to refine to only inputs whose profile connects to the
1721 // call TX device but this information is not in the audio patch
1722 if (mCallTxPatch != 0 &&
1723 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1724 return false;
1725 }
1726
1727 // starting concurrent capture is enabled if:
1728 // 1) capturing for re-routing
1729 // 2) capturing for HOTWORD source
1730 // 3) capturing for FM TUNER source
1731 // 3) All other active captures are either for re-routing or HOTWORD
1732
1733 if (is_virtual_input_device(inputDesc->mDevice) ||
1734 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1735 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1736 return true;
1737 }
1738
1739 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1740 for (size_t i = 0; i < activeInputs.size(); i++) {
1741 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1742 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1743 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1744 !is_virtual_input_device(activeInput->mDevice)) {
1745 return false;
1746 }
1747 }
1748
1749 return true;
1750}
1751
1752
Eric Laurent4dc68062014-07-28 17:26:49 -07001753status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001754 audio_session_t session,
1755 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001756{
1757 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001758 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001759 ssize_t index = mInputs.indexOfKey(input);
1760 if (index < 0) {
1761 ALOGW("startInput() unknown input %d", input);
1762 return BAD_VALUE;
1763 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001764 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001765
Eric Laurent599c7582015-12-07 18:05:55 -08001766 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1767 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001768 ALOGW("startInput() unknown session %d on input %d", session, input);
1769 return BAD_VALUE;
1770 }
1771
Eric Laurentfb66dd92016-01-28 18:32:03 -08001772 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1773 ALOGW("startInput(%d) failed: other input already started", input);
1774 return INVALID_OPERATION;
1775 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001776
Eric Laurentfb66dd92016-01-28 18:32:03 -08001777 if (isInCall()) {
1778 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1779 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001780 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001781 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001782 }
1783
Eric Laurent313d1e72016-01-29 09:56:57 -08001784 // increment activity count before calling getNewInputDevice() below as only active sessions
1785 // are considered for device selection
1786 audioSession->changeActiveCount(1);
1787
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001788 // Routing?
1789 mInputRoutes.incRouteActivity(session);
1790
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001791 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001792 // indicate active capture to sound trigger service if starting capture from a mic on
1793 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001794 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001795 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001796
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001797 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1798 // if input maps to a dynamic policy with an activity listener, notify of state change
1799 if ((inputDesc->mPolicyMix != NULL)
1800 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1801 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1802 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001803 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001804
Eric Laurentf7c50102016-09-30 15:19:43 -07001805 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1806 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001807 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001808 SoundTrigger::setCaptureState(true);
1809 }
1810
1811 // automatically enable the remote submix output when input is started if not
1812 // used by a policy mix of type MIX_TYPE_RECORDERS
1813 // For remote submix (a virtual device), we open only one input per capture request.
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) {
1819 address = inputDesc->mPolicyMix->mDeviceAddress;
1820 }
1821 if (address != "") {
1822 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1823 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1824 address, "remote-submix");
1825 }
Eric Laurentc722f302014-12-10 11:21:49 -08001826 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001827 }
Eric Laurente552edb2014-03-10 17:42:56 -07001828 }
1829
Eric Laurent599c7582015-12-07 18:05:55 -08001830 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001831
Eric Laurente552edb2014-03-10 17:42:56 -07001832 return NO_ERROR;
1833}
1834
Eric Laurent4dc68062014-07-28 17:26:49 -07001835status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1836 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001837{
1838 ALOGV("stopInput() input %d", input);
1839 ssize_t index = mInputs.indexOfKey(input);
1840 if (index < 0) {
1841 ALOGW("stopInput() unknown input %d", input);
1842 return BAD_VALUE;
1843 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001844 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001845
Eric Laurent599c7582015-12-07 18:05:55 -08001846 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001847 if (index < 0) {
1848 ALOGW("stopInput() unknown session %d on input %d", session, input);
1849 return BAD_VALUE;
1850 }
1851
Eric Laurent599c7582015-12-07 18:05:55 -08001852 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001853 ALOGW("stopInput() input %d already stopped", input);
1854 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001855 }
1856
Eric Laurent599c7582015-12-07 18:05:55 -08001857 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001858
1859 // Routing?
1860 mInputRoutes.decRouteActivity(session);
1861
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001862 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001863
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001864 if (inputDesc->isActive()) {
1865 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1866 } else {
1867 // if input maps to a dynamic policy with an activity listener, notify of state change
1868 if ((inputDesc->mPolicyMix != NULL)
1869 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1870 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1871 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001872 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001873
1874 // automatically disable the remote submix output when input is stopped if not
1875 // used by a policy mix of type MIX_TYPE_RECORDERS
1876 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1877 String8 address = String8("");
1878 if (inputDesc->mPolicyMix == NULL) {
1879 address = String8("0");
1880 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1881 address = inputDesc->mPolicyMix->mDeviceAddress;
1882 }
1883 if (address != "") {
1884 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1885 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1886 address, "remote-submix");
1887 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001888 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001889
Eric Laurentf7c50102016-09-30 15:19:43 -07001890 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001891 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001892
Eric Laurentf7c50102016-09-30 15:19:43 -07001893 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1894 // primary HW module
1895 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1896 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1897 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001898 SoundTrigger::setCaptureState(false);
1899 }
1900 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001901 }
Eric Laurente552edb2014-03-10 17:42:56 -07001902 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001903 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001904}
1905
Eric Laurent4dc68062014-07-28 17:26:49 -07001906void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1907 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001908{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001909
Eric Laurente552edb2014-03-10 17:42:56 -07001910 ALOGV("releaseInput() %d", input);
1911 ssize_t index = mInputs.indexOfKey(input);
1912 if (index < 0) {
1913 ALOGW("releaseInput() releasing unknown input %d", input);
1914 return;
1915 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001916
1917 // Routing
1918 mInputRoutes.removeRoute(session);
1919
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001920 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1921 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001922
Eric Laurent599c7582015-12-07 18:05:55 -08001923 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001924 if (index < 0) {
1925 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1926 return;
1927 }
Eric Laurent599c7582015-12-07 18:05:55 -08001928
1929 if (audioSession->openCount() == 0) {
1930 ALOGW("releaseInput() invalid open count %d on session %d",
1931 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001932 return;
1933 }
Eric Laurent599c7582015-12-07 18:05:55 -08001934
1935 if (audioSession->changeOpenCount(-1) == 0) {
1936 inputDesc->removeAudioSession(session);
1937 }
1938
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001939 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001940 ALOGV("releaseInput() exit > 0");
1941 return;
1942 }
1943
Eric Laurent05b90f82014-08-27 15:32:29 -07001944 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001945 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001946 ALOGV("releaseInput() exit");
1947}
1948
Eric Laurentd4692962014-05-05 18:13:44 -07001949void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001950 bool patchRemoved = false;
1951
Eric Laurentd4692962014-05-05 18:13:44 -07001952 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001953 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001954 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001955 if (patch_index >= 0) {
1956 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001957 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001958 mAudioPatches.removeItemsAt(patch_index);
1959 patchRemoved = true;
1960 }
Eric Laurentd4692962014-05-05 18:13:44 -07001961 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1962 }
1963 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001964 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001965 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001966
1967 if (patchRemoved) {
1968 mpClientInterface->onAudioPatchListUpdate();
1969 }
Eric Laurentd4692962014-05-05 18:13:44 -07001970}
1971
Eric Laurente0720872014-03-11 09:30:41 -07001972void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001973 int indexMin,
1974 int indexMax)
1975{
1976 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001977 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001978
1979 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001980 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1981 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001982 continue;
1983 }
1984 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001985 }
Eric Laurente552edb2014-03-10 17:42:56 -07001986}
1987
Eric Laurente0720872014-03-11 09:30:41 -07001988status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001989 int index,
1990 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001991{
1992
François Gaffied1ab2bd2015-12-02 18:20:06 +01001993 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1994 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001995 return BAD_VALUE;
1996 }
1997 if (!audio_is_output_device(device)) {
1998 return BAD_VALUE;
1999 }
2000
2001 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002002 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002003
Eric Laurent1fd372e2016-04-06 14:23:53 -07002004 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002005 stream, device, index);
2006
Eric Laurent28d09f02016-03-08 10:43:05 -08002007 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002008 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2009 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002010 continue;
2011 }
2012 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2013 }
Eric Laurente552edb2014-03-10 17:42:56 -07002014
Eric Laurent1fd372e2016-04-06 14:23:53 -07002015 // update volume on all outputs and streams matching the following:
2016 // - The requested stream (or a stream matching for volume control) is active on the output
2017 // - The device (or devices) selected by the strategy corresponding to this stream includes
2018 // the requested device
2019 // - For non default requested device, currently selected device on the output is either the
2020 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002021 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2022 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002023 status_t status = NO_ERROR;
2024 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002025 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2026 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002027 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2028 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002029 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002030 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002031 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2032 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002033 continue;
2034 }
Eric Laurent794fde22016-03-11 09:50:45 -08002035 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002036 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
2037 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2038 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002039 continue;
2040 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002041 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002042 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002043 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002044 applyVolume = (curDevice & curStreamDevice) != 0;
2045 } else {
2046 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
2047 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07002048 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002049
Eric Laurente76f29c2016-09-14 17:17:53 -07002050 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002051 //FIXME: workaround for truncated touch sounds
2052 // delayed volume change for system stream to be removed when the problem is
2053 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002054 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002055 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2056 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002057 if (volStatus != NO_ERROR) {
2058 status = volStatus;
2059 }
2060 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002061 }
Eric Laurente552edb2014-03-10 17:42:56 -07002062 }
2063 return status;
2064}
2065
Eric Laurente0720872014-03-11 09:30:41 -07002066status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002067 int *index,
2068 audio_devices_t device)
2069{
2070 if (index == NULL) {
2071 return BAD_VALUE;
2072 }
2073 if (!audio_is_output_device(device)) {
2074 return BAD_VALUE;
2075 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002076 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002077 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002078 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002079 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2080 }
François Gaffiedfd74092015-03-19 12:10:59 +01002081 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002082
François Gaffied1ab2bd2015-12-02 18:20:06 +01002083 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002084 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2085 return NO_ERROR;
2086}
2087
Eric Laurente0720872014-03-11 09:30:41 -07002088audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002089 const SortedVector<audio_io_handle_t>& outputs)
2090{
2091 // select one output among several suitable for global effects.
2092 // The priority is as follows:
2093 // 1: An offloaded output. If the effect ends up not being offloadable,
2094 // AudioFlinger will invalidate the track and the offloaded output
2095 // will be closed causing the effect to be moved to a PCM output.
2096 // 2: A deep buffer output
2097 // 3: the first output in the list
2098
2099 if (outputs.size() == 0) {
2100 return 0;
2101 }
2102
2103 audio_io_handle_t outputOffloaded = 0;
2104 audio_io_handle_t outputDeepBuffer = 0;
2105
2106 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002107 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002108 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002109 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2110 outputOffloaded = outputs[i];
2111 }
2112 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2113 outputDeepBuffer = outputs[i];
2114 }
2115 }
2116
2117 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2118 outputOffloaded, outputDeepBuffer);
2119 if (outputOffloaded != 0) {
2120 return outputOffloaded;
2121 }
2122 if (outputDeepBuffer != 0) {
2123 return outputDeepBuffer;
2124 }
2125
2126 return outputs[0];
2127}
2128
Eric Laurente0720872014-03-11 09:30:41 -07002129audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002130{
2131 // apply simple rule where global effects are attached to the same output as MUSIC streams
2132
Eric Laurent3b73df72014-03-11 09:06:29 -07002133 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002134 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2135 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2136
2137 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2138 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2139 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2140
2141 return output;
2142}
2143
Eric Laurente0720872014-03-11 09:30:41 -07002144status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002145 audio_io_handle_t io,
2146 uint32_t strategy,
2147 int session,
2148 int id)
2149{
2150 ssize_t index = mOutputs.indexOfKey(io);
2151 if (index < 0) {
2152 index = mInputs.indexOfKey(io);
2153 if (index < 0) {
2154 ALOGW("registerEffect() unknown io %d", io);
2155 return INVALID_OPERATION;
2156 }
2157 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002158 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002159}
2160
Eric Laurentc75307b2015-03-17 15:29:32 -07002161bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2162{
Eric Laurent28d09f02016-03-08 10:43:05 -08002163 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002164 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2165 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002166 continue;
2167 }
2168 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2169 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002170 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002171}
2172
2173bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2174{
2175 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2176}
2177
Eric Laurente0720872014-03-11 09:30:41 -07002178bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002179{
2180 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002181 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002182 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002183 return true;
2184 }
2185 }
2186 return false;
2187}
2188
Eric Laurent275e8e92014-11-30 15:14:47 -08002189// Register a list of custom mixes with their attributes and format.
2190// When a mix is registered, corresponding input and output profiles are
2191// added to the remote submix hw module. The profile contains only the
2192// parameters (sampling rate, format...) specified by the mix.
2193// The corresponding input remote submix device is also connected.
2194//
2195// When a remote submix device is connected, the address is checked to select the
2196// appropriate profile and the corresponding input or output stream is opened.
2197//
2198// When capture starts, getInputForAttr() will:
2199// - 1 look for a mix matching the address passed in attribtutes tags if any
2200// - 2 if none found, getDeviceForInputSource() will:
2201// - 2.1 look for a mix matching the attributes source
2202// - 2.2 if none found, default to device selection by policy rules
2203// At this time, the corresponding output remote submix device is also connected
2204// and active playback use cases can be transferred to this mix if needed when reconnecting
2205// after AudioTracks are invalidated
2206//
2207// When playback starts, getOutputForAttr() will:
2208// - 1 look for a mix matching the address passed in attribtutes tags if any
2209// - 2 if none found, look for a mix matching the attributes usage
2210// - 3 if none found, default to device and output selection by policy rules.
2211
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002212status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002213{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002214 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2215 status_t res = NO_ERROR;
2216
2217 sp<HwModule> rSubmixModule;
2218 // examine each mix's route type
2219 for (size_t i = 0; i < mixes.size(); i++) {
2220 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2221 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2222 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002223 break;
2224 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002225 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2226 // Loop back through "remote submix"
2227 if (rSubmixModule == 0) {
2228 for (size_t j = 0; i < mHwModules.size(); j++) {
2229 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2230 && mHwModules[j]->mHandle != 0) {
2231 rSubmixModule = mHwModules[j];
2232 break;
2233 }
2234 }
2235 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002236
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002237 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002238
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002239 if (rSubmixModule == 0) {
2240 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2241 res = INVALID_OPERATION;
2242 break;
2243 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002244
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002245 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002246
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002247 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002248 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002249 res = INVALID_OPERATION;
2250 break;
2251 }
2252 audio_config_t outputConfig = mixes[i].mFormat;
2253 audio_config_t inputConfig = mixes[i].mFormat;
2254 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2255 // stereo and let audio flinger do the channel conversion if needed.
2256 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2257 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2258 rSubmixModule->addOutputProfile(address, &outputConfig,
2259 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2260 rSubmixModule->addInputProfile(address, &inputConfig,
2261 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002262
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002263 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2264 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2265 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2266 address.string(), "remote-submix");
2267 } else {
2268 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2269 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2270 address.string(), "remote-submix");
2271 }
2272 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002273 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002274 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002275 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2276 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002277
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002278 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002279 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2280 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2281 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2282 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2283 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2284 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002285 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2286 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002287 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2288 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002289 } else {
2290 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002291 }
2292 break;
2293 }
2294 }
2295
2296 if (res != NO_ERROR) {
2297 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002298 i, device, address.string());
2299 res = INVALID_OPERATION;
2300 break;
2301 } else if (!foundOutput) {
2302 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2303 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002304 res = INVALID_OPERATION;
2305 break;
2306 }
Eric Laurentc722f302014-12-10 11:21:49 -08002307 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002308 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002309 if (res != NO_ERROR) {
2310 unregisterPolicyMixes(mixes);
2311 }
2312 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002313}
2314
2315status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2316{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002317 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002318 status_t res = NO_ERROR;
2319 sp<HwModule> rSubmixModule;
2320 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002321 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002322 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002323
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002324 if (rSubmixModule == 0) {
2325 for (size_t j = 0; i < mHwModules.size(); j++) {
2326 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2327 && mHwModules[j]->mHandle != 0) {
2328 rSubmixModule = mHwModules[j];
2329 break;
2330 }
2331 }
2332 }
2333 if (rSubmixModule == 0) {
2334 res = INVALID_OPERATION;
2335 continue;
2336 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002337
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002338 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002339
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002340 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2341 res = INVALID_OPERATION;
2342 continue;
2343 }
2344
2345 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2346 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2347 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2348 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2349 address.string(), "remote-submix");
2350 }
2351 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2352 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2353 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2354 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2355 address.string(), "remote-submix");
2356 }
2357 rSubmixModule->removeOutputProfile(address);
2358 rSubmixModule->removeInputProfile(address);
2359
2360 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2361 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2362 res = INVALID_OPERATION;
2363 continue;
2364 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002365 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002366 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002367 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002368}
2369
Eric Laurente552edb2014-03-10 17:42:56 -07002370
Eric Laurente0720872014-03-11 09:30:41 -07002371status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002372{
2373 const size_t SIZE = 256;
2374 char buffer[SIZE];
2375 String8 result;
2376
2377 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2378 result.append(buffer);
2379
Eric Laurent87ffa392015-05-22 10:32:38 -07002380 snprintf(buffer, SIZE, " Primary Output: %d\n",
2381 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002382 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002383 std::string stateLiteral;
2384 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2385 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002386 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002387 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002388 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002389 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002390 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002391 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002392 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002393 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002394 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002395 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002396 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002397 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002398 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002399 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002400 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002401 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2402 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2403 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002404 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2405 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002406 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2407 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002408
François Gaffie2110e042015-03-24 08:41:51 +01002409 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002410
François Gaffie112b0af2015-11-19 16:13:25 +01002411 mAvailableOutputDevices.dump(fd, String8("Available output"));
2412 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002413 mHwModules.dump(fd);
2414 mOutputs.dump(fd);
2415 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002416 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002417 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002418 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002419
2420 return NO_ERROR;
2421}
2422
2423// This function checks for the parameters which can be offloaded.
2424// This can be enhanced depending on the capability of the DSP and policy
2425// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002426bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002427{
2428 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002429 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002430 offloadInfo.sample_rate, offloadInfo.channel_mask,
2431 offloadInfo.format,
2432 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2433 offloadInfo.has_video);
2434
Andy Hung2ddee192015-12-18 17:34:44 -08002435 if (mMasterMono) {
2436 return false; // no offloading if mono is set.
2437 }
2438
Eric Laurente552edb2014-03-10 17:42:56 -07002439 // Check if offload has been disabled
2440 char propValue[PROPERTY_VALUE_MAX];
2441 if (property_get("audio.offload.disable", propValue, "0")) {
2442 if (atoi(propValue) != 0) {
2443 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2444 return false;
2445 }
2446 }
2447
2448 // Check if stream type is music, then only allow offload as of now.
2449 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2450 {
2451 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2452 return false;
2453 }
2454
2455 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002456 const bool allowOffloadWithVideo =
2457 property_get_bool("audio.offload.video", false /* default_value */);
2458 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002459 ALOGV("isOffloadSupported: has_video == true, returning false");
2460 return false;
2461 }
2462
2463 //If duration is less than minimum value defined in property, return false
2464 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2465 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2466 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2467 return false;
2468 }
2469 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2470 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2471 return false;
2472 }
2473
2474 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2475 // creating an offloaded track and tearing it down immediately after start when audioflinger
2476 // detects there is an active non offloadable effect.
2477 // FIXME: We should check the audio session here but we do not have it in this context.
2478 // This may prevent offloading in rare situations where effects are left active by apps
2479 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002480 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002481 return false;
2482 }
2483
2484 // See if there is a profile to support this.
2485 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002486 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002487 offloadInfo.sample_rate,
2488 offloadInfo.format,
2489 offloadInfo.channel_mask,
2490 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002491 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2492 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002493}
2494
Eric Laurent6a94d692014-05-20 11:18:06 -07002495status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2496 audio_port_type_t type,
2497 unsigned int *num_ports,
2498 struct audio_port *ports,
2499 unsigned int *generation)
2500{
2501 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2502 generation == NULL) {
2503 return BAD_VALUE;
2504 }
2505 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2506 if (ports == NULL) {
2507 *num_ports = 0;
2508 }
2509
2510 size_t portsWritten = 0;
2511 size_t portsMax = *num_ports;
2512 *num_ports = 0;
2513 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002514 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2515 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002516 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002517 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2518 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2519 continue;
2520 }
2521 if (portsWritten < portsMax) {
2522 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2523 }
2524 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002525 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002526 }
2527 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002528 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2529 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2530 continue;
2531 }
2532 if (portsWritten < portsMax) {
2533 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2534 }
2535 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002536 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002537 }
2538 }
2539 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2540 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2541 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2542 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2543 }
2544 *num_ports += mInputs.size();
2545 }
2546 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002547 size_t numOutputs = 0;
2548 for (size_t i = 0; i < mOutputs.size(); i++) {
2549 if (!mOutputs[i]->isDuplicated()) {
2550 numOutputs++;
2551 if (portsWritten < portsMax) {
2552 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2553 }
2554 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002555 }
Eric Laurent84c70242014-06-23 08:46:27 -07002556 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002557 }
2558 }
2559 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002560 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002561 return NO_ERROR;
2562}
2563
2564status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2565{
2566 return NO_ERROR;
2567}
2568
Eric Laurent6a94d692014-05-20 11:18:06 -07002569status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2570 audio_patch_handle_t *handle,
2571 uid_t uid)
2572{
2573 ALOGV("createAudioPatch()");
2574
2575 if (handle == NULL || patch == NULL) {
2576 return BAD_VALUE;
2577 }
2578 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2579
Eric Laurent874c42872014-08-08 15:13:39 -07002580 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2581 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2582 return BAD_VALUE;
2583 }
2584 // only one source per audio patch supported for now
2585 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002586 return INVALID_OPERATION;
2587 }
Eric Laurent874c42872014-08-08 15:13:39 -07002588
2589 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002590 return INVALID_OPERATION;
2591 }
Eric Laurent874c42872014-08-08 15:13:39 -07002592 for (size_t i = 0; i < patch->num_sinks; i++) {
2593 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2594 return INVALID_OPERATION;
2595 }
2596 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002597
2598 sp<AudioPatch> patchDesc;
2599 ssize_t index = mAudioPatches.indexOfKey(*handle);
2600
Eric Laurent6a94d692014-05-20 11:18:06 -07002601 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2602 patch->sources[0].role,
2603 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002604#if LOG_NDEBUG == 0
2605 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002606 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002607 patch->sinks[i].role,
2608 patch->sinks[i].type);
2609 }
2610#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002611
2612 if (index >= 0) {
2613 patchDesc = mAudioPatches.valueAt(index);
2614 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2615 mUidCached, patchDesc->mUid, uid);
2616 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2617 return INVALID_OPERATION;
2618 }
2619 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002620 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002621 }
2622
2623 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002624 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002625 if (outputDesc == NULL) {
2626 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2627 return BAD_VALUE;
2628 }
Eric Laurent84c70242014-06-23 08:46:27 -07002629 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2630 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002631 if (patchDesc != 0) {
2632 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2633 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2634 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2635 return BAD_VALUE;
2636 }
2637 }
Eric Laurent874c42872014-08-08 15:13:39 -07002638 DeviceVector devices;
2639 for (size_t i = 0; i < patch->num_sinks; i++) {
2640 // Only support mix to devices connection
2641 // TODO add support for mix to mix connection
2642 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2643 ALOGV("createAudioPatch() source mix but sink is not a device");
2644 return INVALID_OPERATION;
2645 }
2646 sp<DeviceDescriptor> devDesc =
2647 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2648 if (devDesc == 0) {
2649 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2650 return BAD_VALUE;
2651 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002652
François Gaffie53615e22015-03-19 09:24:12 +01002653 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002654 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002655 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002656 NULL, // updatedSamplingRate
2657 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002658 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002659 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002660 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002661 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002662 ALOGV("createAudioPatch() profile not supported for device %08x",
2663 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002664 return INVALID_OPERATION;
2665 }
2666 devices.add(devDesc);
2667 }
2668 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002669 return INVALID_OPERATION;
2670 }
Eric Laurent874c42872014-08-08 15:13:39 -07002671
Eric Laurent6a94d692014-05-20 11:18:06 -07002672 // TODO: reconfigure output format and channels here
2673 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002674 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002675 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002676 index = mAudioPatches.indexOfKey(*handle);
2677 if (index >= 0) {
2678 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2679 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2680 }
2681 patchDesc = mAudioPatches.valueAt(index);
2682 patchDesc->mUid = uid;
2683 ALOGV("createAudioPatch() success");
2684 } else {
2685 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2686 return INVALID_OPERATION;
2687 }
2688 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2689 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2690 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002691 // only one sink supported when connecting an input device to a mix
2692 if (patch->num_sinks > 1) {
2693 return INVALID_OPERATION;
2694 }
François Gaffie53615e22015-03-19 09:24:12 +01002695 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002696 if (inputDesc == NULL) {
2697 return BAD_VALUE;
2698 }
2699 if (patchDesc != 0) {
2700 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2701 return BAD_VALUE;
2702 }
2703 }
2704 sp<DeviceDescriptor> devDesc =
2705 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2706 if (devDesc == 0) {
2707 return BAD_VALUE;
2708 }
2709
François Gaffie53615e22015-03-19 09:24:12 +01002710 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002711 devDesc->mAddress,
2712 patch->sinks[0].sample_rate,
2713 NULL, /*updatedSampleRate*/
2714 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002715 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002716 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002717 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002718 // FIXME for the parameter type,
2719 // and the NONE
2720 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002721 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002722 return INVALID_OPERATION;
2723 }
2724 // TODO: reconfigure output format and channels here
2725 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002726 devDesc->type(), inputDesc->mIoHandle);
2727 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002728 index = mAudioPatches.indexOfKey(*handle);
2729 if (index >= 0) {
2730 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2731 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2732 }
2733 patchDesc = mAudioPatches.valueAt(index);
2734 patchDesc->mUid = uid;
2735 ALOGV("createAudioPatch() success");
2736 } else {
2737 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2738 return INVALID_OPERATION;
2739 }
2740 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2741 // device to device connection
2742 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002743 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002744 return BAD_VALUE;
2745 }
2746 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 sp<DeviceDescriptor> srcDeviceDesc =
2748 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002749 if (srcDeviceDesc == 0) {
2750 return BAD_VALUE;
2751 }
Eric Laurent874c42872014-08-08 15:13:39 -07002752
Eric Laurent6a94d692014-05-20 11:18:06 -07002753 //update source and sink with our own data as the data passed in the patch may
2754 // be incomplete.
2755 struct audio_patch newPatch = *patch;
2756 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002757
Eric Laurent874c42872014-08-08 15:13:39 -07002758 for (size_t i = 0; i < patch->num_sinks; i++) {
2759 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2760 ALOGV("createAudioPatch() source device but one sink is not a device");
2761 return INVALID_OPERATION;
2762 }
2763
2764 sp<DeviceDescriptor> sinkDeviceDesc =
2765 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2766 if (sinkDeviceDesc == 0) {
2767 return BAD_VALUE;
2768 }
2769 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2770
Eric Laurent3bcf8592015-04-03 12:13:24 -07002771 // create a software bridge in PatchPanel if:
2772 // - source and sink devices are on differnt HW modules OR
2773 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002774 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002775 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002776 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002777 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002778 return INVALID_OPERATION;
2779 }
Eric Laurent874c42872014-08-08 15:13:39 -07002780 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002781 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002782 // if the sink device is reachable via an opened output stream, request to go via
2783 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002784 audio_io_handle_t output = selectOutput(outputs,
2785 AUDIO_OUTPUT_FLAG_NONE,
2786 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002787 if (output != AUDIO_IO_HANDLE_NONE) {
2788 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2789 if (outputDesc->isDuplicated()) {
2790 return INVALID_OPERATION;
2791 }
2792 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002793 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002794 newPatch.num_sources = 2;
2795 }
Eric Laurent83b88082014-06-20 18:31:16 -07002796 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002797 }
2798 // TODO: check from routing capabilities in config file and other conflicting patches
2799
2800 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2801 if (index >= 0) {
2802 afPatchHandle = patchDesc->mAfPatchHandle;
2803 }
2804
2805 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2806 &afPatchHandle,
2807 0);
2808 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2809 status, afPatchHandle);
2810 if (status == NO_ERROR) {
2811 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002812 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 addAudioPatch(patchDesc->mHandle, patchDesc);
2814 } else {
2815 patchDesc->mPatch = newPatch;
2816 }
2817 patchDesc->mAfPatchHandle = afPatchHandle;
2818 *handle = patchDesc->mHandle;
2819 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002820 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002821 } else {
2822 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2823 status);
2824 return INVALID_OPERATION;
2825 }
2826 } else {
2827 return BAD_VALUE;
2828 }
2829 } else {
2830 return BAD_VALUE;
2831 }
2832 return NO_ERROR;
2833}
2834
2835status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2836 uid_t uid)
2837{
2838 ALOGV("releaseAudioPatch() patch %d", handle);
2839
2840 ssize_t index = mAudioPatches.indexOfKey(handle);
2841
2842 if (index < 0) {
2843 return BAD_VALUE;
2844 }
2845 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2846 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2847 mUidCached, patchDesc->mUid, uid);
2848 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2849 return INVALID_OPERATION;
2850 }
2851
2852 struct audio_patch *patch = &patchDesc->mPatch;
2853 patchDesc->mUid = mUidCached;
2854 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002855 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002856 if (outputDesc == NULL) {
2857 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2858 return BAD_VALUE;
2859 }
2860
Eric Laurentc75307b2015-03-17 15:29:32 -07002861 setOutputDevice(outputDesc,
2862 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002863 true,
2864 0,
2865 NULL);
2866 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2867 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002868 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002869 if (inputDesc == NULL) {
2870 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2871 return BAD_VALUE;
2872 }
2873 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002874 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002875 true,
2876 NULL);
2877 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2879 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2880 status, patchDesc->mAfPatchHandle);
2881 removeAudioPatch(patchDesc->mHandle);
2882 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002883 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002884 } else {
2885 return BAD_VALUE;
2886 }
2887 } else {
2888 return BAD_VALUE;
2889 }
2890 return NO_ERROR;
2891}
2892
2893status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2894 struct audio_patch *patches,
2895 unsigned int *generation)
2896{
François Gaffie53615e22015-03-19 09:24:12 +01002897 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002898 return BAD_VALUE;
2899 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002900 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002901 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002902}
2903
Eric Laurente1715a42014-05-20 11:30:42 -07002904status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002905{
Eric Laurente1715a42014-05-20 11:30:42 -07002906 ALOGV("setAudioPortConfig()");
2907
2908 if (config == NULL) {
2909 return BAD_VALUE;
2910 }
2911 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2912 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002913 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2914 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002915 }
2916
Eric Laurenta121f902014-06-03 13:32:54 -07002917 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002918 if (config->type == AUDIO_PORT_TYPE_MIX) {
2919 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002920 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002921 if (outputDesc == NULL) {
2922 return BAD_VALUE;
2923 }
Eric Laurent84c70242014-06-23 08:46:27 -07002924 ALOG_ASSERT(!outputDesc->isDuplicated(),
2925 "setAudioPortConfig() called on duplicated output %d",
2926 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002927 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002928 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002929 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002930 if (inputDesc == NULL) {
2931 return BAD_VALUE;
2932 }
Eric Laurenta121f902014-06-03 13:32:54 -07002933 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002934 } else {
2935 return BAD_VALUE;
2936 }
2937 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2938 sp<DeviceDescriptor> deviceDesc;
2939 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2940 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2941 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2942 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2943 } else {
2944 return BAD_VALUE;
2945 }
2946 if (deviceDesc == NULL) {
2947 return BAD_VALUE;
2948 }
Eric Laurenta121f902014-06-03 13:32:54 -07002949 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002950 } else {
2951 return BAD_VALUE;
2952 }
2953
Eric Laurenta121f902014-06-03 13:32:54 -07002954 struct audio_port_config backupConfig;
2955 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2956 if (status == NO_ERROR) {
2957 struct audio_port_config newConfig;
2958 audioPortConfig->toAudioPortConfig(&newConfig, config);
2959 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002960 }
Eric Laurenta121f902014-06-03 13:32:54 -07002961 if (status != NO_ERROR) {
2962 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002963 }
Eric Laurente1715a42014-05-20 11:30:42 -07002964
2965 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002966}
2967
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002968void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2969{
Eric Laurentd60560a2015-04-10 11:31:20 -07002970 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002971 clearAudioPatches(uid);
2972 clearSessionRoutes(uid);
2973}
2974
Eric Laurent6a94d692014-05-20 11:18:06 -07002975void AudioPolicyManager::clearAudioPatches(uid_t uid)
2976{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002977 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002978 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2979 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002980 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002981 }
2982 }
2983}
2984
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002985void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2986 audio_io_handle_t ouptutToSkip)
2987{
2988 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2989 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2990 for (size_t j = 0; j < mOutputs.size(); j++) {
2991 if (mOutputs.keyAt(j) == ouptutToSkip) {
2992 continue;
2993 }
2994 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2995 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2996 continue;
2997 }
2998 // If the default device for this strategy is on another output mix,
2999 // invalidate all tracks in this strategy to force re connection.
3000 // Otherwise select new device on the output mix.
3001 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003002 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003003 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3004 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3005 }
3006 }
3007 } else {
3008 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3009 setOutputDevice(outputDesc, newDevice, false);
3010 }
3011 }
3012}
3013
3014void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3015{
3016 // remove output routes associated with this uid
3017 SortedVector<routing_strategy> affectedStrategies;
3018 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3019 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3020 if (route->mUid == uid) {
3021 mOutputRoutes.removeItemsAt(i);
3022 if (route->mDeviceDescriptor != 0) {
3023 affectedStrategies.add(getStrategy(route->mStreamType));
3024 }
3025 }
3026 }
3027 // reroute outputs if necessary
3028 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3029 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3030 }
3031
3032 // remove input routes associated with this uid
3033 SortedVector<audio_source_t> affectedSources;
3034 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3035 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3036 if (route->mUid == uid) {
3037 mInputRoutes.removeItemsAt(i);
3038 if (route->mDeviceDescriptor != 0) {
3039 affectedSources.add(route->mSource);
3040 }
3041 }
3042 }
3043 // reroute inputs if necessary
3044 SortedVector<audio_io_handle_t> inputsToClose;
3045 for (size_t i = 0; i < mInputs.size(); i++) {
3046 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003047 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003048 inputsToClose.add(inputDesc->mIoHandle);
3049 }
3050 }
3051 for (size_t i = 0; i < inputsToClose.size(); i++) {
3052 closeInput(inputsToClose[i]);
3053 }
3054}
3055
Eric Laurentd60560a2015-04-10 11:31:20 -07003056void AudioPolicyManager::clearAudioSources(uid_t uid)
3057{
3058 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3059 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3060 if (sourceDesc->mUid == uid) {
3061 stopAudioSource(mAudioSources.keyAt(i));
3062 }
3063 }
3064}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003065
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003066status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3067 audio_io_handle_t *ioHandle,
3068 audio_devices_t *device)
3069{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003070 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3071 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003072 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003073
François Gaffiedf372692015-03-19 10:43:27 +01003074 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003075}
3076
Eric Laurentd60560a2015-04-10 11:31:20 -07003077status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3078 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003079 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003080 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003081{
Eric Laurentd60560a2015-04-10 11:31:20 -07003082 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3083 if (source == NULL || attributes == NULL || handle == NULL) {
3084 return BAD_VALUE;
3085 }
3086
Glenn Kasten559d4392016-03-29 13:42:57 -07003087 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003088
3089 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3090 source->type != AUDIO_PORT_TYPE_DEVICE) {
3091 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3092 return INVALID_OPERATION;
3093 }
3094
3095 sp<DeviceDescriptor> srcDeviceDesc =
3096 mAvailableInputDevices.getDevice(source->ext.device.type,
3097 String8(source->ext.device.address));
3098 if (srcDeviceDesc == 0) {
3099 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3100 return BAD_VALUE;
3101 }
3102 sp<AudioSourceDescriptor> sourceDesc =
3103 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3104
3105 struct audio_patch dummyPatch;
3106 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3107 sourceDesc->mPatchDesc = patchDesc;
3108
3109 status_t status = connectAudioSource(sourceDesc);
3110 if (status == NO_ERROR) {
3111 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3112 *handle = sourceDesc->getHandle();
3113 }
3114 return status;
3115}
3116
3117status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3118{
3119 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3120
3121 // make sure we only have one patch per source.
3122 disconnectAudioSource(sourceDesc);
3123
3124 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003125 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003126 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3127
3128 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3129 sp<DeviceDescriptor> sinkDeviceDesc =
3130 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3131
3132 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3133 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3134
3135 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3136 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003137 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003138 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3139 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3140 // create patch between src device and output device
3141 // create Hwoutput and add to mHwOutputs
3142 } else {
3143 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3144 audio_io_handle_t output =
3145 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3146 if (output == AUDIO_IO_HANDLE_NONE) {
3147 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3148 return INVALID_OPERATION;
3149 }
3150 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3151 if (outputDesc->isDuplicated()) {
3152 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3153 return INVALID_OPERATION;
3154 }
3155 // create a special patch with no sink and two sources:
3156 // - the second source indicates to PatchPanel through which output mix this patch should
3157 // be connected as well as the stream type for volume control
3158 // - the sink is defined by whatever output device is currently selected for the output
3159 // though which this patch is routed.
3160 patch->num_sinks = 0;
3161 patch->num_sources = 2;
3162 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3163 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3164 patch->sources[1].ext.mix.usecase.stream = stream;
3165 status_t status = mpClientInterface->createAudioPatch(patch,
3166 &afPatchHandle,
3167 0);
3168 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3169 status, afPatchHandle);
3170 if (status != NO_ERROR) {
3171 ALOGW("%s patch panel could not connect device patch, error %d",
3172 __FUNCTION__, status);
3173 return INVALID_OPERATION;
3174 }
3175 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003176 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003177
3178 if (status != NO_ERROR) {
3179 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3180 return status;
3181 }
3182 sourceDesc->mSwOutput = outputDesc;
3183 if (delayMs != 0) {
3184 usleep(delayMs * 1000);
3185 }
3186 }
3187
3188 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3189 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3190
3191 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003192}
3193
Glenn Kasten559d4392016-03-29 13:42:57 -07003194status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003195{
Eric Laurentd60560a2015-04-10 11:31:20 -07003196 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3197 ALOGV("%s handle %d", __FUNCTION__, handle);
3198 if (sourceDesc == 0) {
3199 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3200 return BAD_VALUE;
3201 }
3202 status_t status = disconnectAudioSource(sourceDesc);
3203
3204 mAudioSources.removeItem(handle);
3205 return status;
3206}
3207
Andy Hung2ddee192015-12-18 17:34:44 -08003208status_t AudioPolicyManager::setMasterMono(bool mono)
3209{
3210 if (mMasterMono == mono) {
3211 return NO_ERROR;
3212 }
3213 mMasterMono = mono;
3214 // if enabling mono we close all offloaded devices, which will invalidate the
3215 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3216 // for recreating the new AudioTrack as non-offloaded PCM.
3217 //
3218 // If disabling mono, we leave all tracks as is: we don't know which clients
3219 // and tracks are able to be recreated as offloaded. The next "song" should
3220 // play back offloaded.
3221 if (mMasterMono) {
3222 Vector<audio_io_handle_t> offloaded;
3223 for (size_t i = 0; i < mOutputs.size(); ++i) {
3224 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3225 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3226 offloaded.push(desc->mIoHandle);
3227 }
3228 }
3229 for (size_t i = 0; i < offloaded.size(); ++i) {
3230 closeOutput(offloaded[i]);
3231 }
3232 }
3233 // update master mono for all remaining outputs
3234 for (size_t i = 0; i < mOutputs.size(); ++i) {
3235 updateMono(mOutputs.keyAt(i));
3236 }
3237 return NO_ERROR;
3238}
3239
3240status_t AudioPolicyManager::getMasterMono(bool *mono)
3241{
3242 *mono = mMasterMono;
3243 return NO_ERROR;
3244}
3245
Eric Laurentd60560a2015-04-10 11:31:20 -07003246status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3247{
3248 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3249
3250 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3251 if (patchDesc == 0) {
3252 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3253 sourceDesc->mPatchDesc->mHandle);
3254 return BAD_VALUE;
3255 }
3256 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3257
Eric Laurent28d09f02016-03-08 10:43:05 -08003258 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003259 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3260 if (swOutputDesc != 0) {
3261 stopSource(swOutputDesc, stream, false);
3262 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3263 } else {
3264 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3265 if (hwOutputDesc != 0) {
3266 // release patch between src device and output device
3267 // close Hwoutput and remove from mHwOutputs
3268 } else {
3269 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3270 }
3271 }
3272 return NO_ERROR;
3273}
3274
3275sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3276 audio_io_handle_t output, routing_strategy strategy)
3277{
3278 sp<AudioSourceDescriptor> source;
3279 for (size_t i = 0; i < mAudioSources.size(); i++) {
3280 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3281 routing_strategy sourceStrategy =
3282 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3283 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3284 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3285 source = sourceDesc;
3286 break;
3287 }
3288 }
3289 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003290}
3291
Eric Laurente552edb2014-03-10 17:42:56 -07003292// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003293// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003294// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003295uint32_t AudioPolicyManager::nextAudioPortGeneration()
3296{
3297 return android_atomic_inc(&mAudioPortGeneration);
3298}
3299
Eric Laurente0720872014-03-11 09:30:41 -07003300AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003301 :
3302#ifdef AUDIO_POLICY_TEST
3303 Thread(false),
3304#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003305 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003306 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003307 mAudioPortGeneration(1),
3308 mBeaconMuteRefCount(0),
3309 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003310 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003311 mTtsOutputAvailable(false),
3312 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003313{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003314 mUidCached = getuid();
3315 mpClientInterface = clientInterface;
3316
3317 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3318 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3319 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3320 bool speakerDrcEnabled = false;
3321
3322#ifdef USE_XML_AUDIO_POLICY_CONF
3323 mVolumeCurves = new VolumeCurvesCollection();
3324 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3325 mDefaultOutputDevice, speakerDrcEnabled,
3326 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3327 PolicySerializer serializer;
3328 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3329#else
3330 mVolumeCurves = new StreamDescriptorCollection();
3331 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3332 mDefaultOutputDevice, speakerDrcEnabled);
3333 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3334 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3335#endif
3336 ALOGE("could not load audio policy configuration file, setting defaults");
3337 config.setDefault();
3338 }
3339 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3340 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3341
3342 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003343 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3344 if (!engineInstance) {
3345 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3346 return;
3347 }
3348 // Retrieve the Policy Manager Interface
3349 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3350 if (mEngine == NULL) {
3351 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3352 return;
3353 }
3354 mEngine->setObserver(this);
3355 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003356 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003357 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3358
Eric Laurent3a4311c2014-03-17 12:00:47 -07003359 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003360 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003361 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3362 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003363 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003364 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003365 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003366 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003367 continue;
3368 }
3369 // open all output streams needed to access attached devices
3370 // except for direct output streams that are only opened when they are actually
3371 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003372 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003373 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3374 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003375 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003376
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003377 if (!outProfile->hasSupportedDevices()) {
3378 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003379 continue;
3380 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003381 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003382 mTtsOutputAvailable = true;
3383 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003384
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003385 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003386 continue;
3387 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003388 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003389 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3390 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003391 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003392 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003393 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003394 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003395 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003396 if ((profileType & outputDeviceTypes) == 0) {
3397 continue;
3398 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003399 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3400 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003401 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3402 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3403 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3404 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003405
3406 outputDesc->mDevice = profileType;
3407 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3408 config.sample_rate = outputDesc->mSamplingRate;
3409 config.channel_mask = outputDesc->mChannelMask;
3410 config.format = outputDesc->mFormat;
3411 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003412 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003413 &output,
3414 &config,
3415 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003416 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003417 &outputDesc->mLatency,
3418 outputDesc->mFlags);
3419
3420 if (status != NO_ERROR) {
3421 ALOGW("Cannot open output stream for device %08x on hw module %s",
3422 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003423 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003424 } else {
3425 outputDesc->mSamplingRate = config.sample_rate;
3426 outputDesc->mChannelMask = config.channel_mask;
3427 outputDesc->mFormat = config.format;
3428
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003429 for (size_t k = 0; k < supportedDevices.size(); k++) {
3430 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003431 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003432 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3433 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003434 }
3435 }
3436 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003437 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003438 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003439 }
3440 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003441 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003442 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003443 true,
3444 0,
3445 NULL,
3446 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003447 }
Eric Laurente552edb2014-03-10 17:42:56 -07003448 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003449 // open input streams needed to access attached devices to validate
3450 // mAvailableInputDevices list
3451 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3452 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003453 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003454
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003455 if (!inProfile->hasSupportedDevices()) {
3456 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003457 continue;
3458 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003459 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003460 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003461 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3462
Eric Laurentd78f1532014-09-16 16:38:20 -07003463 if ((profileType & inputDeviceTypes) == 0) {
3464 continue;
3465 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003466 sp<AudioInputDescriptor> inputDesc =
3467 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003468
Eric Laurentd78f1532014-09-16 16:38:20 -07003469 inputDesc->mDevice = profileType;
3470
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003471 // find the address
3472 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3473 // the inputs vector must be of size 1, but we don't want to crash here
3474 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3475 : String8("");
3476 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3477 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3478
Eric Laurentd78f1532014-09-16 16:38:20 -07003479 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3480 config.sample_rate = inputDesc->mSamplingRate;
3481 config.channel_mask = inputDesc->mChannelMask;
3482 config.format = inputDesc->mFormat;
3483 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003484 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003485 &input,
3486 &config,
3487 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003488 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003489 AUDIO_SOURCE_MIC,
3490 AUDIO_INPUT_FLAG_NONE);
3491
3492 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003493 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3494 for (size_t k = 0; k < supportedDevices.size(); k++) {
3495 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003496 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003497 if (index >= 0) {
3498 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3499 if (!devDesc->isAttached()) {
3500 devDesc->attach(mHwModules[i]);
3501 devDesc->importAudioPort(inProfile);
3502 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003503 }
3504 }
3505 mpClientInterface->closeInput(input);
3506 } else {
3507 ALOGW("Cannot open input stream for device %08x on hw module %s",
3508 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003509 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003510 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003511 }
3512 }
3513 // make sure all attached devices have been allocated a unique ID
3514 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003515 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003516 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003517 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3518 continue;
3519 }
François Gaffie2110e042015-03-24 08:41:51 +01003520 // The device is now validated and can be appended to the available devices of the engine
3521 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003523 i++;
3524 }
3525 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003526 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003527 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003528 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3529 continue;
3530 }
François Gaffie2110e042015-03-24 08:41:51 +01003531 // The device is now validated and can be appended to the available devices of the engine
3532 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3533 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003534 i++;
3535 }
3536 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003537 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003538 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003539 }
Eric Laurente552edb2014-03-10 17:42:56 -07003540
3541 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3542
3543 updateDevicesAndOutputs();
3544
3545#ifdef AUDIO_POLICY_TEST
3546 if (mPrimaryOutput != 0) {
3547 AudioParameter outputCmd = AudioParameter();
3548 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003549 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003550
3551 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3552 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003553 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3554 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003555 mTestLatencyMs = 0;
3556 mCurOutput = 0;
3557 mDirectOutput = false;
3558 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3559 mTestOutputs[i] = 0;
3560 }
3561
3562 const size_t SIZE = 256;
3563 char buffer[SIZE];
3564 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3565 run(buffer, ANDROID_PRIORITY_AUDIO);
3566 }
3567#endif //AUDIO_POLICY_TEST
3568}
3569
Eric Laurente0720872014-03-11 09:30:41 -07003570AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003571{
3572#ifdef AUDIO_POLICY_TEST
3573 exit();
3574#endif //AUDIO_POLICY_TEST
3575 for (size_t i = 0; i < mOutputs.size(); i++) {
3576 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003577 }
3578 for (size_t i = 0; i < mInputs.size(); i++) {
3579 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003580 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003581 mAvailableOutputDevices.clear();
3582 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003583 mOutputs.clear();
3584 mInputs.clear();
3585 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003586}
3587
Eric Laurente0720872014-03-11 09:30:41 -07003588status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003589{
Eric Laurent87ffa392015-05-22 10:32:38 -07003590 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003591}
3592
3593#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003594bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003595{
3596 ALOGV("entering threadLoop()");
3597 while (!exitPending())
3598 {
3599 String8 command;
3600 int valueInt;
3601 String8 value;
3602
3603 Mutex::Autolock _l(mLock);
3604 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3605
3606 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3607 AudioParameter param = AudioParameter(command);
3608
3609 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3610 valueInt != 0) {
3611 ALOGV("Test command %s received", command.string());
3612 String8 target;
3613 if (param.get(String8("target"), target) != NO_ERROR) {
3614 target = "Manager";
3615 }
3616 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3617 param.remove(String8("test_cmd_policy_output"));
3618 mCurOutput = valueInt;
3619 }
3620 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3621 param.remove(String8("test_cmd_policy_direct"));
3622 if (value == "false") {
3623 mDirectOutput = false;
3624 } else if (value == "true") {
3625 mDirectOutput = true;
3626 }
3627 }
3628 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3629 param.remove(String8("test_cmd_policy_input"));
3630 mTestInput = valueInt;
3631 }
3632
3633 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3634 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003635 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003636 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003637 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003638 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003639 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003640 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003641 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003642 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003643 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003644 if (target == "Manager") {
3645 mTestFormat = format;
3646 } else if (mTestOutputs[mCurOutput] != 0) {
3647 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003648 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003649 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3650 }
3651 }
3652 }
3653 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3654 param.remove(String8("test_cmd_policy_channels"));
3655 int channels = 0;
3656
3657 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003658 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003659 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003660 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003661 }
3662 if (channels != 0) {
3663 if (target == "Manager") {
3664 mTestChannels = channels;
3665 } else if (mTestOutputs[mCurOutput] != 0) {
3666 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003667 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003668 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3669 }
3670 }
3671 }
3672 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3673 param.remove(String8("test_cmd_policy_sampleRate"));
3674 if (valueInt >= 0 && valueInt <= 96000) {
3675 int samplingRate = valueInt;
3676 if (target == "Manager") {
3677 mTestSamplingRate = samplingRate;
3678 } else if (mTestOutputs[mCurOutput] != 0) {
3679 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003680 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003681 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3682 }
3683 }
3684 }
3685
3686 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3687 param.remove(String8("test_cmd_policy_reopen"));
3688
Eric Laurentc75307b2015-03-17 15:29:32 -07003689 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003690
Eric Laurentc75307b2015-03-17 15:29:32 -07003691 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003692
Eric Laurentc75307b2015-03-17 15:29:32 -07003693 removeOutput(mPrimaryOutput->mIoHandle);
3694 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3695 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003696 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003697 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3698 config.sample_rate = outputDesc->mSamplingRate;
3699 config.channel_mask = outputDesc->mChannelMask;
3700 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003701 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003702 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003703 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003704 &config,
3705 &outputDesc->mDevice,
3706 String8(""),
3707 &outputDesc->mLatency,
3708 outputDesc->mFlags);
3709 if (status != NO_ERROR) {
3710 ALOGE("Failed to reopen hardware output stream, "
3711 "samplingRate: %d, format %d, channels %d",
3712 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003713 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003714 outputDesc->mSamplingRate = config.sample_rate;
3715 outputDesc->mChannelMask = config.channel_mask;
3716 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003717 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003718 AudioParameter outputCmd = AudioParameter();
3719 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003720 mpClientInterface->setParameters(handle, outputCmd.toString());
3721 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003722 }
3723 }
3724
3725
3726 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3727 }
3728 }
3729 return false;
3730}
3731
Eric Laurente0720872014-03-11 09:30:41 -07003732void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003733{
3734 {
3735 AutoMutex _l(mLock);
3736 requestExit();
3737 mWaitWorkCV.signal();
3738 }
3739 requestExitAndWait();
3740}
3741
Eric Laurente0720872014-03-11 09:30:41 -07003742int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003743{
3744 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3745 if (output == mTestOutputs[i]) return i;
3746 }
3747 return 0;
3748}
3749#endif //AUDIO_POLICY_TEST
3750
3751// ---
3752
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003753void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003754{
François Gaffie98cc1912015-03-18 17:52:40 +01003755 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003756 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003757 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003758 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003759}
3760
François Gaffie53615e22015-03-19 09:24:12 +01003761void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3762{
3763 mOutputs.removeItem(output);
3764}
3765
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003766void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003767{
François Gaffie98cc1912015-03-18 17:52:40 +01003768 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003769 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003770 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003771}
Eric Laurente552edb2014-03-10 17:42:56 -07003772
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003773void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003774 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003775 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003776 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003777 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003778 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003779 if (devDesc != 0) {
3780 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3781 desc->mIoHandle, address.string());
3782 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003783 }
3784}
3785
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003786status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003787 audio_policy_dev_state_t state,
3788 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003789 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003790{
François Gaffie53615e22015-03-19 09:24:12 +01003791 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003792 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003793
3794 if (audio_device_is_digital(device)) {
3795 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003796 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003797 }
Eric Laurente552edb2014-03-10 17:42:56 -07003798
Eric Laurent3b73df72014-03-11 09:06:29 -07003799 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003800 // first list already open outputs that can be routed to this device
3801 for (size_t i = 0; i < mOutputs.size(); i++) {
3802 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003803 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003804 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003805 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3806 outputs.add(mOutputs.keyAt(i));
3807 } else {
3808 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003809 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003810 }
Eric Laurente552edb2014-03-10 17:42:56 -07003811 }
3812 }
3813 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003814 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003815 for (size_t i = 0; i < mHwModules.size(); i++)
3816 {
3817 if (mHwModules[i]->mHandle == 0) {
3818 continue;
3819 }
3820 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3821 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003822 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003823 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003824 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003825 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003826 profiles.add(profile);
3827 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3828 }
Eric Laurente552edb2014-03-10 17:42:56 -07003829 }
3830 }
3831 }
3832
Eric Laurent7b279bb2015-12-14 10:18:23 -08003833 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003834
Eric Laurente552edb2014-03-10 17:42:56 -07003835 if (profiles.isEmpty() && outputs.isEmpty()) {
3836 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3837 return BAD_VALUE;
3838 }
3839
3840 // open outputs for matching profiles if needed. Direct outputs are also opened to
3841 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3842 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003843 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003844
3845 // nothing to do if one output is already opened for this profile
3846 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003847 for (j = 0; j < outputs.size(); j++) {
3848 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003849 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003850 // matching profile: save the sample rates, format and channel masks supported
3851 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003852 if (audio_device_is_digital(device)) {
3853 devDesc->importAudioPort(profile);
3854 }
Eric Laurente552edb2014-03-10 17:42:56 -07003855 break;
3856 }
3857 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003858 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003859 continue;
3860 }
3861
Eric Laurent83b88082014-06-20 18:31:16 -07003862 ALOGV("opening output for device %08x with params %s profile %p",
3863 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003864 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003865 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003866 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3867 config.sample_rate = desc->mSamplingRate;
3868 config.channel_mask = desc->mChannelMask;
3869 config.format = desc->mFormat;
3870 config.offload_info.sample_rate = desc->mSamplingRate;
3871 config.offload_info.channel_mask = desc->mChannelMask;
3872 config.offload_info.format = desc->mFormat;
3873 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003874 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003875 &output,
3876 &config,
3877 &desc->mDevice,
3878 address,
3879 &desc->mLatency,
3880 desc->mFlags);
3881 if (status == NO_ERROR) {
3882 desc->mSamplingRate = config.sample_rate;
3883 desc->mChannelMask = config.channel_mask;
3884 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003885
Eric Laurentd4692962014-05-05 18:13:44 -07003886 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003887 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003888 char *param = audio_device_address_to_parameter(device, address);
3889 mpClientInterface->setParameters(output, String8(param));
3890 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003891 }
Phil Burk00eeb322016-03-31 12:41:00 -07003892 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003893 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003894 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003895 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003896 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003897 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003898 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003899 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003900 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003901 config.offload_info.sample_rate = config.sample_rate;
3902 config.offload_info.channel_mask = config.channel_mask;
3903 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003904 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003905 &output,
3906 &config,
3907 &desc->mDevice,
3908 address,
3909 &desc->mLatency,
3910 desc->mFlags);
3911 if (status == NO_ERROR) {
3912 desc->mSamplingRate = config.sample_rate;
3913 desc->mChannelMask = config.channel_mask;
3914 desc->mFormat = config.format;
3915 } else {
3916 output = AUDIO_IO_HANDLE_NONE;
3917 }
Eric Laurentd4692962014-05-05 18:13:44 -07003918 }
3919
Eric Laurentcf2c0212014-07-25 16:20:43 -07003920 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003921 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003922 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003923 sp<AudioPolicyMix> policyMix;
3924 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003925 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3926 address.string());
3927 }
François Gaffie036e1e92015-03-19 10:16:24 +01003928 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003929 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003930
Eric Laurent87ffa392015-05-22 10:32:38 -07003931 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3932 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003933 // no duplicated output for direct outputs and
3934 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003935 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003936
Eric Laurentd4692962014-05-05 18:13:44 -07003937 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003938 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003939
Eric Laurentd4692962014-05-05 18:13:44 -07003940 //TODO: configure audio effect output stage here
3941
3942 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003943 duplicatedOutput =
3944 mpClientInterface->openDuplicateOutput(output,
3945 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003946 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003947 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003948 sp<SwAudioOutputDescriptor> dupOutputDesc =
3949 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3950 dupOutputDesc->mOutput1 = mPrimaryOutput;
3951 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003952 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3953 dupOutputDesc->mFormat = desc->mFormat;
3954 dupOutputDesc->mChannelMask = desc->mChannelMask;
3955 dupOutputDesc->mLatency = desc->mLatency;
3956 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003957 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003958 } else {
3959 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003960 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003961 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003962 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003963 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003964 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003965 }
Eric Laurente552edb2014-03-10 17:42:56 -07003966 }
3967 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003968 } else {
3969 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003970 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003971 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003972 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003973 profiles.removeAt(profile_index);
3974 profile_index--;
3975 } else {
3976 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003977 // Load digital format info only for digital devices
3978 if (audio_device_is_digital(device)) {
3979 devDesc->importAudioPort(profile);
3980 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003981
François Gaffie53615e22015-03-19 09:24:12 +01003982 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003983 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3984 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003985 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003986 NULL/*patch handle*/, address.string());
3987 }
Eric Laurente552edb2014-03-10 17:42:56 -07003988 ALOGV("checkOutputsForDevice(): adding output %d", output);
3989 }
3990 }
3991
3992 if (profiles.isEmpty()) {
3993 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3994 return BAD_VALUE;
3995 }
Eric Laurentd4692962014-05-05 18:13:44 -07003996 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003997 // check if one opened output is not needed any more after disconnecting one device
3998 for (size_t i = 0; i < mOutputs.size(); i++) {
3999 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004000 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004001 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004002 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004003 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004004 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004005 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004006 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4007 mOutputs.keyAt(i));
4008 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004009 }
Eric Laurente552edb2014-03-10 17:42:56 -07004010 }
4011 }
Eric Laurentd4692962014-05-05 18:13:44 -07004012 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004013 for (size_t i = 0; i < mHwModules.size(); i++)
4014 {
4015 if (mHwModules[i]->mHandle == 0) {
4016 continue;
4017 }
4018 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4019 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004020 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004021 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004022 ALOGV("checkOutputsForDevice(): "
4023 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004024 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004025 }
4026 }
4027 }
4028 }
4029 return NO_ERROR;
4030}
4031
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004032status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004033 audio_policy_dev_state_t state,
4034 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004035 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004036{
Paul McLean9080a4c2015-06-18 08:24:02 -07004037 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004038 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004039
4040 if (audio_device_is_digital(device)) {
4041 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004042 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004043 }
4044
Eric Laurentd4692962014-05-05 18:13:44 -07004045 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4046 // first list already open inputs that can be routed to this device
4047 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4048 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004049 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004050 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4051 inputs.add(mInputs.keyAt(input_index));
4052 }
4053 }
4054
4055 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004056 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004057 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4058 {
4059 if (mHwModules[module_idx]->mHandle == 0) {
4060 continue;
4061 }
4062 for (size_t profile_index = 0;
4063 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4064 profile_index++)
4065 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004066 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4067
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004068 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004069 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004070 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004071 profiles.add(profile);
4072 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4073 profile_index, module_idx);
4074 }
Eric Laurentd4692962014-05-05 18:13:44 -07004075 }
4076 }
4077 }
4078
4079 if (profiles.isEmpty() && inputs.isEmpty()) {
4080 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4081 return BAD_VALUE;
4082 }
4083
4084 // open inputs for matching profiles if needed. Direct inputs are also opened to
4085 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4086 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4087
Eric Laurent1c333e22014-05-20 10:48:17 -07004088 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004089 // nothing to do if one input is already opened for this profile
4090 size_t input_index;
4091 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4092 desc = mInputs.valueAt(input_index);
4093 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004094 if (audio_device_is_digital(device)) {
4095 devDesc->importAudioPort(profile);
4096 }
Eric Laurentd4692962014-05-05 18:13:44 -07004097 break;
4098 }
4099 }
4100 if (input_index != mInputs.size()) {
4101 continue;
4102 }
4103
4104 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4105 desc = new AudioInputDescriptor(profile);
4106 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004107 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4108 config.sample_rate = desc->mSamplingRate;
4109 config.channel_mask = desc->mChannelMask;
4110 config.format = desc->mFormat;
4111 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004112 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004113 &input,
4114 &config,
4115 &desc->mDevice,
4116 address,
4117 AUDIO_SOURCE_MIC,
4118 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004119
Eric Laurentcf2c0212014-07-25 16:20:43 -07004120 if (status == NO_ERROR) {
4121 desc->mSamplingRate = config.sample_rate;
4122 desc->mChannelMask = config.channel_mask;
4123 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004124
Eric Laurentd4692962014-05-05 18:13:44 -07004125 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004126 char *param = audio_device_address_to_parameter(device, address);
4127 mpClientInterface->setParameters(input, String8(param));
4128 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004129 }
Phil Burk00eeb322016-03-31 12:41:00 -07004130 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004131 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004132 ALOGW("checkInputsForDevice() direct input missing param");
4133 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004134 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004135 }
4136
4137 if (input != 0) {
4138 addInput(input, desc);
4139 }
4140 } // endif input != 0
4141
Eric Laurentcf2c0212014-07-25 16:20:43 -07004142 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004143 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004144 profiles.removeAt(profile_index);
4145 profile_index--;
4146 } else {
4147 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004148 if (audio_device_is_digital(device)) {
4149 devDesc->importAudioPort(profile);
4150 }
Eric Laurentd4692962014-05-05 18:13:44 -07004151 ALOGV("checkInputsForDevice(): adding input %d", input);
4152 }
4153 } // end scan profiles
4154
4155 if (profiles.isEmpty()) {
4156 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4157 return BAD_VALUE;
4158 }
4159 } else {
4160 // Disconnect
4161 // check if one opened input is not needed any more after disconnecting one device
4162 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4163 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004164 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004165 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4166 mInputs.keyAt(input_index));
4167 inputs.add(mInputs.keyAt(input_index));
4168 }
4169 }
4170 // Clear any profiles associated with the disconnected device.
4171 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4172 if (mHwModules[module_index]->mHandle == 0) {
4173 continue;
4174 }
4175 for (size_t profile_index = 0;
4176 profile_index < mHwModules[module_index]->mInputProfiles.size();
4177 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004178 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004179 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004180 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004181 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004182 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004183 }
4184 }
4185 }
4186 } // end disconnect
4187
4188 return NO_ERROR;
4189}
4190
4191
Eric Laurente0720872014-03-11 09:30:41 -07004192void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004193{
4194 ALOGV("closeOutput(%d)", output);
4195
Eric Laurentc75307b2015-03-17 15:29:32 -07004196 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004197 if (outputDesc == NULL) {
4198 ALOGW("closeOutput() unknown output %d", output);
4199 return;
4200 }
François Gaffie036e1e92015-03-19 10:16:24 +01004201 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004202
Eric Laurente552edb2014-03-10 17:42:56 -07004203 // look for duplicated outputs connected to the output being removed.
4204 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004205 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004206 if (dupOutputDesc->isDuplicated() &&
4207 (dupOutputDesc->mOutput1 == outputDesc ||
4208 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004209 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004210 if (dupOutputDesc->mOutput1 == outputDesc) {
4211 outputDesc2 = dupOutputDesc->mOutput2;
4212 } else {
4213 outputDesc2 = dupOutputDesc->mOutput1;
4214 }
4215 // As all active tracks on duplicated output will be deleted,
4216 // and as they were also referenced on the other output, the reference
4217 // count for their stream type must be adjusted accordingly on
4218 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004219 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004220 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004221 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004222 }
4223 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4224 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4225
4226 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004227 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004228 }
4229 }
4230
Eric Laurent05b90f82014-08-27 15:32:29 -07004231 nextAudioPortGeneration();
4232
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004233 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004234 if (index >= 0) {
4235 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004236 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004237 mAudioPatches.removeItemsAt(index);
4238 mpClientInterface->onAudioPatchListUpdate();
4239 }
4240
Eric Laurente552edb2014-03-10 17:42:56 -07004241 AudioParameter param;
4242 param.add(String8("closing"), String8("true"));
4243 mpClientInterface->setParameters(output, param.toString());
4244
4245 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004246 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004247 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004248}
4249
4250void AudioPolicyManager::closeInput(audio_io_handle_t input)
4251{
4252 ALOGV("closeInput(%d)", input);
4253
4254 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4255 if (inputDesc == NULL) {
4256 ALOGW("closeInput() unknown input %d", input);
4257 return;
4258 }
4259
Eric Laurent6a94d692014-05-20 11:18:06 -07004260 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004261
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004262 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004263 if (index >= 0) {
4264 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004265 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004266 mAudioPatches.removeItemsAt(index);
4267 mpClientInterface->onAudioPatchListUpdate();
4268 }
4269
4270 mpClientInterface->closeInput(input);
4271 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004272}
4273
Eric Laurentc75307b2015-03-17 15:29:32 -07004274SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4275 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004276 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004277{
4278 SortedVector<audio_io_handle_t> outputs;
4279
4280 ALOGVV("getOutputsForDevice() device %04x", device);
4281 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004282 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004283 i, openOutputs.valueAt(i)->isDuplicated(),
4284 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004285 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4286 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4287 outputs.add(openOutputs.keyAt(i));
4288 }
4289 }
4290 return outputs;
4291}
4292
Eric Laurente0720872014-03-11 09:30:41 -07004293bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004294 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004295{
4296 if (outputs1.size() != outputs2.size()) {
4297 return false;
4298 }
4299 for (size_t i = 0; i < outputs1.size(); i++) {
4300 if (outputs1[i] != outputs2[i]) {
4301 return false;
4302 }
4303 }
4304 return true;
4305}
4306
Eric Laurente0720872014-03-11 09:30:41 -07004307void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004308{
4309 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4310 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4311 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4312 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4313
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004314 // also take into account external policy-related changes: add all outputs which are
4315 // associated with policies in the "before" and "after" output vectors
4316 ALOGVV("checkOutputForStrategy(): policy related outputs");
4317 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004318 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004319 if (desc != 0 && desc->mPolicyMix != NULL) {
4320 srcOutputs.add(desc->mIoHandle);
4321 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4322 }
4323 }
4324 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004325 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004326 if (desc != 0 && desc->mPolicyMix != NULL) {
4327 dstOutputs.add(desc->mIoHandle);
4328 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4329 }
4330 }
4331
Eric Laurente552edb2014-03-10 17:42:56 -07004332 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4333 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4334 strategy, srcOutputs[0], dstOutputs[0]);
4335 // mute strategy while moving tracks from one output to another
4336 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004337 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004338 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004339 setStrategyMute(strategy, true, desc);
4340 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004341 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004342 sp<AudioSourceDescriptor> source =
4343 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4344 if (source != 0){
4345 connectAudioSource(source);
4346 }
Eric Laurente552edb2014-03-10 17:42:56 -07004347 }
4348
4349 // Move effects associated to this strategy from previous output to new output
4350 if (strategy == STRATEGY_MEDIA) {
4351 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4352 SortedVector<audio_io_handle_t> moved;
4353 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004354 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4355 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4356 effectDesc->mIo != fxOutput) {
4357 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004358 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4359 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004360 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004361 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004362 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004363 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004364 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004365 }
4366 }
4367 }
4368 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004369 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004370 if (getStrategy((audio_stream_type_t)i) == strategy) {
4371 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004372 }
4373 }
4374 }
4375}
4376
Eric Laurente0720872014-03-11 09:30:41 -07004377void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004378{
François Gaffie2110e042015-03-24 08:41:51 +01004379 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004380 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004381 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004382 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004383 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004384 checkOutputForStrategy(STRATEGY_SONIFICATION);
4385 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004386 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004387 checkOutputForStrategy(STRATEGY_MEDIA);
4388 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004389 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004390}
4391
Eric Laurente0720872014-03-11 09:30:41 -07004392void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004393{
François Gaffie53615e22015-03-19 09:24:12 +01004394 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004395 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004396 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004397 return;
4398 }
4399
Eric Laurent3a4311c2014-03-17 12:00:47 -07004400 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004401 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4402 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4403 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004404
4405 // if suspended, restore A2DP output if:
4406 // ((SCO device is NOT connected) ||
4407 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4408 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004409 //
Eric Laurentf732e072016-08-03 19:30:28 -07004410 // if not suspended, suspend A2DP output if:
4411 // (SCO device is connected) &&
4412 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4413 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004414 //
4415 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004416 if (!isScoConnected ||
4417 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4418 AUDIO_POLICY_FORCE_BT_SCO) &&
4419 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4420 AUDIO_POLICY_FORCE_BT_SCO) &&
4421 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004422 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004423
4424 mpClientInterface->restoreOutput(a2dpOutput);
4425 mA2dpSuspended = false;
4426 }
4427 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004428 if (isScoConnected &&
4429 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4430 AUDIO_POLICY_FORCE_BT_SCO) ||
4431 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4432 AUDIO_POLICY_FORCE_BT_SCO) ||
4433 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004434 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004435
4436 mpClientInterface->suspendOutput(a2dpOutput);
4437 mA2dpSuspended = true;
4438 }
4439 }
4440}
4441
Eric Laurentc75307b2015-03-17 15:29:32 -07004442audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4443 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004444{
4445 audio_devices_t device = AUDIO_DEVICE_NONE;
4446
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004447 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004448 if (index >= 0) {
4449 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4450 if (patchDesc->mUid != mUidCached) {
4451 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004452 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004453 return outputDesc->device();
4454 }
4455 }
4456
Eric Laurente552edb2014-03-10 17:42:56 -07004457 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004458 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004459 // use device for strategy enforced audible
4460 // 2: we are in call or the strategy phone is active on the output:
4461 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004462 // 3: the strategy for enforced audible is active but not enforced on the output:
4463 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004464 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004465 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004466 // 5: the strategy accessibility is active on the output:
4467 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004468 // 6: the strategy "respectful" sonification is active on the output:
4469 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004470 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004471 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004472 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004473 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004474 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004475 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004476 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004477 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004478 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4479 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004480 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004481 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004482 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004483 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004484 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004485 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004486 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4487 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004488 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004489 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004490 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004491 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004492 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004493 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004494 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004495 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004496 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004497 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004498 }
4499
Eric Laurent1c333e22014-05-20 10:48:17 -07004500 ALOGV("getNewOutputDevice() selected device %x", device);
4501 return device;
4502}
4503
Eric Laurentfb66dd92016-01-28 18:32:03 -08004504audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004505{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004506 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004507
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004508 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004509 if (index >= 0) {
4510 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4511 if (patchDesc->mUid != mUidCached) {
4512 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004513 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004514 return inputDesc->mDevice;
4515 }
4516 }
4517
Eric Laurentfb66dd92016-01-28 18:32:03 -08004518 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4519 if (isInCall()) {
4520 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4521 } else if (source != AUDIO_SOURCE_DEFAULT) {
4522 device = getDeviceAndMixForInputSource(source);
4523 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004524
Eric Laurente552edb2014-03-10 17:42:56 -07004525 return device;
4526}
4527
Eric Laurent794fde22016-03-11 09:50:45 -08004528bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4529 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004530 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004531}
4532
Eric Laurente0720872014-03-11 09:30:41 -07004533uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004534 return (uint32_t)getStrategy(stream);
4535}
4536
Eric Laurente0720872014-03-11 09:30:41 -07004537audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004538 // By checking the range of stream before calling getStrategy, we avoid
4539 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4540 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004541 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004542 return AUDIO_DEVICE_NONE;
4543 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004544 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004545 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4546 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004547 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004548 }
Eric Laurent794fde22016-03-11 09:50:45 -08004549 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004550 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004551 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004552 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4553 for (size_t i = 0; i < outputs.size(); i++) {
4554 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004555 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004556 curDevices |= outputDesc->device();
4557 }
4558 }
4559 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004560 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004561
4562 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4563 and doesn't really need to.*/
4564 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4565 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4566 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4567 }
Eric Laurente552edb2014-03-10 17:42:56 -07004568 return devices;
4569}
4570
François Gaffie2110e042015-03-24 08:41:51 +01004571routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4572{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004573 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004574 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004575}
4576
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004577uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4578 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004579 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4580 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4581 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004582 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4583 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4584 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004585 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004586 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004587}
4588
Eric Laurente0720872014-03-11 09:30:41 -07004589void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004590 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004591 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004592 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4593 updateDevicesAndOutputs();
4594 break;
4595 default:
4596 break;
4597 }
4598}
4599
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004600uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004601
4602 // skip beacon mute management if a dedicated TTS output is available
4603 if (mTtsOutputAvailable) {
4604 return 0;
4605 }
4606
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004607 switch(event) {
4608 case STARTING_OUTPUT:
4609 mBeaconMuteRefCount++;
4610 break;
4611 case STOPPING_OUTPUT:
4612 if (mBeaconMuteRefCount > 0) {
4613 mBeaconMuteRefCount--;
4614 }
4615 break;
4616 case STARTING_BEACON:
4617 mBeaconPlayingRefCount++;
4618 break;
4619 case STOPPING_BEACON:
4620 if (mBeaconPlayingRefCount > 0) {
4621 mBeaconPlayingRefCount--;
4622 }
4623 break;
4624 }
4625
4626 if (mBeaconMuteRefCount > 0) {
4627 // any playback causes beacon to be muted
4628 return setBeaconMute(true);
4629 } else {
4630 // no other playback: unmute when beacon starts playing, mute when it stops
4631 return setBeaconMute(mBeaconPlayingRefCount == 0);
4632 }
4633}
4634
4635uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4636 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4637 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4638 // keep track of muted state to avoid repeating mute/unmute operations
4639 if (mBeaconMuted != mute) {
4640 // mute/unmute AUDIO_STREAM_TTS on all outputs
4641 ALOGV("\t muting %d", mute);
4642 uint32_t maxLatency = 0;
4643 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004644 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004645 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004646 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004647 0 /*delay*/, AUDIO_DEVICE_NONE);
4648 const uint32_t latency = desc->latency() * 2;
4649 if (latency > maxLatency) {
4650 maxLatency = latency;
4651 }
4652 }
4653 mBeaconMuted = mute;
4654 return maxLatency;
4655 }
4656 return 0;
4657}
4658
Eric Laurente0720872014-03-11 09:30:41 -07004659audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004660 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004661{
Paul McLeanaa981192015-03-21 09:55:15 -07004662 // Routing
4663 // see if we have an explicit route
4664 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4665 // (getStrategy(stream)).
4666 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4667 // and activity count is non-zero
4668 // the device = the device from the descriptor in the RouteMap, and exit.
4669 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4670 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004671 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4672 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004673 return route->mDeviceDescriptor->type();
4674 }
4675 }
4676
Eric Laurente552edb2014-03-10 17:42:56 -07004677 if (fromCache) {
4678 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4679 strategy, mDeviceForStrategy[strategy]);
4680 return mDeviceForStrategy[strategy];
4681 }
François Gaffie2110e042015-03-24 08:41:51 +01004682 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004683}
4684
Eric Laurente0720872014-03-11 09:30:41 -07004685void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004686{
4687 for (int i = 0; i < NUM_STRATEGIES; i++) {
4688 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4689 }
4690 mPreviousOutputs = mOutputs;
4691}
4692
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004693uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004694 audio_devices_t prevDevice,
4695 uint32_t delayMs)
4696{
4697 // mute/unmute strategies using an incompatible device combination
4698 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4699 // if unmuting, unmute only after the specified delay
4700 if (outputDesc->isDuplicated()) {
4701 return 0;
4702 }
4703
4704 uint32_t muteWaitMs = 0;
4705 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004706 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004707
4708 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4709 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004710 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004711 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4712 bool doMute = false;
4713
4714 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4715 doMute = true;
4716 outputDesc->mStrategyMutedByDevice[i] = true;
4717 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4718 doMute = true;
4719 outputDesc->mStrategyMutedByDevice[i] = false;
4720 }
Eric Laurent99401132014-05-07 19:48:15 -07004721 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004722 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004723 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004724 // skip output if it does not share any device with current output
4725 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4726 == AUDIO_DEVICE_NONE) {
4727 continue;
4728 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004729 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004730 mute ? "muting" : "unmuting", i, curDevice);
4731 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004732 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004733 if (mute) {
4734 // FIXME: should not need to double latency if volume could be applied
4735 // immediately by the audioflinger mixer. We must account for the delay
4736 // between now and the next time the audioflinger thread for this output
4737 // will process a buffer (which corresponds to one buffer size,
4738 // usually 1/2 or 1/4 of the latency).
4739 if (muteWaitMs < desc->latency() * 2) {
4740 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004741 }
4742 }
4743 }
4744 }
4745 }
4746 }
4747
Eric Laurent99401132014-05-07 19:48:15 -07004748 // temporary mute output if device selection changes to avoid volume bursts due to
4749 // different per device volumes
4750 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004751 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4752 // temporary mute duration is conservatively set to 4 times the reported latency
4753 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4754 if (muteWaitMs < tempMuteWaitMs) {
4755 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004756 }
Eric Laurentdc462862016-07-19 12:29:53 -07004757
Eric Laurent99401132014-05-07 19:48:15 -07004758 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004759 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004760 // make sure that we do not start the temporary mute period too early in case of
4761 // delayed device change
4762 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004763 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004764 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004765 }
4766 }
4767 }
4768
Eric Laurente552edb2014-03-10 17:42:56 -07004769 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4770 if (muteWaitMs > delayMs) {
4771 muteWaitMs -= delayMs;
4772 usleep(muteWaitMs * 1000);
4773 return muteWaitMs;
4774 }
4775 return 0;
4776}
4777
Eric Laurentc75307b2015-03-17 15:29:32 -07004778uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004779 audio_devices_t device,
4780 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004781 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004782 audio_patch_handle_t *patchHandle,
4783 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004784{
Eric Laurentc75307b2015-03-17 15:29:32 -07004785 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004786 AudioParameter param;
4787 uint32_t muteWaitMs;
4788
4789 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004790 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4791 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004792 return muteWaitMs;
4793 }
4794 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4795 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004796 if ((device != AUDIO_DEVICE_NONE) &&
4797 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004798 return 0;
4799 }
4800
4801 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004802 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004803
4804 audio_devices_t prevDevice = outputDesc->mDevice;
4805
Paul McLeanaa981192015-03-21 09:55:15 -07004806 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004807
4808 if (device != AUDIO_DEVICE_NONE) {
4809 outputDesc->mDevice = device;
4810 }
4811 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4812
4813 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004814 // the requested device is AUDIO_DEVICE_NONE
4815 // OR the requested device is the same as current device
4816 // AND force is not specified
4817 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004818 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004819 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4820 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004821 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004822 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004823 return muteWaitMs;
4824 }
4825
4826 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004827
Eric Laurente552edb2014-03-10 17:42:56 -07004828 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004829 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004830 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004831 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004832 DeviceVector deviceList;
4833 if ((address == NULL) || (strlen(address) == 0)) {
4834 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4835 } else {
4836 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4837 }
4838
Eric Laurent1c333e22014-05-20 10:48:17 -07004839 if (!deviceList.isEmpty()) {
4840 struct audio_patch patch;
4841 outputDesc->toAudioPortConfig(&patch.sources[0]);
4842 patch.num_sources = 1;
4843 patch.num_sinks = 0;
4844 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4845 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004846 patch.num_sinks++;
4847 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004848 ssize_t index;
4849 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4850 index = mAudioPatches.indexOfKey(*patchHandle);
4851 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004852 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 }
4854 sp< AudioPatch> patchDesc;
4855 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4856 if (index >= 0) {
4857 patchDesc = mAudioPatches.valueAt(index);
4858 afPatchHandle = patchDesc->mAfPatchHandle;
4859 }
4860
Eric Laurent1c333e22014-05-20 10:48:17 -07004861 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 &afPatchHandle,
4863 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004864 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4865 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004866 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004867 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004869 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004870 addAudioPatch(patchDesc->mHandle, patchDesc);
4871 } else {
4872 patchDesc->mPatch = patch;
4873 }
4874 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004875 if (patchHandle) {
4876 *patchHandle = patchDesc->mHandle;
4877 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004878 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004879 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004880 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004881 }
4882 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004883
4884 // inform all input as well
4885 for (size_t i = 0; i < mInputs.size(); i++) {
4886 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004887 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004888 AudioParameter inputCmd = AudioParameter();
4889 ALOGV("%s: inform input %d of device:%d", __func__,
4890 inputDescriptor->mIoHandle, device);
4891 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4892 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4893 inputCmd.toString(),
4894 delayMs);
4895 }
4896 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004897 }
Eric Laurente552edb2014-03-10 17:42:56 -07004898
4899 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004900 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004901
4902 return muteWaitMs;
4903}
4904
Eric Laurentc75307b2015-03-17 15:29:32 -07004905status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004906 int delayMs,
4907 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004908{
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 ssize_t index;
4910 if (patchHandle) {
4911 index = mAudioPatches.indexOfKey(*patchHandle);
4912 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004913 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 }
4915 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004916 return INVALID_OPERATION;
4917 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4919 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004920 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004921 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 removeAudioPatch(patchDesc->mHandle);
4923 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004924 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004925 return status;
4926}
4927
4928status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4929 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 bool force,
4931 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004932{
4933 status_t status = NO_ERROR;
4934
Eric Laurent1f2f2232014-06-02 12:01:23 -07004935 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004936 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4937 inputDesc->mDevice = device;
4938
4939 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4940 if (!deviceList.isEmpty()) {
4941 struct audio_patch patch;
4942 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004943 // AUDIO_SOURCE_HOTWORD is for internal use only:
4944 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004945 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004946 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004947 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4948 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004949 patch.num_sinks = 1;
4950 //only one input device for now
4951 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004952 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004953 ssize_t index;
4954 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4955 index = mAudioPatches.indexOfKey(*patchHandle);
4956 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004957 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 }
4959 sp< AudioPatch> patchDesc;
4960 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4961 if (index >= 0) {
4962 patchDesc = mAudioPatches.valueAt(index);
4963 afPatchHandle = patchDesc->mAfPatchHandle;
4964 }
4965
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004968 0);
4969 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004971 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004973 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 addAudioPatch(patchDesc->mHandle, patchDesc);
4975 } else {
4976 patchDesc->mPatch = patch;
4977 }
4978 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004979 if (patchHandle) {
4980 *patchHandle = patchDesc->mHandle;
4981 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004982 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004984 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 }
4986 }
4987 }
4988 return status;
4989}
4990
Eric Laurent6a94d692014-05-20 11:18:06 -07004991status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4992 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004993{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004994 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 ssize_t index;
4996 if (patchHandle) {
4997 index = mAudioPatches.indexOfKey(*patchHandle);
4998 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004999 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005000 }
5001 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005002 return INVALID_OPERATION;
5003 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5005 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005006 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005007 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 removeAudioPatch(patchDesc->mHandle);
5009 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005010 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005011 return status;
5012}
5013
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005014sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005015 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005016 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005017 audio_format_t& format,
5018 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005019 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005020{
5021 // Choose an input profile based on the requested capture parameters: select the first available
5022 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005023 //
5024 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5025 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005026
5027 for (size_t i = 0; i < mHwModules.size(); i++)
5028 {
5029 if (mHwModules[i]->mHandle == 0) {
5030 continue;
5031 }
5032 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5033 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005034 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005035 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005036 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005037 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005038 format,
5039 &format /*updatedFormat*/,
5040 channelMask,
5041 &channelMask /*updatedChannelMask*/,
5042 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005043
Eric Laurente552edb2014-03-10 17:42:56 -07005044 return profile;
5045 }
5046 }
5047 }
5048 return NULL;
5049}
5050
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005051
5052audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005053 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005054{
François Gaffie036e1e92015-03-19 10:16:24 +01005055 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5056 audio_devices_t selectedDeviceFromMix =
5057 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005058
François Gaffie036e1e92015-03-19 10:16:24 +01005059 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5060 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005061 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005062 return getDeviceForInputSource(inputSource);
5063}
5064
5065audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5066{
Paul McLean466dc8e2015-04-17 13:15:36 -06005067 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5068 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005069 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005070 return route->mDeviceDescriptor->type();
5071 }
5072 }
5073
5074 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005075}
5076
Eric Laurente0720872014-03-11 09:30:41 -07005077float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005078 int index,
5079 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005080{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005081 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005082
5083 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5084 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5085 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5086 // the ringtone volume
5087 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5088 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5089 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5090 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5091 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5092 }
5093
Eric Laurente552edb2014-03-10 17:42:56 -07005094 // if a headset is connected, apply the following rules to ring tones and notifications
5095 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005096 // - always attenuate notifications volume by 6dB
5097 // - attenuate ring tones volume by 6dB unless music is not playing and
5098 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005099 // - if music is playing, always limit the volume to current music volume,
5100 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005101 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005102 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5103 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5104 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5105 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5106 ((stream_strategy == STRATEGY_SONIFICATION)
5107 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005108 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005109 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005110 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005111 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005112 // when the phone is ringing we must consider that music could have been paused just before
5113 // by the music application and behave as if music was active if the last music track was
5114 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005115 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005116 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005117 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005118 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005119 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005120 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5121 musicDevice),
5122 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005123 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5124 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005125 if (volumeDB > minVolDB) {
5126 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005127 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005128 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005129 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5130 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5131 // on A2DP, also ensure notification volume is not too low compared to media when
5132 // intended to be played
5133 if ((volumeDB > -96.0f) &&
5134 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5135 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5136 stream, device,
5137 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5138 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5139 }
5140 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005141 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5142 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005143 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005144 }
5145 }
5146
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005147 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005148}
5149
Eric Laurente0720872014-03-11 09:30:41 -07005150status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005151 int index,
5152 const sp<AudioOutputDescriptor>& outputDesc,
5153 audio_devices_t device,
5154 int delayMs,
5155 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005156{
Eric Laurente552edb2014-03-10 17:42:56 -07005157 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005158 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005159 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005160 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005161 return NO_ERROR;
5162 }
François Gaffie2110e042015-03-24 08:41:51 +01005163 audio_policy_forced_cfg_t forceUseForComm =
5164 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005165 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005166 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5167 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005168 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005169 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005170 return INVALID_OPERATION;
5171 }
5172
Eric Laurentc75307b2015-03-17 15:29:32 -07005173 if (device == AUDIO_DEVICE_NONE) {
5174 device = outputDesc->device();
5175 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005176
Eric Laurentffbc80f2015-03-18 18:30:19 -07005177 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005178 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005179 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005180 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005181
Eric Laurentffbc80f2015-03-18 18:30:19 -07005182 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005183
Eric Laurent3b73df72014-03-11 09:06:29 -07005184 if (stream == AUDIO_STREAM_VOICE_CALL ||
5185 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005186 float voiceVolume;
5187 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005188 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005189 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005190 } else {
5191 voiceVolume = 1.0;
5192 }
5193
Eric Laurent18fba842016-03-31 14:41:26 -07005194 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005195 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5196 mLastVoiceVolume = voiceVolume;
5197 }
5198 }
5199
5200 return NO_ERROR;
5201}
5202
Eric Laurentc75307b2015-03-17 15:29:32 -07005203void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5204 audio_devices_t device,
5205 int delayMs,
5206 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005207{
Eric Laurentc75307b2015-03-17 15:29:32 -07005208 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005209
Eric Laurent794fde22016-03-11 09:50:45 -08005210 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005211 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005212 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005213 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005214 device,
5215 delayMs,
5216 force);
5217 }
5218}
5219
Eric Laurente0720872014-03-11 09:30:41 -07005220void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005221 bool on,
5222 const sp<AudioOutputDescriptor>& outputDesc,
5223 int delayMs,
5224 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005225{
Eric Laurent72249d52015-06-08 11:12:15 -07005226 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5227 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005228 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005229 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005230 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005231 }
5232 }
5233}
5234
Eric Laurente0720872014-03-11 09:30:41 -07005235void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005236 bool on,
5237 const sp<AudioOutputDescriptor>& outputDesc,
5238 int delayMs,
5239 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005240{
Eric Laurente552edb2014-03-10 17:42:56 -07005241 if (device == AUDIO_DEVICE_NONE) {
5242 device = outputDesc->device();
5243 }
5244
Eric Laurentc75307b2015-03-17 15:29:32 -07005245 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5246 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005247
5248 if (on) {
5249 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005250 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005251 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005252 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005253 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005254 }
5255 }
5256 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5257 outputDesc->mMuteCount[stream]++;
5258 } else {
5259 if (outputDesc->mMuteCount[stream] == 0) {
5260 ALOGV("setStreamMute() unmuting non muted stream!");
5261 return;
5262 }
5263 if (--outputDesc->mMuteCount[stream] == 0) {
5264 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005265 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005266 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005267 device,
5268 delayMs);
5269 }
5270 }
5271}
5272
Eric Laurente0720872014-03-11 09:30:41 -07005273void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005274 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005275{
Eric Laurent87ffa392015-05-22 10:32:38 -07005276 if(!hasPrimaryOutput()) {
5277 return;
5278 }
5279
Eric Laurente552edb2014-03-10 17:42:56 -07005280 // if the stream pertains to sonification strategy and we are in call we must
5281 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5282 // in the device used for phone strategy and play the tone if the selected device does not
5283 // interfere with the device used for phone strategy
5284 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5285 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005286 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005287 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5288 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005289 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005290 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5291 stream, starting, outputDesc->mDevice, stateChange);
5292 if (outputDesc->mRefCount[stream]) {
5293 int muteCount = 1;
5294 if (stateChange) {
5295 muteCount = outputDesc->mRefCount[stream];
5296 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005297 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005298 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5299 for (int i = 0; i < muteCount; i++) {
5300 setStreamMute(stream, starting, mPrimaryOutput);
5301 }
5302 } else {
5303 ALOGV("handleIncallSonification() high visibility");
5304 if (outputDesc->device() &
5305 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5306 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5307 for (int i = 0; i < muteCount; i++) {
5308 setStreamMute(stream, starting, mPrimaryOutput);
5309 }
5310 }
5311 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005312 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5313 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005314 } else {
5315 mpClientInterface->stopTone();
5316 }
5317 }
5318 }
5319 }
5320}
5321
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005322audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5323{
5324 // flags to stream type mapping
5325 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5326 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5327 }
5328 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5329 return AUDIO_STREAM_BLUETOOTH_SCO;
5330 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005331 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5332 return AUDIO_STREAM_TTS;
5333 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005334
5335 // usage to stream type mapping
5336 switch (attr->usage) {
5337 case AUDIO_USAGE_MEDIA:
5338 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005339 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005340 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5341 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005342 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5343 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005344 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5345 return AUDIO_STREAM_SYSTEM;
5346 case AUDIO_USAGE_VOICE_COMMUNICATION:
5347 return AUDIO_STREAM_VOICE_CALL;
5348
5349 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5350 return AUDIO_STREAM_DTMF;
5351
5352 case AUDIO_USAGE_ALARM:
5353 return AUDIO_STREAM_ALARM;
5354 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5355 return AUDIO_STREAM_RING;
5356
5357 case AUDIO_USAGE_NOTIFICATION:
5358 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5359 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5360 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5361 case AUDIO_USAGE_NOTIFICATION_EVENT:
5362 return AUDIO_STREAM_NOTIFICATION;
5363
5364 case AUDIO_USAGE_UNKNOWN:
5365 default:
5366 return AUDIO_STREAM_MUSIC;
5367 }
5368}
Eric Laurente83b55d2014-11-14 10:06:21 -08005369
François Gaffie53615e22015-03-19 09:24:12 +01005370bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5371{
Eric Laurente83b55d2014-11-14 10:06:21 -08005372 // has flags that map to a strategy?
5373 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5374 return true;
5375 }
5376
5377 // has known usage?
5378 switch (paa->usage) {
5379 case AUDIO_USAGE_UNKNOWN:
5380 case AUDIO_USAGE_MEDIA:
5381 case AUDIO_USAGE_VOICE_COMMUNICATION:
5382 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5383 case AUDIO_USAGE_ALARM:
5384 case AUDIO_USAGE_NOTIFICATION:
5385 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5386 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5387 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5388 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5389 case AUDIO_USAGE_NOTIFICATION_EVENT:
5390 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5391 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5392 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5393 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005394 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005395 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005396 break;
5397 default:
5398 return false;
5399 }
5400 return true;
5401}
5402
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005403bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005404 routing_strategy strategy, uint32_t inPastMs,
5405 nsecs_t sysTime) const
5406{
5407 if ((sysTime == 0) && (inPastMs != 0)) {
5408 sysTime = systemTime();
5409 }
Eric Laurent794fde22016-03-11 09:50:45 -08005410 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005411 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5412 (NUM_STRATEGIES == strategy)) &&
5413 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5414 return true;
5415 }
5416 }
5417 return false;
5418}
5419
François Gaffie2110e042015-03-24 08:41:51 +01005420audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5421{
5422 return mEngine->getForceUse(usage);
5423}
5424
5425bool AudioPolicyManager::isInCall()
5426{
5427 return isStateInCall(mEngine->getPhoneState());
5428}
5429
5430bool AudioPolicyManager::isStateInCall(int state)
5431{
5432 return is_state_in_call(state);
5433}
5434
Eric Laurentd60560a2015-04-10 11:31:20 -07005435void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5436{
5437 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5438 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5439 if (sourceDesc->mDevice->equals(deviceDesc)) {
5440 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5441 stopAudioSource(sourceDesc->getHandle());
5442 }
5443 }
5444
5445 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5446 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5447 bool release = false;
5448 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5449 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5450 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5451 source->ext.device.type == deviceDesc->type()) {
5452 release = true;
5453 }
5454 }
5455 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5456 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5457 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5458 sink->ext.device.type == deviceDesc->type()) {
5459 release = true;
5460 }
5461 }
5462 if (release) {
5463 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5464 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5465 }
5466 }
5467}
5468
Phil Burk09bc4612016-02-24 15:58:15 -08005469// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005470void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5471 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005472 // TODO Set this based on Config properties.
5473 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005474
5475 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5476 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005477 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005478
5479 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005480 bool supportsAC3 = false;
5481 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005482 bool supportsIEC61937 = false;
5483 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5484 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005485 switch (format) {
5486 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005487 supportsAC3 = true;
5488 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005489 case AUDIO_FORMAT_E_AC3:
5490 case AUDIO_FORMAT_DTS:
5491 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005492 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005493 break;
5494 case AUDIO_FORMAT_IEC61937:
5495 supportsIEC61937 = true;
5496 break;
5497 default:
5498 break;
5499 }
5500 }
Phil Burk09bc4612016-02-24 15:58:15 -08005501
5502 // Modify formats based on surround preferences.
5503 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005504 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5505 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5506 // Remove surround sound related formats.
5507 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5508 audio_format_t format = formats[formatIndex];
5509 switch(format) {
5510 case AUDIO_FORMAT_AC3:
5511 case AUDIO_FORMAT_E_AC3:
5512 case AUDIO_FORMAT_DTS:
5513 case AUDIO_FORMAT_DTS_HD:
5514 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005515 formats.removeAt(formatIndex);
5516 break;
5517 default:
5518 formatIndex++; // keep it
5519 break;
5520 }
Phil Burk09bc4612016-02-24 15:58:15 -08005521 }
Phil Burk07ac1142016-03-25 13:39:29 -07005522 supportsAC3 = false;
5523 supportsOtherSurround = false;
5524 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005525 }
Phil Burk07ac1142016-03-25 13:39:29 -07005526 } else { // AUTO or ALWAYS
5527 // Most TVs support AC3 even if they do not report it in the EDID.
5528 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5529 && !supportsAC3) {
5530 formats.add(AUDIO_FORMAT_AC3);
5531 supportsAC3 = true;
5532 }
5533
5534 // If ALWAYS, add support for raw surround formats if all are missing.
5535 // This assumes that if any of these formats are reported by the HAL
5536 // then the report is valid and should not be modified.
5537 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5538 && !supportsOtherSurround) {
5539 formats.add(AUDIO_FORMAT_E_AC3);
5540 formats.add(AUDIO_FORMAT_DTS);
5541 formats.add(AUDIO_FORMAT_DTS_HD);
5542 supportsOtherSurround = true;
5543 }
5544
5545 // Add support for IEC61937 if any raw surround supported.
5546 // The HAL could do this but add it here, just in case.
5547 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5548 formats.add(AUDIO_FORMAT_IEC61937);
5549 supportsIEC61937 = true;
5550 }
Phil Burk09bc4612016-02-24 15:58:15 -08005551 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005552}
5553
5554// Modify the list of channel masks supported.
5555void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5556 ChannelsVector &channelMasks = *channelMasksPtr;
5557 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5558 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5559
5560 // If NEVER, then remove support for channelMasks > stereo.
5561 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5562 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5563 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5564 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5565 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5566 channelMasks.removeAt(maskIndex);
5567 } else {
5568 maskIndex++;
5569 }
5570 }
5571 // If ALWAYS, then make sure we at least support 5.1
5572 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5573 bool supports5dot1 = false;
5574 // Are there any channel masks that can be considered "surround"?
5575 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5576 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5577 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5578 supports5dot1 = true;
5579 break;
5580 }
5581 }
5582 // If not then add 5.1 support.
5583 if (!supports5dot1) {
5584 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5585 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5586 }
Phil Burk09bc4612016-02-24 15:58:15 -08005587 }
5588}
5589
Phil Burk00eeb322016-03-31 12:41:00 -07005590void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5591 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005592 AudioProfileVector &profiles)
5593{
5594 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005595
François Gaffie112b0af2015-11-19 16:13:25 +01005596 // Format MUST be checked first to update the list of AudioProfile
5597 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005598 reply = mpClientInterface->getParameters(
5599 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005600 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005601 AudioParameter repliedParameters(reply);
5602 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005603 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005604 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5605 return;
5606 }
Phil Burk09bc4612016-02-24 15:58:15 -08005607 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005608 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005609 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005610 }
Phil Burk09bc4612016-02-24 15:58:15 -08005611 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005612 }
5613 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5614
Eric Laurent20eb3a42016-01-26 18:39:17 -08005615 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005616 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005617 ChannelsVector channelMasks;
5618 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005619 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005620 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005621
5622 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005623 reply = mpClientInterface->getParameters(
5624 ioHandle,
5625 requestedParameters.toString() + ";" +
5626 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005627 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005628 AudioParameter repliedParameters(reply);
5629 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005630 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005631 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005632 }
5633 }
5634 if (profiles.hasDynamicChannelsFor(format)) {
5635 reply = mpClientInterface->getParameters(ioHandle,
5636 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005637 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005638 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005639 AudioParameter repliedParameters(reply);
5640 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005641 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005642 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005643 if (device == AUDIO_DEVICE_OUT_HDMI) {
5644 filterSurroundChannelMasks(&channelMasks);
5645 }
François Gaffie112b0af2015-11-19 16:13:25 +01005646 }
5647 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005648 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005649 }
5650}
Eric Laurentd60560a2015-04-10 11:31:20 -07005651
Eric Laurente552edb2014-03-10 17:42:56 -07005652}; // namespace android