blob: 923d4f66ef599452cb96e8fe4f5b4bbe502e20d5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070036#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080037#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070038#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070039#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070040#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurentdc462862016-07-19 12:29:53 -070052//FIXME: workaround for truncated touch sounds
53// to be removed when the problem is handled by system UI
54#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070055// ----------------------------------------------------------------------------
56// AudioPolicyInterface implementation
57// ----------------------------------------------------------------------------
58
Eric Laurente0720872014-03-11 09:30:41 -070059status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080060 audio_policy_dev_state_t state,
61 const char *device_address,
62 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070063{
Paul McLeane743a472015-01-28 11:07:31 -080064 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080065}
66
François Gaffie44481e72016-04-20 07:49:57 +020067void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
68 audio_policy_dev_state_t state,
69 const String8 &device_address)
70{
71 AudioParameter param(device_address);
72 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070073 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020074 param.addInt(key, device);
75 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
76}
77
Eric Laurentc73ca6e2014-12-12 14:34:22 -080078status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080079 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080080 const char *device_address,
81 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080082{
Paul McLeane743a472015-01-28 11:07:31 -080083 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
84- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070085
86 // connect/disconnect only 1 device at a time
87 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
88
François Gaffie53615e22015-03-19 09:24:12 +010089 sp<DeviceDescriptor> devDesc =
90 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080091
Eric Laurente552edb2014-03-10 17:42:56 -070092 // handle output devices
93 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070094 SortedVector <audio_io_handle_t> outputs;
95
Eric Laurent3a4311c2014-03-17 12:00:47 -070096 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
97
Eric Laurente552edb2014-03-10 17:42:56 -070098 // save a copy of the opened output descriptors before any output is opened or closed
99 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
100 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700101 switch (state)
102 {
103 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800104 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700105 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700106 ALOGW("setDeviceConnectionState() device already connected: %x", device);
107 return INVALID_OPERATION;
108 }
109 ALOGV("setDeviceConnectionState() connecting device %x", device);
110
Eric Laurente552edb2014-03-10 17:42:56 -0700111 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 index = mAvailableOutputDevices.add(devDesc);
113 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100114 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700115 if (module == 0) {
116 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
117 device);
118 mAvailableOutputDevices.remove(devDesc);
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122 } else {
123 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 }
125
François Gaffie44481e72016-04-20 07:49:57 +0200126 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
127 // parameters on newly connected devices (instead of opening the outputs...)
128 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
129
Eric Laurenta1d525f2015-01-29 13:36:45 -0800130 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700131 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200132
133 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
134 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700135 return INVALID_OPERATION;
136 }
François Gaffie2110e042015-03-24 08:41:51 +0100137 // Propagate device availability to Engine
138 mEngine->setDeviceConnectionState(devDesc, state);
139
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700140 // outputs should never be empty here
141 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
142 "checkOutputsForDevice() returned no outputs but status OK");
143 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
144 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800145
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700148 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700150 ALOGW("setDeviceConnectionState() device not connected: %x", device);
151 return INVALID_OPERATION;
152 }
153
Paul McLean5c477aa2014-08-20 16:47:57 -0700154 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
155
Paul McLeane743a472015-01-28 11:07:31 -0800156 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200157 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700158
Eric Laurente552edb2014-03-10 17:42:56 -0700159 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700160 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100163
164 // Propagate device availability to Engine
165 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700166 } break;
167
168 default:
169 ALOGE("setDeviceConnectionState() invalid state: %x", state);
170 return BAD_VALUE;
171 }
172
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
174 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700175 checkA2dpSuspend();
176 checkOutputForAllStrategies();
177 // outputs must be closed after checkOutputForAllStrategies() is executed
178 if (!outputs.isEmpty()) {
179 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // close unused outputs after device disconnection or direct outputs that have been
182 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700183 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700184 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
185 (desc->mDirectOpenCount == 0))) {
186 closeOutput(outputs[i]);
187 }
188 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189 // check again after closing A2DP output to reset mA2dpSuspended if needed
190 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700191 }
192
193 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700194 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700195 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
196 updateCallRouting(newDevice);
197 }
Eric Laurente552edb2014-03-10 17:42:56 -0700198 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
200 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
201 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 // do not force device change on duplicated output because if device is 0, it will
203 // also force a device 0 for the two outputs it is duplicated to which may override
204 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700205 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100206 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700207 // always force when disconnecting (a non-duplicated device)
208 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700209 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700210 }
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
Eric Laurentd60560a2015-04-10 11:31:20 -0700213 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
214 cleanUpForDevice(devDesc);
215 }
216
Eric Laurent72aa32f2014-05-30 18:51:48 -0700217 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700218 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700219 } // end if is output device
220
Eric Laurente552edb2014-03-10 17:42:56 -0700221 // handle input devices
222 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700223 SortedVector <audio_io_handle_t> inputs;
224
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700226 switch (state)
227 {
228 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700231 ALOGW("setDeviceConnectionState() device already connected: %d", device);
232 return INVALID_OPERATION;
233 }
François Gaffie53615e22015-03-19 09:24:12 +0100234 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700235 if (module == NULL) {
236 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
237 device);
238 return INVALID_OPERATION;
239 }
François Gaffie44481e72016-04-20 07:49:57 +0200240
241 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
242 // parameters on newly connected devices (instead of opening the inputs...)
243 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
244
Paul McLean9080a4c2015-06-18 08:24:02 -0700245 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200246 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
247 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700248 return INVALID_OPERATION;
249 }
250
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 index = mAvailableInputDevices.add(devDesc);
252 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800253 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 } else {
255 return NO_MEMORY;
256 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800257
François Gaffie2110e042015-03-24 08:41:51 +0100258 // Propagate device availability to Engine
259 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700260 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700261
262 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700263 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700265 ALOGW("setDeviceConnectionState() device not connected: %d", device);
266 return INVALID_OPERATION;
267 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700268
269 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
270
271 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200272 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700273
Paul McLean9080a4c2015-06-18 08:24:02 -0700274 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700276
François Gaffie2110e042015-03-24 08:41:51 +0100277 // Propagate device availability to Engine
278 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700279 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurentd4692962014-05-05 18:13:44 -0700286 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700287 // As the input device list can impact the output device selection, update
288 // getDeviceForStrategy() cache
289 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700290
Eric Laurent87ffa392015-05-22 10:32:38 -0700291 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700292 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
293 updateCallRouting(newDevice);
294 }
295
Eric Laurentd60560a2015-04-10 11:31:20 -0700296 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
297 cleanUpForDevice(devDesc);
298 }
299
Eric Laurentb52c1522014-05-20 11:27:36 -0700300 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700301 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 ALOGW("setDeviceConnectionState() invalid device: %x", device);
305 return BAD_VALUE;
306}
307
Eric Laurente0720872014-03-11 09:30:41 -0700308audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100309 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700310{
Eric Laurent634b7142016-04-20 13:48:02 -0700311 sp<DeviceDescriptor> devDesc =
312 mHwModules.getDeviceDescriptor(device, device_address, "",
313 (strlen(device_address) != 0)/*matchAddress*/);
314
315 if (devDesc == 0) {
316 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
317 device, device_address);
318 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
319 }
François Gaffie53615e22015-03-19 09:24:12 +0100320
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 DeviceVector *deviceVector;
322
Eric Laurente552edb2014-03-10 17:42:56 -0700323 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700325 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 deviceVector = &mAvailableInputDevices;
327 } else {
328 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
329 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700330 }
Eric Laurent634b7142016-04-20 13:48:02 -0700331
332 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
333 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800334}
335
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800336status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
337 const char *device_address,
338 const char *device_name)
339{
340 status_t status;
341
342 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
343 device, device_address, device_name);
344
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800345 // connect/disconnect only 1 device at a time
346 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
347
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800348 // Check if the device is currently connected
349 sp<DeviceDescriptor> devDesc =
350 mHwModules.getDeviceDescriptor(device, device_address, device_name);
351 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
352 if (index < 0) {
353 // Nothing to do: device is not connected
354 return NO_ERROR;
355 }
356
357 // Toggle the device state: UNAVAILABLE -> AVAILABLE
358 // This will force reading again the device configuration
359 status = setDeviceConnectionState(device,
360 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
361 device_address, device_name);
362 if (status != NO_ERROR) {
363 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
364 status);
365 return status;
366 }
367
368 status = setDeviceConnectionState(device,
369 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
370 device_address, device_name);
371 if (status != NO_ERROR) {
372 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
373 status);
374 return status;
375 }
376
377 return NO_ERROR;
378}
379
Eric Laurentdc462862016-07-19 12:29:53 -0700380uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700381{
382 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700383 status_t status;
384 audio_patch_handle_t afPatchHandle;
385 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700386 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700387
Andy Hunga76c7de2016-12-13 19:14:31 -0800388 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700389 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700390 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800391 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700392 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
393
394 // release existing RX patch if any
395 if (mCallRxPatch != 0) {
396 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
397 mCallRxPatch.clear();
398 }
399 // release TX patch if any
400 if (mCallTxPatch != 0) {
401 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
402 mCallTxPatch.clear();
403 }
404
405 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
406 // via setOutputDevice() on primary output.
407 // Otherwise, create two audio patches for TX and RX path.
408 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700409 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700410 // If the TX device is also on the primary HW module, setOutputDevice() will take care
411 // of it due to legacy implementation. If not, create a patch.
412 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
413 == AUDIO_DEVICE_NONE) {
414 createTxPatch = true;
415 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700416 } else { // create RX path audio patch
417 struct audio_patch patch;
418
419 patch.num_sources = 1;
420 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700421 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
422 ALOG_ASSERT(!deviceList.isEmpty(),
423 "updateCallRouting() selected device not in output device list");
424 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
425 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
426 ALOG_ASSERT(!deviceList.isEmpty(),
427 "updateCallRouting() no telephony RX device");
428 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
429
430 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
431 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
432
433 // request to reuse existing output stream if one is already opened to reach the RX device
434 SortedVector<audio_io_handle_t> outputs =
435 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700436 audio_io_handle_t output = selectOutput(outputs,
437 AUDIO_OUTPUT_FLAG_NONE,
438 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700439 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700440 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441 ALOG_ASSERT(!outputDesc->isDuplicated(),
442 "updateCallRouting() RX device output is duplicated");
443 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700444 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700445 patch.num_sources = 2;
446 }
447
448 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700449 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700450 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
451 status);
452 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100453 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454 mCallRxPatch->mAfPatchHandle = afPatchHandle;
455 mCallRxPatch->mUid = mUidCached;
456 }
457 createTxPatch = true;
458 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700459 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700461
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 patch.num_sources = 1;
463 patch.num_sinks = 1;
464 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
465 ALOG_ASSERT(!deviceList.isEmpty(),
466 "updateCallRouting() selected device not in input device list");
467 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
468 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
469 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
470 ALOG_ASSERT(!deviceList.isEmpty(),
471 "updateCallRouting() no telephony TX device");
472 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
473 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
474
475 SortedVector<audio_io_handle_t> outputs =
476 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700477 audio_io_handle_t output = selectOutput(outputs,
478 AUDIO_OUTPUT_FLAG_NONE,
479 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480 // request to reuse existing output stream if one is already opened to reach the TX
481 // path output device
482 if (output != AUDIO_IO_HANDLE_NONE) {
483 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
484 ALOG_ASSERT(!outputDesc->isDuplicated(),
485 "updateCallRouting() RX device output is duplicated");
486 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700487 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700488 patch.num_sources = 2;
489 }
490
Eric Laurentc0a889f2015-10-14 14:36:34 -0700491 // terminate active capture if on the same HW module as the call TX source device
492 // FIXME: would be better to refine to only inputs whose profile connects to the
493 // call TX device but this information is not in the audio patch and logic here must be
494 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800495 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
496 for (size_t i = 0; i < activeInputs.size(); i++) {
497 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
498 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
499 AudioSessionCollection activeSessions =
500 activeDesc->getAudioSessions(true /*activeOnly*/);
501 for (size_t j = 0; j < activeSessions.size(); j++) {
502 audio_session_t activeSession = activeSessions.keyAt(j);
503 stopInput(activeDesc->mIoHandle, activeSession);
504 releaseInput(activeDesc->mIoHandle, activeSession);
505 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700506 }
507 }
508
Eric Laurentc2730ba2014-07-20 15:47:07 -0700509 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700510 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700511 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
512 status);
513 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100514 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700515 mCallTxPatch->mAfPatchHandle = afPatchHandle;
516 mCallTxPatch->mUid = mUidCached;
517 }
518 }
Eric Laurentdc462862016-07-19 12:29:53 -0700519
520 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700521}
522
Eric Laurente0720872014-03-11 09:30:41 -0700523void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700524{
525 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100526 // store previous phone state for management of sonification strategy below
527 int oldState = mEngine->getPhoneState();
528
529 if (mEngine->setPhoneState(state) != NO_ERROR) {
530 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700531 return;
532 }
François Gaffie2110e042015-03-24 08:41:51 +0100533 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700534 // if leaving call state, handle special case of active streams
535 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700536 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700537 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800538 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700540 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800541
Eric Laurent63dea1d2015-07-02 17:10:28 -0700542 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800543 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700544 }
545
François Gaffie2110e042015-03-24 08:41:51 +0100546 /**
547 * Switching to or from incall state or switching between telephony and VoIP lead to force
548 * routing command.
549 */
550 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
551 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700552
553 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700554 checkA2dpSuspend();
555 checkOutputForAllStrategies();
556 updateDevicesAndOutputs();
557
Eric Laurente552edb2014-03-10 17:42:56 -0700558 int delayMs = 0;
559 if (isStateInCall(state)) {
560 nsecs_t sysTime = systemTime();
561 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700563 // mute media and sonification strategies and delay device switch by the largest
564 // latency of any output where either strategy is active.
565 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100566 if ((isStrategyActive(desc, STRATEGY_MEDIA,
567 SONIFICATION_HEADSET_MUSIC_DELAY,
568 sysTime) ||
569 isStrategyActive(desc, STRATEGY_SONIFICATION,
570 SONIFICATION_HEADSET_MUSIC_DELAY,
571 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 (delayMs < (int)desc->latency()*2)) {
573 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700574 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700575 setStrategyMute(STRATEGY_MEDIA, true, desc);
576 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700577 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700578 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
579 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700580 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
581 }
582 }
583
Eric Laurent87ffa392015-05-22 10:32:38 -0700584 if (hasPrimaryOutput()) {
585 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
586 // the device returned is not necessarily reachable via this output
587 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
588 // force routing command to audio hardware when ending call
589 // even if no device change is needed
590 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
591 rxDevice = mPrimaryOutput->device();
592 }
Eric Laurente552edb2014-03-10 17:42:56 -0700593
Eric Laurent87ffa392015-05-22 10:32:38 -0700594 if (state == AUDIO_MODE_IN_CALL) {
595 updateCallRouting(rxDevice, delayMs);
596 } else if (oldState == AUDIO_MODE_IN_CALL) {
597 if (mCallRxPatch != 0) {
598 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
599 mCallRxPatch.clear();
600 }
601 if (mCallTxPatch != 0) {
602 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
603 mCallTxPatch.clear();
604 }
605 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
606 } else {
607 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700608 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 }
Eric Laurente552edb2014-03-10 17:42:56 -0700610 // if entering in call state, handle special case of active streams
611 // pertaining to sonification strategy see handleIncallSonification()
612 if (isStateInCall(state)) {
613 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800614 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700615 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700616 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700617
618 // force reevaluating accessibility routing when call starts
619 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700620 }
621
622 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 if (state == AUDIO_MODE_RINGTONE &&
624 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700625 mLimitRingtoneVolume = true;
626 } else {
627 mLimitRingtoneVolume = false;
628 }
629}
630
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700631audio_mode_t AudioPolicyManager::getPhoneState() {
632 return mEngine->getPhoneState();
633}
634
Eric Laurente0720872014-03-11 09:30:41 -0700635void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700636 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700637{
François Gaffie2110e042015-03-24 08:41:51 +0100638 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700639
François Gaffie2110e042015-03-24 08:41:51 +0100640 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
641 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
642 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700643 }
François Gaffie2110e042015-03-24 08:41:51 +0100644 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
645 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
646 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700647
648 // check for device and output changes triggered by new force usage
649 checkA2dpSuspend();
650 checkOutputForAllStrategies();
651 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800652
Eric Laurentdc462862016-07-19 12:29:53 -0700653 //FIXME: workaround for truncated touch sounds
654 // to be removed when the problem is handled by system UI
655 uint32_t delayMs = 0;
656 uint32_t waitMs = 0;
657 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
658 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
659 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700660 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700661 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700662 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700663 }
Eric Laurente552edb2014-03-10 17:42:56 -0700664 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700665 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
666 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
667 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700668 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
669 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670 }
Eric Laurente552edb2014-03-10 17:42:56 -0700671 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700672 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700673 }
674 }
675
Eric Laurentfb66dd92016-01-28 18:32:03 -0800676 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
677 for (size_t i = 0; i < activeInputs.size(); i++) {
678 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
679 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700680 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800681 if (activeDesc->mProfile->getSupportedDevices().types() &
682 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
683 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700684 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800685 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688}
689
Eric Laurente0720872014-03-11 09:30:41 -0700690void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700691{
692 ALOGV("setSystemProperty() property %s, value %s", property, value);
693}
694
695// Find a direct output profile compatible with the parameters passed, even if the input flags do
696// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800697sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700698 audio_devices_t device,
699 uint32_t samplingRate,
700 audio_format_t format,
701 audio_channel_mask_t channelMask,
702 audio_output_flags_t flags)
703{
Eric Laurent861a6282015-05-18 15:40:16 -0700704 // only retain flags that will drive the direct output profile selection
705 // if explicitly requested
706 static const uint32_t kRelevantFlags =
707 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
708 flags =
709 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
710
711 sp<IOProfile> profile;
712
Eric Laurente552edb2014-03-10 17:42:56 -0700713 for (size_t i = 0; i < mHwModules.size(); i++) {
714 if (mHwModules[i]->mHandle == 0) {
715 continue;
716 }
717 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700718 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
719 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700720 samplingRate, NULL /*updatedSamplingRate*/,
721 format, NULL /*updatedFormat*/,
722 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700723 flags)) {
724 continue;
725 }
726 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100727 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700728 continue;
729 }
730 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100731 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700732 continue;
733 }
734 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100735 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700736 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700737 }
Eric Laurente552edb2014-03-10 17:42:56 -0700738 }
739 }
Eric Laurent861a6282015-05-18 15:40:16 -0700740 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700741}
742
Eric Laurente0720872014-03-11 09:30:41 -0700743audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100744 uint32_t samplingRate,
745 audio_format_t format,
746 audio_channel_mask_t channelMask,
747 audio_output_flags_t flags,
748 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700749{
Eric Laurent3b73df72014-03-11 09:06:29 -0700750 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700751 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
752 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
753 device, stream, samplingRate, format, channelMask, flags);
754
Eric Laurente83b55d2014-11-14 10:06:21 -0800755 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
756 stream, samplingRate,format, channelMask,
757 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700758}
759
Eric Laurente83b55d2014-11-14 10:06:21 -0800760status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
761 audio_io_handle_t *output,
762 audio_session_t session,
763 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700764 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800765 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800766 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700767 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800768 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700769{
Eric Laurente83b55d2014-11-14 10:06:21 -0800770 audio_attributes_t attributes;
771 if (attr != NULL) {
772 if (!isValidAttributes(attr)) {
773 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
774 attr->usage, attr->content_type, attr->flags,
775 attr->tags);
776 return BAD_VALUE;
777 }
778 attributes = *attr;
779 } else {
780 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
781 ALOGE("getOutputForAttr(): invalid stream type");
782 return BAD_VALUE;
783 }
784 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700785 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800786
787 // TODO: check for existing client for this port ID
788 if (*portId == AUDIO_PORT_HANDLE_NONE) {
789 *portId = AudioPort::getNextUniqueId();
790 }
791
Eric Laurentc75307b2015-03-17 15:29:32 -0700792 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800793 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100794 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800795 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100796 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800797 }
François Gaffie036e1e92015-03-19 10:16:24 +0100798 *stream = streamTypefromAttributesInt(&attributes);
799 *output = desc->mIoHandle;
800 ALOGV("getOutputForAttr() returns output %d", *output);
801 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800802 }
803 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
804 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
805 return BAD_VALUE;
806 }
807
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700808 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
809 " session %d selectedDeviceId %d",
810 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
811 session, selectedDeviceId);
812
813 *stream = streamTypefromAttributesInt(&attributes);
814
815 // Explicit routing?
816 sp<DeviceDescriptor> deviceDesc;
817 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
818 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
819 deviceDesc = mAvailableOutputDevices[i];
820 break;
821 }
822 }
823 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700824
Eric Laurente83b55d2014-11-14 10:06:21 -0800825 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700826 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700827
Eric Laurente83b55d2014-11-14 10:06:21 -0800828 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700829 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
830 }
831
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700832 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800833 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700834
Eric Laurente83b55d2014-11-14 10:06:21 -0800835 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800836 config->sample_rate, config->format, config->channel_mask,
837 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800838 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700839 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800840 return INVALID_OPERATION;
841 }
Paul McLeanaa981192015-03-21 09:55:15 -0700842
Eric Laurente83b55d2014-11-14 10:06:21 -0800843 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700844}
845
846audio_io_handle_t AudioPolicyManager::getOutputForDevice(
847 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800848 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700849 audio_stream_type_t stream,
850 uint32_t samplingRate,
851 audio_format_t format,
852 audio_channel_mask_t channelMask,
853 audio_output_flags_t flags,
854 const audio_offload_info_t *offloadInfo)
855{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700856 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700857 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858
Eric Laurente552edb2014-03-10 17:42:56 -0700859#ifdef AUDIO_POLICY_TEST
860 if (mCurOutput != 0) {
861 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
862 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
863
864 if (mTestOutputs[mCurOutput] == 0) {
865 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700866 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
867 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700868 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700869 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700870 outputDesc->mFlags =
871 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700872 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700873 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
874 config.sample_rate = mTestSamplingRate;
875 config.channel_mask = mTestChannels;
876 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700877 if (offloadInfo != NULL) {
878 config.offload_info = *offloadInfo;
879 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700880 status = mpClientInterface->openOutput(0,
881 &mTestOutputs[mCurOutput],
882 &config,
883 &outputDesc->mDevice,
884 String8(""),
885 &outputDesc->mLatency,
886 outputDesc->mFlags);
887 if (status == NO_ERROR) {
888 outputDesc->mSamplingRate = config.sample_rate;
889 outputDesc->mFormat = config.format;
890 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700891 AudioParameter outputCmd = AudioParameter();
892 outputCmd.addInt(String8("set_id"),mCurOutput);
893 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
894 addOutput(mTestOutputs[mCurOutput], outputDesc);
895 }
896 }
897 return mTestOutputs[mCurOutput];
898 }
899#endif //AUDIO_POLICY_TEST
900
901 // open a direct output if required by specified parameters
902 //force direct flag if offload flag is set: offloading implies a direct output stream
903 // and all common behaviors are driven by checking only the direct flag
904 // this should normally be set appropriately in the policy configuration file
905 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700906 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700907 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700908 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
909 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
910 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800911 // only allow deep buffering for music stream type
912 if (stream != AUDIO_STREAM_MUSIC) {
913 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700914 } else if (/* stream == AUDIO_STREAM_MUSIC && */
915 flags == AUDIO_OUTPUT_FLAG_NONE &&
916 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
917 // use DEEP_BUFFER as default output for music stream type
918 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800919 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700920 if (stream == AUDIO_STREAM_TTS) {
921 flags = AUDIO_OUTPUT_FLAG_TTS;
922 }
Eric Laurente552edb2014-03-10 17:42:56 -0700923
Eric Laurentb732cf52014-09-24 19:08:21 -0700924 sp<IOProfile> profile;
925
926 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700927 // and not explicitly requested
928 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800929 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700930 audio_channel_count_from_out_mask(channelMask) <= 2) {
931 goto non_direct_output;
932 }
933
Andy Hung2ddee192015-12-18 17:34:44 -0800934 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
935 // This prevents creating an offloaded track and tearing it down immediately after start
936 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700937 // FIXME: We should check the audio session here but we do not have it in this context.
938 // This may prevent offloading in rare situations where effects are left active by apps
939 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700940
Eric Laurente552edb2014-03-10 17:42:56 -0700941 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800942 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700943 profile = getProfileForDirectOutput(device,
944 samplingRate,
945 format,
946 channelMask,
947 (audio_output_flags_t)flags);
948 }
949
Eric Laurent1c333e22014-05-20 10:48:17 -0700950 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700951 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700952
953 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700954 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700955 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
956 outputDesc = desc;
957 // reuse direct output if currently open and configured with same parameters
958 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800959 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700960 (channelMask == outputDesc->mChannelMask)) {
961 outputDesc->mDirectOpenCount++;
962 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
963 return mOutputs.keyAt(i);
964 }
965 }
966 }
967 // close direct output if currently open and configured with different parameters
968 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700969 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700970 }
Eric Laurent861a6282015-05-18 15:40:16 -0700971
972 // if the selected profile is offloaded and no offload info was specified,
973 // create a default one
974 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100975 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700976 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
977 defaultOffloadInfo.sample_rate = samplingRate;
978 defaultOffloadInfo.channel_mask = channelMask;
979 defaultOffloadInfo.format = format;
980 defaultOffloadInfo.stream_type = stream;
981 defaultOffloadInfo.bit_rate = 0;
982 defaultOffloadInfo.duration_us = -1;
983 defaultOffloadInfo.has_video = true; // conservative
984 defaultOffloadInfo.is_streaming = true; // likely
985 offloadInfo = &defaultOffloadInfo;
986 }
987
Eric Laurentc75307b2015-03-17 15:29:32 -0700988 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700989 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700990 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700991 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700992 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
993 config.sample_rate = samplingRate;
994 config.channel_mask = channelMask;
995 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700996 if (offloadInfo != NULL) {
997 config.offload_info = *offloadInfo;
998 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700999 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07001000 &output,
1001 &config,
1002 &outputDesc->mDevice,
1003 String8(""),
1004 &outputDesc->mLatency,
1005 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001006
1007 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001008 if (status != NO_ERROR ||
1009 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001010 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001011 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001012 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1013 "format %d %d, channelMask %04x %04x", output, samplingRate,
1014 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1015 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001016 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001017 mpClientInterface->closeOutput(output);
1018 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001019 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001020 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001021 goto non_direct_output;
1022 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001023 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001024 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001025 outputDesc->mSamplingRate = config.sample_rate;
1026 outputDesc->mChannelMask = config.channel_mask;
1027 outputDesc->mFormat = config.format;
1028 outputDesc->mRefCount[stream] = 0;
1029 outputDesc->mStopTime[stream] = 0;
1030 outputDesc->mDirectOpenCount = 1;
1031
Eric Laurente552edb2014-03-10 17:42:56 -07001032 audio_io_handle_t srcOutput = getOutputForEffect();
1033 addOutput(output, outputDesc);
1034 audio_io_handle_t dstOutput = getOutputForEffect();
1035 if (dstOutput == output) {
1036 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1037 }
1038 mPreviousOutputs = mOutputs;
1039 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001040 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001041 return output;
1042 }
1043
Eric Laurentb732cf52014-09-24 19:08:21 -07001044non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001045
1046 // A request for HW A/V sync cannot fallback to a mixed output because time
1047 // stamps are embedded in audio data
1048 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1049 return AUDIO_IO_HANDLE_NONE;
1050 }
1051
Eric Laurente552edb2014-03-10 17:42:56 -07001052 // ignoring channel mask due to downmix capability in mixer
1053
1054 // open a non direct output
1055
1056 // for non direct outputs, only PCM is supported
1057 if (audio_is_linear_pcm(format)) {
1058 // get which output is suitable for the specified stream. The actual
1059 // routing change will happen when startOutput() will be called
1060 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1061
Eric Laurent8838a382014-09-08 16:44:28 -07001062 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1063 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1064 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001065 }
1066 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1067 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1068
Paul McLeanaa981192015-03-21 09:55:15 -07001069 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001070
1071 return output;
1072}
1073
Eric Laurente0720872014-03-11 09:30:41 -07001074audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001075 audio_output_flags_t flags,
1076 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001077{
1078 // select one output among several that provide a path to a particular device or set of
1079 // devices (the list was previously build by getOutputsForDevice()).
1080 // The priority is as follows:
1081 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001082 // 2: the output with the bit depth the closest to the requested one
1083 // 3: the primary output
1084 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001085
1086 if (outputs.size() == 0) {
1087 return 0;
1088 }
1089 if (outputs.size() == 1) {
1090 return outputs[0];
1091 }
1092
1093 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001094 audio_io_handle_t outputForFlags = 0;
1095 audio_io_handle_t outputForPrimary = 0;
1096 audio_io_handle_t outputForFormat = 0;
1097 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1098 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001099
1100 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001101 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001102 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001103 // if a valid format is specified, skip output if not compatible
1104 if (format != AUDIO_FORMAT_INVALID) {
1105 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001106 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001107 continue;
1108 }
1109 } else if (!audio_is_linear_pcm(format)) {
1110 continue;
1111 }
Eric Laurente6930022016-02-11 10:20:40 -08001112 if (AudioPort::isBetterFormatMatch(
1113 outputDesc->mFormat, bestFormat, format)) {
1114 outputForFormat = outputs[i];
1115 bestFormat = outputDesc->mFormat;
1116 }
Eric Laurent8838a382014-09-08 16:44:28 -07001117 }
1118
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001119 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001120 if (commonFlags >= maxCommonFlags) {
1121 if (commonFlags == maxCommonFlags) {
1122 if (AudioPort::isBetterFormatMatch(
1123 outputDesc->mFormat, bestFormatForFlags, format)) {
1124 outputForFlags = outputs[i];
1125 bestFormatForFlags = outputDesc->mFormat;
1126 }
1127 } else {
1128 outputForFlags = outputs[i];
1129 maxCommonFlags = commonFlags;
1130 bestFormatForFlags = outputDesc->mFormat;
1131 }
Eric Laurente552edb2014-03-10 17:42:56 -07001132 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1133 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001134 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001135 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001136 }
1137 }
1138 }
1139
Eric Laurente6930022016-02-11 10:20:40 -08001140 if (outputForFlags != 0) {
1141 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001142 }
Eric Laurente6930022016-02-11 10:20:40 -08001143 if (outputForFormat != 0) {
1144 return outputForFormat;
1145 }
1146 if (outputForPrimary != 0) {
1147 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001148 }
1149
1150 return outputs[0];
1151}
1152
Eric Laurente0720872014-03-11 09:30:41 -07001153status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001154 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001155 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001156{
Paul McLeanaa981192015-03-21 09:55:15 -07001157 ALOGV("startOutput() output %d, stream %d, session %d",
1158 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001159 ssize_t index = mOutputs.indexOfKey(output);
1160 if (index < 0) {
1161 ALOGW("startOutput() unknown output %d", output);
1162 return BAD_VALUE;
1163 }
1164
Eric Laurentc75307b2015-03-17 15:29:32 -07001165 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1166
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001167 // Routing?
1168 mOutputRoutes.incRouteActivity(session);
1169
Eric Laurentc75307b2015-03-17 15:29:32 -07001170 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001171 AudioMix *policyMix = NULL;
1172 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001173 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001174 policyMix = outputDesc->mPolicyMix;
1175 address = policyMix->mDeviceAddress.string();
1176 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1177 newDevice = policyMix->mDeviceType;
1178 } else {
1179 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1180 }
Eric Laurent493404d2015-04-21 15:07:36 -07001181 } else if (mOutputRoutes.hasRouteChanged(session)) {
1182 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001183 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001184 } else {
1185 newDevice = AUDIO_DEVICE_NONE;
1186 }
1187
1188 uint32_t delayMs = 0;
1189
Eric Laurentc40d9692016-04-13 19:14:13 -07001190 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001191
1192 if (status != NO_ERROR) {
1193 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001194 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001195 }
1196 // Automatically enable the remote submix input when output is started on a re routing mix
1197 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001198 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1199 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001200 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1201 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001202 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001203 "remote-submix");
1204 }
1205
1206 if (delayMs != 0) {
1207 usleep(delayMs * 1000);
1208 }
1209
1210 return status;
1211}
1212
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001213status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001214 audio_stream_type_t stream,
1215 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001216 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001217 uint32_t *delayMs)
1218{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001219 // cannot start playback of STREAM_TTS if any other output is being used
1220 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001221
1222 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001223 if (stream == AUDIO_STREAM_TTS) {
1224 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001225 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001226 return INVALID_OPERATION;
1227 } else {
1228 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1229 }
1230 } else {
1231 // some playback other than beacon starts
1232 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1233 }
1234
Eric Laurent77305a62016-07-25 16:39:22 -07001235 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001236 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001237 bool force = !outputDesc->isActive() &&
1238 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001239
Eric Laurente552edb2014-03-10 17:42:56 -07001240 // increment usage count for this stream on the requested output:
1241 // NOTE that the usage count is the same for duplicated output and hardware output which is
1242 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1243 outputDesc->changeRefCount(stream, 1);
1244
Eric Laurent493404d2015-04-21 15:07:36 -07001245 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001246 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001247 if (device == AUDIO_DEVICE_NONE) {
1248 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001249 }
Eric Laurente552edb2014-03-10 17:42:56 -07001250 routing_strategy strategy = getStrategy(stream);
1251 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001252 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1253 (beaconMuteLatency > 0);
1254 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001255 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001256 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001257 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001258 // force a device change if any other output is:
1259 // - managed by the same hw module
1260 // - has a current device selection that differs from selected device.
1261 // - supports currently selected device
1262 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001263 // In this case, the audio HAL must receive the new device selection so that it can
1264 // change the device currently selected by the other active output.
1265 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001266 desc->device() != device &&
1267 desc->supportedDevices() & device &&
1268 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001269 force = true;
1270 }
1271 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001272 // a notification so that audio focus effect can propagate, or that a mute/unmute
1273 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001274 uint32_t latency = desc->latency();
1275 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1276 waitMs = latency;
1277 }
1278 }
1279 }
Eric Laurentdc462862016-07-19 12:29:53 -07001280 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001281
1282 // handle special case for sonification while in call
1283 if (isInCall()) {
1284 handleIncallSonification(stream, true, false);
1285 }
1286
1287 // apply volume rules for current stream and device if necessary
1288 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001289 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001290 outputDesc,
1291 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001292
1293 // update the outputs if starting an output with a stream that can affect notification
1294 // routing
1295 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001296
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001297 // force reevaluating accessibility routing when ringtone or alarm starts
1298 if (strategy == STRATEGY_SONIFICATION) {
1299 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1300 }
Eric Laurentdc462862016-07-19 12:29:53 -07001301
1302 if (waitMs > muteWaitMs) {
1303 *delayMs = waitMs - muteWaitMs;
1304 }
Eric Laurente552edb2014-03-10 17:42:56 -07001305 }
Eric Laurentdc462862016-07-19 12:29:53 -07001306
Eric Laurente552edb2014-03-10 17:42:56 -07001307 return NO_ERROR;
1308}
1309
1310
Eric Laurente0720872014-03-11 09:30:41 -07001311status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001312 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001313 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001314{
1315 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1316 ssize_t index = mOutputs.indexOfKey(output);
1317 if (index < 0) {
1318 ALOGW("stopOutput() unknown output %d", output);
1319 return BAD_VALUE;
1320 }
1321
Eric Laurentc75307b2015-03-17 15:29:32 -07001322 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001323
Eric Laurentc75307b2015-03-17 15:29:32 -07001324 if (outputDesc->mRefCount[stream] == 1) {
1325 // Automatically disable the remote submix input when output is stopped on a
1326 // re routing mix of type MIX_TYPE_RECORDERS
1327 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1328 outputDesc->mPolicyMix != NULL &&
1329 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1330 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1331 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001332 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001333 "remote-submix");
1334 }
1335 }
1336
1337 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001338 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001340 int activityCount = mOutputRoutes.decRouteActivity(session);
1341 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1342
1343 if (forceDeviceUpdate) {
1344 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1345 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 }
1347
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001348 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001349}
1350
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001351status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001352 audio_stream_type_t stream,
1353 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001354{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001355 // always handle stream stop, check which stream type is stopping
1356 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1357
Eric Laurente552edb2014-03-10 17:42:56 -07001358 // handle special case for sonification while in call
1359 if (isInCall()) {
1360 handleIncallSonification(stream, false, false);
1361 }
1362
1363 if (outputDesc->mRefCount[stream] > 0) {
1364 // decrement usage count of this stream on the output
1365 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001366
Eric Laurente552edb2014-03-10 17:42:56 -07001367 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001368 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001369 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001370 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001371 // delay the device switch by twice the latency because stopOutput() is executed when
1372 // the track stop() command is received and at that time the audio track buffer can
1373 // still contain data that needs to be drained. The latency only covers the audio HAL
1374 // and kernel buffers. Also the latency does not always include additional delay in the
1375 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001376 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001377
1378 // force restoring the device selection on other active outputs if it differs from the
1379 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001380 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001381 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001382 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001383 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001384 desc->isActive() &&
1385 outputDesc->sharesHwModuleWith(desc) &&
1386 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001387 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1388 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001389 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001390 newDevice2,
1391 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001392 delayMs);
1393 // re-apply device specific volume if not done by setOutputDevice()
1394 if (!force) {
1395 applyStreamVolumes(desc, newDevice2, delayMs);
1396 }
Eric Laurente552edb2014-03-10 17:42:56 -07001397 }
1398 }
1399 // update the outputs if stopping one with a stream that can affect notification routing
1400 handleNotificationRoutingForStream(stream);
1401 }
1402 return NO_ERROR;
1403 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001404 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001405 return INVALID_OPERATION;
1406 }
1407}
1408
Eric Laurente83b55d2014-11-14 10:06:21 -08001409void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001410 audio_stream_type_t stream __unused,
1411 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001412{
1413 ALOGV("releaseOutput() %d", output);
1414 ssize_t index = mOutputs.indexOfKey(output);
1415 if (index < 0) {
1416 ALOGW("releaseOutput() releasing unknown output %d", output);
1417 return;
1418 }
1419
1420#ifdef AUDIO_POLICY_TEST
1421 int testIndex = testOutputIndex(output);
1422 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001423 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001424 if (outputDesc->isActive()) {
1425 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001426 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001427 mTestOutputs[testIndex] = 0;
1428 }
1429 return;
1430 }
1431#endif //AUDIO_POLICY_TEST
1432
Paul McLeanaa981192015-03-21 09:55:15 -07001433 // Routing
1434 mOutputRoutes.removeRoute(session);
1435
Eric Laurentc75307b2015-03-17 15:29:32 -07001436 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001437 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001438 if (desc->mDirectOpenCount <= 0) {
1439 ALOGW("releaseOutput() invalid open count %d for output %d",
1440 desc->mDirectOpenCount, output);
1441 return;
1442 }
1443 if (--desc->mDirectOpenCount == 0) {
1444 closeOutput(output);
1445 // If effects where present on the output, audioflinger moved them to the primary
1446 // output by default: move them back to the appropriate output.
1447 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001448 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001449 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1450 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001451 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001452 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001453 }
1454 }
1455}
1456
1457
Eric Laurentcaf7f482014-11-25 17:50:47 -08001458status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1459 audio_io_handle_t *input,
1460 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001461 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001462 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001463 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001464 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001465 input_type_t *inputType,
1466 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001467{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001468 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1469 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001470 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001471
Eric Laurentcaf7f482014-11-25 17:50:47 -08001472 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001473 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001474
Eric Laurent275e8e92014-11-30 15:14:47 -08001475 audio_devices_t device;
1476 // handle legacy remote submix case where the address was not always specified
1477 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001478 audio_source_t inputSource = attr->source;
1479 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001480 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001481
Eric Laurentc447ded2015-01-06 08:47:05 -08001482 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1483 inputSource = AUDIO_SOURCE_MIC;
1484 }
1485 halInputSource = inputSource;
1486
Eric Laurent20b9ef02016-12-05 11:03:16 -08001487 // TODO: check for existing client for this port ID
1488 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1489 *portId = AudioPort::getNextUniqueId();
1490 }
1491
Paul McLean466dc8e2015-04-17 13:15:36 -06001492 // Explicit routing?
1493 sp<DeviceDescriptor> deviceDesc;
1494 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1495 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1496 deviceDesc = mAvailableInputDevices[i];
1497 break;
1498 }
1499 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001500 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001501
Eric Laurentc447ded2015-01-06 08:47:05 -08001502 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001503 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001504 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001505 if (ret != NO_ERROR) {
1506 return ret;
1507 }
1508 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001509 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1510 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001511 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001512 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001513 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001514 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001515 return BAD_VALUE;
1516 }
Eric Laurentc722f302014-12-10 11:21:49 -08001517 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001518 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001519 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1520 // there is an external policy, but this input is attached to a mix of recorders,
1521 // meaning it receives audio injected into the framework, so the recorder doesn't
1522 // know about it and is therefore considered "legacy"
1523 *inputType = API_INPUT_LEGACY;
1524 } else {
1525 // recording a mix of players defined by an external policy, we're rerouting for
1526 // an external policy
1527 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1528 }
Eric Laurentc722f302014-12-10 11:21:49 -08001529 } else if (audio_is_remote_submix_device(device)) {
1530 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001531 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001532 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1533 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001534 } else {
1535 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001536 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001537
Eric Laurent599c7582015-12-07 18:05:55 -08001538 }
1539
1540 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001541 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001542 policyMix);
1543 if (*input == AUDIO_IO_HANDLE_NONE) {
1544 mInputRoutes.removeRoute(session);
1545 return INVALID_OPERATION;
1546 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001547
Eric Laurent599c7582015-12-07 18:05:55 -08001548 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1549 return NO_ERROR;
1550}
1551
1552
1553audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1554 String8 address,
1555 audio_session_t session,
1556 uid_t uid,
1557 audio_source_t inputSource,
1558 uint32_t samplingRate,
1559 audio_format_t format,
1560 audio_channel_mask_t channelMask,
1561 audio_input_flags_t flags,
1562 AudioMix *policyMix)
1563{
1564 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1565 audio_source_t halInputSource = inputSource;
1566 bool isSoundTrigger = false;
1567
1568 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1569 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1570 if (index >= 0) {
1571 input = mSoundTriggerSessions.valueFor(session);
1572 isSoundTrigger = true;
1573 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1574 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1575 } else {
1576 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001577 }
1578 }
1579
Andy Hungf129b032015-04-07 13:45:50 -07001580 // find a compatible input profile (not necessarily identical in parameters)
1581 sp<IOProfile> profile;
1582 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001583 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001584 audio_format_t profileFormat = format;
1585 audio_channel_mask_t profileChannelMask = channelMask;
1586 audio_input_flags_t profileFlags = flags;
1587 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001588 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001589 profileSamplingRate, profileFormat, profileChannelMask,
1590 profileFlags);
1591 if (profile != 0) {
1592 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001593 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1594 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001595 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1596 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1597 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001598 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1599 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001600 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001601 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001602 }
Eric Laurente552edb2014-03-10 17:42:56 -07001603 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001604 // Pick input sampling rate if not specified by client
1605 if (samplingRate == 0) {
1606 samplingRate = profileSamplingRate;
1607 }
Eric Laurente552edb2014-03-10 17:42:56 -07001608
Eric Laurent322b4d22015-04-03 15:57:54 -07001609 if (profile->getModuleHandle() == 0) {
1610 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001611 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001612 }
1613
Eric Laurent599c7582015-12-07 18:05:55 -08001614 sp<AudioSession> audioSession = new AudioSession(session,
1615 inputSource,
1616 format,
1617 samplingRate,
1618 channelMask,
1619 flags,
1620 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001621 isSoundTrigger,
1622 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001623
Eric Laurentfb66dd92016-01-28 18:32:03 -08001624
Eric Laurent599c7582015-12-07 18:05:55 -08001625 // reuse an open input if possible
1626 for (size_t i = 0; i < mInputs.size(); i++) {
1627 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001628 // reuse input if:
1629 // - it shares the same profile
1630 // AND
1631 // - it is not a reroute submix input
1632 // AND
1633 // - it is: not used for sound trigger
1634 // OR
1635 // used for sound trigger and all clients use the same session ID
1636 //
1637 if ((profile == desc->mProfile) &&
1638 (isSoundTrigger == desc->isSoundTrigger()) &&
1639 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001640
1641 sp<AudioSession> as = desc->getAudioSession(session);
1642 if (as != 0) {
1643 // do not allow unmatching properties on same session
1644 if (as->matches(audioSession)) {
1645 as->changeOpenCount(1);
1646 } else {
1647 ALOGW("getInputForDevice() record with different attributes"
1648 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001649 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001650 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001651 } else if (isSoundTrigger) {
1652 break;
1653 }
1654 // force close input if current source is now the highest priority request on this input
1655 // and current input properties are not exactly as requested.
1656 if ((desc->mSamplingRate != samplingRate ||
1657 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001658 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001659 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1660 source_priority(inputSource))) {
1661 ALOGV("%s: ", __FUNCTION__);
1662 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1663 for (size_t j = 0; j < sessions.size(); j++) {
1664 audio_session_t currentSession = sessions.keyAt(j);
1665 stopInput(desc->mIoHandle, currentSession);
1666 releaseInput(desc->mIoHandle, currentSession);
1667 }
1668 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001669 } else {
1670 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001671 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1672 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001673 }
Eric Laurent599c7582015-12-07 18:05:55 -08001674 }
1675 }
Eric Laurent599c7582015-12-07 18:05:55 -08001676
Eric Laurentcf2c0212014-07-25 16:20:43 -07001677 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001678 config.sample_rate = profileSamplingRate;
1679 config.channel_mask = profileChannelMask;
1680 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001681
Eric Laurent322b4d22015-04-03 15:57:54 -07001682 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001683 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001684 &config,
1685 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001686 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001687 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001688 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001689
1690 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001691 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001692 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001693 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001694 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001695 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1696 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001697 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001698 if (input != AUDIO_IO_HANDLE_NONE) {
1699 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001700 }
Eric Laurent599c7582015-12-07 18:05:55 -08001701 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001702 }
1703
Eric Laurent1f2f2232014-06-02 12:01:23 -07001704 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001705 inputDesc->mSamplingRate = profileSamplingRate;
1706 inputDesc->mFormat = profileFormat;
1707 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001708 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001709 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001710 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001711
Eric Laurent599c7582015-12-07 18:05:55 -08001712 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001713 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001714
Eric Laurent599c7582015-12-07 18:05:55 -08001715 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001716}
1717
Eric Laurentfb66dd92016-01-28 18:32:03 -08001718bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1719 const sp<AudioSession>& audioSession)
1720{
1721 // Do not allow capture if an active voice call is using a software patch and
1722 // the call TX source device is on the same HW module.
1723 // FIXME: would be better to refine to only inputs whose profile connects to the
1724 // call TX device but this information is not in the audio patch
1725 if (mCallTxPatch != 0 &&
1726 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1727 return false;
1728 }
1729
1730 // starting concurrent capture is enabled if:
1731 // 1) capturing for re-routing
1732 // 2) capturing for HOTWORD source
1733 // 3) capturing for FM TUNER source
1734 // 3) All other active captures are either for re-routing or HOTWORD
1735
1736 if (is_virtual_input_device(inputDesc->mDevice) ||
1737 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1738 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1739 return true;
1740 }
1741
1742 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1743 for (size_t i = 0; i < activeInputs.size(); i++) {
1744 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1745 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1746 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1747 !is_virtual_input_device(activeInput->mDevice)) {
1748 return false;
1749 }
1750 }
1751
1752 return true;
1753}
1754
1755
Eric Laurent4dc68062014-07-28 17:26:49 -07001756status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001757 audio_session_t session,
1758 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001759{
1760 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001761 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001762 ssize_t index = mInputs.indexOfKey(input);
1763 if (index < 0) {
1764 ALOGW("startInput() unknown input %d", input);
1765 return BAD_VALUE;
1766 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001767 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001768
Eric Laurent599c7582015-12-07 18:05:55 -08001769 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1770 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001771 ALOGW("startInput() unknown session %d on input %d", session, input);
1772 return BAD_VALUE;
1773 }
1774
Eric Laurentfb66dd92016-01-28 18:32:03 -08001775 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1776 ALOGW("startInput(%d) failed: other input already started", input);
1777 return INVALID_OPERATION;
1778 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001779
Eric Laurentfb66dd92016-01-28 18:32:03 -08001780 if (isInCall()) {
1781 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1782 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001783 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001784 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001785 }
1786
Eric Laurent313d1e72016-01-29 09:56:57 -08001787 // increment activity count before calling getNewInputDevice() below as only active sessions
1788 // are considered for device selection
1789 audioSession->changeActiveCount(1);
1790
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001791 // Routing?
1792 mInputRoutes.incRouteActivity(session);
1793
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001794 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001795 // indicate active capture to sound trigger service if starting capture from a mic on
1796 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001797 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001798 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001799
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001800 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1801 // if input maps to a dynamic policy with an activity listener, notify of state change
1802 if ((inputDesc->mPolicyMix != NULL)
1803 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1804 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1805 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001806 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001807
Eric Laurentf7c50102016-09-30 15:19:43 -07001808 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1809 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001810 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001811 SoundTrigger::setCaptureState(true);
1812 }
1813
1814 // automatically enable the remote submix output when input is started if not
1815 // used by a policy mix of type MIX_TYPE_RECORDERS
1816 // For remote submix (a virtual device), we open only one input per capture request.
1817 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1818 String8 address = String8("");
1819 if (inputDesc->mPolicyMix == NULL) {
1820 address = String8("0");
1821 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1822 address = inputDesc->mPolicyMix->mDeviceAddress;
1823 }
1824 if (address != "") {
1825 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1826 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1827 address, "remote-submix");
1828 }
Eric Laurentc722f302014-12-10 11:21:49 -08001829 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001830 }
Eric Laurente552edb2014-03-10 17:42:56 -07001831 }
1832
Eric Laurent599c7582015-12-07 18:05:55 -08001833 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001834
Eric Laurente552edb2014-03-10 17:42:56 -07001835 return NO_ERROR;
1836}
1837
Eric Laurent4dc68062014-07-28 17:26:49 -07001838status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1839 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001840{
1841 ALOGV("stopInput() input %d", input);
1842 ssize_t index = mInputs.indexOfKey(input);
1843 if (index < 0) {
1844 ALOGW("stopInput() unknown input %d", input);
1845 return BAD_VALUE;
1846 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001847 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001848
Eric Laurent599c7582015-12-07 18:05:55 -08001849 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001850 if (index < 0) {
1851 ALOGW("stopInput() unknown session %d on input %d", session, input);
1852 return BAD_VALUE;
1853 }
1854
Eric Laurent599c7582015-12-07 18:05:55 -08001855 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001856 ALOGW("stopInput() input %d already stopped", input);
1857 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001858 }
1859
Eric Laurent599c7582015-12-07 18:05:55 -08001860 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001861
1862 // Routing?
1863 mInputRoutes.decRouteActivity(session);
1864
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001865 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001866
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001867 if (inputDesc->isActive()) {
1868 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1869 } else {
1870 // if input maps to a dynamic policy with an activity listener, notify of state change
1871 if ((inputDesc->mPolicyMix != NULL)
1872 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1873 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1874 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001875 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001876
1877 // automatically disable the remote submix output when input is stopped if not
1878 // used by a policy mix of type MIX_TYPE_RECORDERS
1879 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1880 String8 address = String8("");
1881 if (inputDesc->mPolicyMix == NULL) {
1882 address = String8("0");
1883 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1884 address = inputDesc->mPolicyMix->mDeviceAddress;
1885 }
1886 if (address != "") {
1887 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1888 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1889 address, "remote-submix");
1890 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001891 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001892
Eric Laurentf7c50102016-09-30 15:19:43 -07001893 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001894 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001895
Eric Laurentf7c50102016-09-30 15:19:43 -07001896 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1897 // primary HW module
1898 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1899 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1900 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001901 SoundTrigger::setCaptureState(false);
1902 }
1903 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001904 }
Eric Laurente552edb2014-03-10 17:42:56 -07001905 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001906 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001907}
1908
Eric Laurent4dc68062014-07-28 17:26:49 -07001909void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1910 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001911{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001912
Eric Laurente552edb2014-03-10 17:42:56 -07001913 ALOGV("releaseInput() %d", input);
1914 ssize_t index = mInputs.indexOfKey(input);
1915 if (index < 0) {
1916 ALOGW("releaseInput() releasing unknown input %d", input);
1917 return;
1918 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001919
1920 // Routing
1921 mInputRoutes.removeRoute(session);
1922
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001923 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1924 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001925
Eric Laurent599c7582015-12-07 18:05:55 -08001926 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001927 if (index < 0) {
1928 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1929 return;
1930 }
Eric Laurent599c7582015-12-07 18:05:55 -08001931
1932 if (audioSession->openCount() == 0) {
1933 ALOGW("releaseInput() invalid open count %d on session %d",
1934 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001935 return;
1936 }
Eric Laurent599c7582015-12-07 18:05:55 -08001937
1938 if (audioSession->changeOpenCount(-1) == 0) {
1939 inputDesc->removeAudioSession(session);
1940 }
1941
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001942 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001943 ALOGV("releaseInput() exit > 0");
1944 return;
1945 }
1946
Eric Laurent05b90f82014-08-27 15:32:29 -07001947 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001948 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001949 ALOGV("releaseInput() exit");
1950}
1951
Eric Laurentd4692962014-05-05 18:13:44 -07001952void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001953 bool patchRemoved = false;
1954
Eric Laurentd4692962014-05-05 18:13:44 -07001955 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001956 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001957 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001958 if (patch_index >= 0) {
1959 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001960 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001961 mAudioPatches.removeItemsAt(patch_index);
1962 patchRemoved = true;
1963 }
Eric Laurentd4692962014-05-05 18:13:44 -07001964 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1965 }
1966 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001967 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001968 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001969
1970 if (patchRemoved) {
1971 mpClientInterface->onAudioPatchListUpdate();
1972 }
Eric Laurentd4692962014-05-05 18:13:44 -07001973}
1974
Eric Laurente0720872014-03-11 09:30:41 -07001975void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001976 int indexMin,
1977 int indexMax)
1978{
1979 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001980 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001981
1982 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001983 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1984 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001985 continue;
1986 }
1987 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001988 }
Eric Laurente552edb2014-03-10 17:42:56 -07001989}
1990
Eric Laurente0720872014-03-11 09:30:41 -07001991status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001992 int index,
1993 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001994{
1995
François Gaffied1ab2bd2015-12-02 18:20:06 +01001996 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1997 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001998 return BAD_VALUE;
1999 }
2000 if (!audio_is_output_device(device)) {
2001 return BAD_VALUE;
2002 }
2003
2004 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002005 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002006
Eric Laurent1fd372e2016-04-06 14:23:53 -07002007 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002008 stream, device, index);
2009
Eric Laurent28d09f02016-03-08 10:43:05 -08002010 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002011 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2012 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002013 continue;
2014 }
2015 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2016 }
Eric Laurente552edb2014-03-10 17:42:56 -07002017
Eric Laurent1fd372e2016-04-06 14:23:53 -07002018 // update volume on all outputs and streams matching the following:
2019 // - The requested stream (or a stream matching for volume control) is active on the output
2020 // - The device (or devices) selected by the strategy corresponding to this stream includes
2021 // the requested device
2022 // - For non default requested device, currently selected device on the output is either the
2023 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002024 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2025 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002026 status_t status = NO_ERROR;
2027 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002028 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2029 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002030 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2031 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002032 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002033 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002034 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2035 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002036 continue;
2037 }
Eric Laurent794fde22016-03-11 09:50:45 -08002038 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002039 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
2040 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2041 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002042 continue;
2043 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002044 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002045 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002046 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002047 applyVolume = (curDevice & curStreamDevice) != 0;
2048 } else {
2049 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
2050 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07002051 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002052
Eric Laurente76f29c2016-09-14 17:17:53 -07002053 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002054 //FIXME: workaround for truncated touch sounds
2055 // delayed volume change for system stream to be removed when the problem is
2056 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002057 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002058 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2059 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002060 if (volStatus != NO_ERROR) {
2061 status = volStatus;
2062 }
2063 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002064 }
Eric Laurente552edb2014-03-10 17:42:56 -07002065 }
2066 return status;
2067}
2068
Eric Laurente0720872014-03-11 09:30:41 -07002069status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002070 int *index,
2071 audio_devices_t device)
2072{
2073 if (index == NULL) {
2074 return BAD_VALUE;
2075 }
2076 if (!audio_is_output_device(device)) {
2077 return BAD_VALUE;
2078 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002079 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002080 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002081 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002082 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2083 }
François Gaffiedfd74092015-03-19 12:10:59 +01002084 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002085
François Gaffied1ab2bd2015-12-02 18:20:06 +01002086 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002087 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2088 return NO_ERROR;
2089}
2090
Eric Laurente0720872014-03-11 09:30:41 -07002091audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002092 const SortedVector<audio_io_handle_t>& outputs)
2093{
2094 // select one output among several suitable for global effects.
2095 // The priority is as follows:
2096 // 1: An offloaded output. If the effect ends up not being offloadable,
2097 // AudioFlinger will invalidate the track and the offloaded output
2098 // will be closed causing the effect to be moved to a PCM output.
2099 // 2: A deep buffer output
2100 // 3: the first output in the list
2101
2102 if (outputs.size() == 0) {
2103 return 0;
2104 }
2105
2106 audio_io_handle_t outputOffloaded = 0;
2107 audio_io_handle_t outputDeepBuffer = 0;
2108
2109 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002110 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002111 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002112 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2113 outputOffloaded = outputs[i];
2114 }
2115 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2116 outputDeepBuffer = outputs[i];
2117 }
2118 }
2119
2120 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2121 outputOffloaded, outputDeepBuffer);
2122 if (outputOffloaded != 0) {
2123 return outputOffloaded;
2124 }
2125 if (outputDeepBuffer != 0) {
2126 return outputDeepBuffer;
2127 }
2128
2129 return outputs[0];
2130}
2131
Eric Laurente0720872014-03-11 09:30:41 -07002132audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002133{
2134 // apply simple rule where global effects are attached to the same output as MUSIC streams
2135
Eric Laurent3b73df72014-03-11 09:06:29 -07002136 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002137 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2138 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2139
2140 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2141 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2142 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2143
2144 return output;
2145}
2146
Eric Laurente0720872014-03-11 09:30:41 -07002147status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002148 audio_io_handle_t io,
2149 uint32_t strategy,
2150 int session,
2151 int id)
2152{
2153 ssize_t index = mOutputs.indexOfKey(io);
2154 if (index < 0) {
2155 index = mInputs.indexOfKey(io);
2156 if (index < 0) {
2157 ALOGW("registerEffect() unknown io %d", io);
2158 return INVALID_OPERATION;
2159 }
2160 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002161 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002162}
2163
Eric Laurentc75307b2015-03-17 15:29:32 -07002164bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2165{
Eric Laurent28d09f02016-03-08 10:43:05 -08002166 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002167 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2168 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002169 continue;
2170 }
2171 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2172 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002173 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002174}
2175
2176bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2177{
2178 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2179}
2180
Eric Laurente0720872014-03-11 09:30:41 -07002181bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002182{
2183 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002184 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002185 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002186 return true;
2187 }
2188 }
2189 return false;
2190}
2191
Eric Laurent275e8e92014-11-30 15:14:47 -08002192// Register a list of custom mixes with their attributes and format.
2193// When a mix is registered, corresponding input and output profiles are
2194// added to the remote submix hw module. The profile contains only the
2195// parameters (sampling rate, format...) specified by the mix.
2196// The corresponding input remote submix device is also connected.
2197//
2198// When a remote submix device is connected, the address is checked to select the
2199// appropriate profile and the corresponding input or output stream is opened.
2200//
2201// When capture starts, getInputForAttr() will:
2202// - 1 look for a mix matching the address passed in attribtutes tags if any
2203// - 2 if none found, getDeviceForInputSource() will:
2204// - 2.1 look for a mix matching the attributes source
2205// - 2.2 if none found, default to device selection by policy rules
2206// At this time, the corresponding output remote submix device is also connected
2207// and active playback use cases can be transferred to this mix if needed when reconnecting
2208// after AudioTracks are invalidated
2209//
2210// When playback starts, getOutputForAttr() will:
2211// - 1 look for a mix matching the address passed in attribtutes tags if any
2212// - 2 if none found, look for a mix matching the attributes usage
2213// - 3 if none found, default to device and output selection by policy rules.
2214
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002215status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002216{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002217 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2218 status_t res = NO_ERROR;
2219
2220 sp<HwModule> rSubmixModule;
2221 // examine each mix's route type
2222 for (size_t i = 0; i < mixes.size(); i++) {
2223 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2224 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2225 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002226 break;
2227 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002228 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2229 // Loop back through "remote submix"
2230 if (rSubmixModule == 0) {
2231 for (size_t j = 0; i < mHwModules.size(); j++) {
2232 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2233 && mHwModules[j]->mHandle != 0) {
2234 rSubmixModule = mHwModules[j];
2235 break;
2236 }
2237 }
2238 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002239
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002240 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002241
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002242 if (rSubmixModule == 0) {
2243 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2244 res = INVALID_OPERATION;
2245 break;
2246 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002247
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002248 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002249
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002250 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002251 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002252 res = INVALID_OPERATION;
2253 break;
2254 }
2255 audio_config_t outputConfig = mixes[i].mFormat;
2256 audio_config_t inputConfig = mixes[i].mFormat;
2257 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2258 // stereo and let audio flinger do the channel conversion if needed.
2259 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2260 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2261 rSubmixModule->addOutputProfile(address, &outputConfig,
2262 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2263 rSubmixModule->addInputProfile(address, &inputConfig,
2264 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002265
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002266 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2267 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2268 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2269 address.string(), "remote-submix");
2270 } else {
2271 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2272 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2273 address.string(), "remote-submix");
2274 }
2275 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002276 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002277 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002278 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2279 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002280
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002281 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002282 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2283 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2284 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2285 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2286 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2287 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002288 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2289 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002290 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2291 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002292 } else {
2293 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002294 }
2295 break;
2296 }
2297 }
2298
2299 if (res != NO_ERROR) {
2300 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002301 i, device, address.string());
2302 res = INVALID_OPERATION;
2303 break;
2304 } else if (!foundOutput) {
2305 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2306 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002307 res = INVALID_OPERATION;
2308 break;
2309 }
Eric Laurentc722f302014-12-10 11:21:49 -08002310 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002311 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002312 if (res != NO_ERROR) {
2313 unregisterPolicyMixes(mixes);
2314 }
2315 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002316}
2317
2318status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2319{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002320 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002321 status_t res = NO_ERROR;
2322 sp<HwModule> rSubmixModule;
2323 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002324 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002325 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002326
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002327 if (rSubmixModule == 0) {
2328 for (size_t j = 0; i < mHwModules.size(); j++) {
2329 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2330 && mHwModules[j]->mHandle != 0) {
2331 rSubmixModule = mHwModules[j];
2332 break;
2333 }
2334 }
2335 }
2336 if (rSubmixModule == 0) {
2337 res = INVALID_OPERATION;
2338 continue;
2339 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002340
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002341 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002342
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002343 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2344 res = INVALID_OPERATION;
2345 continue;
2346 }
2347
2348 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2349 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2350 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2351 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2352 address.string(), "remote-submix");
2353 }
2354 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2355 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2356 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2357 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2358 address.string(), "remote-submix");
2359 }
2360 rSubmixModule->removeOutputProfile(address);
2361 rSubmixModule->removeInputProfile(address);
2362
2363 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2364 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2365 res = INVALID_OPERATION;
2366 continue;
2367 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002368 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002369 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002370 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002371}
2372
Eric Laurente552edb2014-03-10 17:42:56 -07002373
Eric Laurente0720872014-03-11 09:30:41 -07002374status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002375{
2376 const size_t SIZE = 256;
2377 char buffer[SIZE];
2378 String8 result;
2379
2380 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2381 result.append(buffer);
2382
Eric Laurent87ffa392015-05-22 10:32:38 -07002383 snprintf(buffer, SIZE, " Primary Output: %d\n",
2384 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002385 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002386 std::string stateLiteral;
2387 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2388 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002389 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002390 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002391 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002392 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002393 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002394 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002395 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002396 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002397 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002398 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002399 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002400 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002401 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002402 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002403 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002404 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2405 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2406 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002407 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2408 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002409 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2410 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002411
François Gaffie2110e042015-03-24 08:41:51 +01002412 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002413
François Gaffie112b0af2015-11-19 16:13:25 +01002414 mAvailableOutputDevices.dump(fd, String8("Available output"));
2415 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002416 mHwModules.dump(fd);
2417 mOutputs.dump(fd);
2418 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002419 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002420 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002421 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002422
2423 return NO_ERROR;
2424}
2425
2426// This function checks for the parameters which can be offloaded.
2427// This can be enhanced depending on the capability of the DSP and policy
2428// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002429bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002430{
2431 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002432 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002433 offloadInfo.sample_rate, offloadInfo.channel_mask,
2434 offloadInfo.format,
2435 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2436 offloadInfo.has_video);
2437
Andy Hung2ddee192015-12-18 17:34:44 -08002438 if (mMasterMono) {
2439 return false; // no offloading if mono is set.
2440 }
2441
Eric Laurente552edb2014-03-10 17:42:56 -07002442 // Check if offload has been disabled
2443 char propValue[PROPERTY_VALUE_MAX];
2444 if (property_get("audio.offload.disable", propValue, "0")) {
2445 if (atoi(propValue) != 0) {
2446 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2447 return false;
2448 }
2449 }
2450
2451 // Check if stream type is music, then only allow offload as of now.
2452 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2453 {
2454 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2455 return false;
2456 }
2457
2458 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002459 const bool allowOffloadWithVideo =
2460 property_get_bool("audio.offload.video", false /* default_value */);
2461 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002462 ALOGV("isOffloadSupported: has_video == true, returning false");
2463 return false;
2464 }
2465
2466 //If duration is less than minimum value defined in property, return false
2467 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2468 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2469 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2470 return false;
2471 }
2472 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2473 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2474 return false;
2475 }
2476
2477 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2478 // creating an offloaded track and tearing it down immediately after start when audioflinger
2479 // detects there is an active non offloadable effect.
2480 // FIXME: We should check the audio session here but we do not have it in this context.
2481 // This may prevent offloading in rare situations where effects are left active by apps
2482 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002483 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002484 return false;
2485 }
2486
2487 // See if there is a profile to support this.
2488 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002489 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002490 offloadInfo.sample_rate,
2491 offloadInfo.format,
2492 offloadInfo.channel_mask,
2493 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002494 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2495 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002496}
2497
Eric Laurent6a94d692014-05-20 11:18:06 -07002498status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2499 audio_port_type_t type,
2500 unsigned int *num_ports,
2501 struct audio_port *ports,
2502 unsigned int *generation)
2503{
2504 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2505 generation == NULL) {
2506 return BAD_VALUE;
2507 }
2508 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2509 if (ports == NULL) {
2510 *num_ports = 0;
2511 }
2512
2513 size_t portsWritten = 0;
2514 size_t portsMax = *num_ports;
2515 *num_ports = 0;
2516 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002517 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2518 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002519 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002520 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2521 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2522 continue;
2523 }
2524 if (portsWritten < portsMax) {
2525 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2526 }
2527 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002528 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002529 }
2530 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002531 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2532 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2533 continue;
2534 }
2535 if (portsWritten < portsMax) {
2536 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2537 }
2538 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002539 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002540 }
2541 }
2542 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2543 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2544 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2545 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2546 }
2547 *num_ports += mInputs.size();
2548 }
2549 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002550 size_t numOutputs = 0;
2551 for (size_t i = 0; i < mOutputs.size(); i++) {
2552 if (!mOutputs[i]->isDuplicated()) {
2553 numOutputs++;
2554 if (portsWritten < portsMax) {
2555 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2556 }
2557 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002558 }
Eric Laurent84c70242014-06-23 08:46:27 -07002559 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002560 }
2561 }
2562 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002563 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002564 return NO_ERROR;
2565}
2566
2567status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2568{
2569 return NO_ERROR;
2570}
2571
Eric Laurent6a94d692014-05-20 11:18:06 -07002572status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2573 audio_patch_handle_t *handle,
2574 uid_t uid)
2575{
2576 ALOGV("createAudioPatch()");
2577
2578 if (handle == NULL || patch == NULL) {
2579 return BAD_VALUE;
2580 }
2581 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2582
Eric Laurent874c42872014-08-08 15:13:39 -07002583 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2584 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2585 return BAD_VALUE;
2586 }
2587 // only one source per audio patch supported for now
2588 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002589 return INVALID_OPERATION;
2590 }
Eric Laurent874c42872014-08-08 15:13:39 -07002591
2592 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002593 return INVALID_OPERATION;
2594 }
Eric Laurent874c42872014-08-08 15:13:39 -07002595 for (size_t i = 0; i < patch->num_sinks; i++) {
2596 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2597 return INVALID_OPERATION;
2598 }
2599 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002600
2601 sp<AudioPatch> patchDesc;
2602 ssize_t index = mAudioPatches.indexOfKey(*handle);
2603
Eric Laurent6a94d692014-05-20 11:18:06 -07002604 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2605 patch->sources[0].role,
2606 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002607#if LOG_NDEBUG == 0
2608 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002609 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002610 patch->sinks[i].role,
2611 patch->sinks[i].type);
2612 }
2613#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002614
2615 if (index >= 0) {
2616 patchDesc = mAudioPatches.valueAt(index);
2617 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2618 mUidCached, patchDesc->mUid, uid);
2619 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2620 return INVALID_OPERATION;
2621 }
2622 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002623 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002624 }
2625
2626 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002627 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002628 if (outputDesc == NULL) {
2629 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2630 return BAD_VALUE;
2631 }
Eric Laurent84c70242014-06-23 08:46:27 -07002632 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2633 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002634 if (patchDesc != 0) {
2635 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2636 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2637 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2638 return BAD_VALUE;
2639 }
2640 }
Eric Laurent874c42872014-08-08 15:13:39 -07002641 DeviceVector devices;
2642 for (size_t i = 0; i < patch->num_sinks; i++) {
2643 // Only support mix to devices connection
2644 // TODO add support for mix to mix connection
2645 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2646 ALOGV("createAudioPatch() source mix but sink is not a device");
2647 return INVALID_OPERATION;
2648 }
2649 sp<DeviceDescriptor> devDesc =
2650 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2651 if (devDesc == 0) {
2652 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2653 return BAD_VALUE;
2654 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002655
François Gaffie53615e22015-03-19 09:24:12 +01002656 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002657 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002658 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002659 NULL, // updatedSamplingRate
2660 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002661 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002662 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002663 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002664 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002665 ALOGV("createAudioPatch() profile not supported for device %08x",
2666 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002667 return INVALID_OPERATION;
2668 }
2669 devices.add(devDesc);
2670 }
2671 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002672 return INVALID_OPERATION;
2673 }
Eric Laurent874c42872014-08-08 15:13:39 -07002674
Eric Laurent6a94d692014-05-20 11:18:06 -07002675 // TODO: reconfigure output format and channels here
2676 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002677 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002678 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002679 index = mAudioPatches.indexOfKey(*handle);
2680 if (index >= 0) {
2681 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2682 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2683 }
2684 patchDesc = mAudioPatches.valueAt(index);
2685 patchDesc->mUid = uid;
2686 ALOGV("createAudioPatch() success");
2687 } else {
2688 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2689 return INVALID_OPERATION;
2690 }
2691 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2692 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2693 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002694 // only one sink supported when connecting an input device to a mix
2695 if (patch->num_sinks > 1) {
2696 return INVALID_OPERATION;
2697 }
François Gaffie53615e22015-03-19 09:24:12 +01002698 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002699 if (inputDesc == NULL) {
2700 return BAD_VALUE;
2701 }
2702 if (patchDesc != 0) {
2703 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2704 return BAD_VALUE;
2705 }
2706 }
2707 sp<DeviceDescriptor> devDesc =
2708 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2709 if (devDesc == 0) {
2710 return BAD_VALUE;
2711 }
2712
François Gaffie53615e22015-03-19 09:24:12 +01002713 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002714 devDesc->mAddress,
2715 patch->sinks[0].sample_rate,
2716 NULL, /*updatedSampleRate*/
2717 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002718 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002719 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002720 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002721 // FIXME for the parameter type,
2722 // and the NONE
2723 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002724 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002725 return INVALID_OPERATION;
2726 }
2727 // TODO: reconfigure output format and channels here
2728 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002729 devDesc->type(), inputDesc->mIoHandle);
2730 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002731 index = mAudioPatches.indexOfKey(*handle);
2732 if (index >= 0) {
2733 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2734 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2735 }
2736 patchDesc = mAudioPatches.valueAt(index);
2737 patchDesc->mUid = uid;
2738 ALOGV("createAudioPatch() success");
2739 } else {
2740 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2741 return INVALID_OPERATION;
2742 }
2743 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2744 // device to device connection
2745 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002746 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 return BAD_VALUE;
2748 }
2749 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002750 sp<DeviceDescriptor> srcDeviceDesc =
2751 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002752 if (srcDeviceDesc == 0) {
2753 return BAD_VALUE;
2754 }
Eric Laurent874c42872014-08-08 15:13:39 -07002755
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 //update source and sink with our own data as the data passed in the patch may
2757 // be incomplete.
2758 struct audio_patch newPatch = *patch;
2759 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002760
Eric Laurent874c42872014-08-08 15:13:39 -07002761 for (size_t i = 0; i < patch->num_sinks; i++) {
2762 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2763 ALOGV("createAudioPatch() source device but one sink is not a device");
2764 return INVALID_OPERATION;
2765 }
2766
2767 sp<DeviceDescriptor> sinkDeviceDesc =
2768 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2769 if (sinkDeviceDesc == 0) {
2770 return BAD_VALUE;
2771 }
2772 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2773
Eric Laurent3bcf8592015-04-03 12:13:24 -07002774 // create a software bridge in PatchPanel if:
2775 // - source and sink devices are on differnt HW modules OR
2776 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002777 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002778 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002779 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002780 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002781 return INVALID_OPERATION;
2782 }
Eric Laurent874c42872014-08-08 15:13:39 -07002783 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002784 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002785 // if the sink device is reachable via an opened output stream, request to go via
2786 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002787 audio_io_handle_t output = selectOutput(outputs,
2788 AUDIO_OUTPUT_FLAG_NONE,
2789 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002790 if (output != AUDIO_IO_HANDLE_NONE) {
2791 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2792 if (outputDesc->isDuplicated()) {
2793 return INVALID_OPERATION;
2794 }
2795 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002796 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002797 newPatch.num_sources = 2;
2798 }
Eric Laurent83b88082014-06-20 18:31:16 -07002799 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002800 }
2801 // TODO: check from routing capabilities in config file and other conflicting patches
2802
2803 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2804 if (index >= 0) {
2805 afPatchHandle = patchDesc->mAfPatchHandle;
2806 }
2807
2808 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2809 &afPatchHandle,
2810 0);
2811 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2812 status, afPatchHandle);
2813 if (status == NO_ERROR) {
2814 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002815 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 addAudioPatch(patchDesc->mHandle, patchDesc);
2817 } else {
2818 patchDesc->mPatch = newPatch;
2819 }
2820 patchDesc->mAfPatchHandle = afPatchHandle;
2821 *handle = patchDesc->mHandle;
2822 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002823 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002824 } else {
2825 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2826 status);
2827 return INVALID_OPERATION;
2828 }
2829 } else {
2830 return BAD_VALUE;
2831 }
2832 } else {
2833 return BAD_VALUE;
2834 }
2835 return NO_ERROR;
2836}
2837
2838status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2839 uid_t uid)
2840{
2841 ALOGV("releaseAudioPatch() patch %d", handle);
2842
2843 ssize_t index = mAudioPatches.indexOfKey(handle);
2844
2845 if (index < 0) {
2846 return BAD_VALUE;
2847 }
2848 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2849 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2850 mUidCached, patchDesc->mUid, uid);
2851 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2852 return INVALID_OPERATION;
2853 }
2854
2855 struct audio_patch *patch = &patchDesc->mPatch;
2856 patchDesc->mUid = mUidCached;
2857 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002858 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002859 if (outputDesc == NULL) {
2860 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2861 return BAD_VALUE;
2862 }
2863
Eric Laurentc75307b2015-03-17 15:29:32 -07002864 setOutputDevice(outputDesc,
2865 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002866 true,
2867 0,
2868 NULL);
2869 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2870 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002871 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002872 if (inputDesc == NULL) {
2873 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2874 return BAD_VALUE;
2875 }
2876 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002877 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 true,
2879 NULL);
2880 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2882 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2883 status, patchDesc->mAfPatchHandle);
2884 removeAudioPatch(patchDesc->mHandle);
2885 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002886 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002887 } else {
2888 return BAD_VALUE;
2889 }
2890 } else {
2891 return BAD_VALUE;
2892 }
2893 return NO_ERROR;
2894}
2895
2896status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2897 struct audio_patch *patches,
2898 unsigned int *generation)
2899{
François Gaffie53615e22015-03-19 09:24:12 +01002900 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002901 return BAD_VALUE;
2902 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002903 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002904 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002905}
2906
Eric Laurente1715a42014-05-20 11:30:42 -07002907status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002908{
Eric Laurente1715a42014-05-20 11:30:42 -07002909 ALOGV("setAudioPortConfig()");
2910
2911 if (config == NULL) {
2912 return BAD_VALUE;
2913 }
2914 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2915 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002916 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2917 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002918 }
2919
Eric Laurenta121f902014-06-03 13:32:54 -07002920 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002921 if (config->type == AUDIO_PORT_TYPE_MIX) {
2922 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002923 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002924 if (outputDesc == NULL) {
2925 return BAD_VALUE;
2926 }
Eric Laurent84c70242014-06-23 08:46:27 -07002927 ALOG_ASSERT(!outputDesc->isDuplicated(),
2928 "setAudioPortConfig() called on duplicated output %d",
2929 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002930 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002931 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002932 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002933 if (inputDesc == NULL) {
2934 return BAD_VALUE;
2935 }
Eric Laurenta121f902014-06-03 13:32:54 -07002936 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002937 } else {
2938 return BAD_VALUE;
2939 }
2940 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2941 sp<DeviceDescriptor> deviceDesc;
2942 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2943 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2944 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2945 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2946 } else {
2947 return BAD_VALUE;
2948 }
2949 if (deviceDesc == NULL) {
2950 return BAD_VALUE;
2951 }
Eric Laurenta121f902014-06-03 13:32:54 -07002952 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002953 } else {
2954 return BAD_VALUE;
2955 }
2956
Eric Laurenta121f902014-06-03 13:32:54 -07002957 struct audio_port_config backupConfig;
2958 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2959 if (status == NO_ERROR) {
2960 struct audio_port_config newConfig;
2961 audioPortConfig->toAudioPortConfig(&newConfig, config);
2962 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002963 }
Eric Laurenta121f902014-06-03 13:32:54 -07002964 if (status != NO_ERROR) {
2965 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002966 }
Eric Laurente1715a42014-05-20 11:30:42 -07002967
2968 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002969}
2970
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002971void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2972{
Eric Laurentd60560a2015-04-10 11:31:20 -07002973 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002974 clearAudioPatches(uid);
2975 clearSessionRoutes(uid);
2976}
2977
Eric Laurent6a94d692014-05-20 11:18:06 -07002978void AudioPolicyManager::clearAudioPatches(uid_t uid)
2979{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002980 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002981 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2982 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002983 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002984 }
2985 }
2986}
2987
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002988void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2989 audio_io_handle_t ouptutToSkip)
2990{
2991 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2992 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2993 for (size_t j = 0; j < mOutputs.size(); j++) {
2994 if (mOutputs.keyAt(j) == ouptutToSkip) {
2995 continue;
2996 }
2997 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2998 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2999 continue;
3000 }
3001 // If the default device for this strategy is on another output mix,
3002 // invalidate all tracks in this strategy to force re connection.
3003 // Otherwise select new device on the output mix.
3004 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003005 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003006 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3007 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3008 }
3009 }
3010 } else {
3011 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3012 setOutputDevice(outputDesc, newDevice, false);
3013 }
3014 }
3015}
3016
3017void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3018{
3019 // remove output routes associated with this uid
3020 SortedVector<routing_strategy> affectedStrategies;
3021 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3022 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3023 if (route->mUid == uid) {
3024 mOutputRoutes.removeItemsAt(i);
3025 if (route->mDeviceDescriptor != 0) {
3026 affectedStrategies.add(getStrategy(route->mStreamType));
3027 }
3028 }
3029 }
3030 // reroute outputs if necessary
3031 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3032 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3033 }
3034
3035 // remove input routes associated with this uid
3036 SortedVector<audio_source_t> affectedSources;
3037 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3038 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3039 if (route->mUid == uid) {
3040 mInputRoutes.removeItemsAt(i);
3041 if (route->mDeviceDescriptor != 0) {
3042 affectedSources.add(route->mSource);
3043 }
3044 }
3045 }
3046 // reroute inputs if necessary
3047 SortedVector<audio_io_handle_t> inputsToClose;
3048 for (size_t i = 0; i < mInputs.size(); i++) {
3049 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003050 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003051 inputsToClose.add(inputDesc->mIoHandle);
3052 }
3053 }
3054 for (size_t i = 0; i < inputsToClose.size(); i++) {
3055 closeInput(inputsToClose[i]);
3056 }
3057}
3058
Eric Laurentd60560a2015-04-10 11:31:20 -07003059void AudioPolicyManager::clearAudioSources(uid_t uid)
3060{
3061 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3062 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3063 if (sourceDesc->mUid == uid) {
3064 stopAudioSource(mAudioSources.keyAt(i));
3065 }
3066 }
3067}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003068
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003069status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3070 audio_io_handle_t *ioHandle,
3071 audio_devices_t *device)
3072{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003073 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3074 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003075 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003076
François Gaffiedf372692015-03-19 10:43:27 +01003077 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003078}
3079
Eric Laurentd60560a2015-04-10 11:31:20 -07003080status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3081 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003082 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003083 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003084{
Eric Laurentd60560a2015-04-10 11:31:20 -07003085 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3086 if (source == NULL || attributes == NULL || handle == NULL) {
3087 return BAD_VALUE;
3088 }
3089
Glenn Kasten559d4392016-03-29 13:42:57 -07003090 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003091
3092 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3093 source->type != AUDIO_PORT_TYPE_DEVICE) {
3094 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3095 return INVALID_OPERATION;
3096 }
3097
3098 sp<DeviceDescriptor> srcDeviceDesc =
3099 mAvailableInputDevices.getDevice(source->ext.device.type,
3100 String8(source->ext.device.address));
3101 if (srcDeviceDesc == 0) {
3102 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3103 return BAD_VALUE;
3104 }
3105 sp<AudioSourceDescriptor> sourceDesc =
3106 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3107
3108 struct audio_patch dummyPatch;
3109 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3110 sourceDesc->mPatchDesc = patchDesc;
3111
3112 status_t status = connectAudioSource(sourceDesc);
3113 if (status == NO_ERROR) {
3114 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3115 *handle = sourceDesc->getHandle();
3116 }
3117 return status;
3118}
3119
3120status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3121{
3122 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3123
3124 // make sure we only have one patch per source.
3125 disconnectAudioSource(sourceDesc);
3126
3127 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003128 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003129 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3130
3131 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3132 sp<DeviceDescriptor> sinkDeviceDesc =
3133 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3134
3135 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3136 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3137
3138 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3139 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003140 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003141 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3142 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3143 // create patch between src device and output device
3144 // create Hwoutput and add to mHwOutputs
3145 } else {
3146 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3147 audio_io_handle_t output =
3148 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3149 if (output == AUDIO_IO_HANDLE_NONE) {
3150 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3151 return INVALID_OPERATION;
3152 }
3153 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3154 if (outputDesc->isDuplicated()) {
3155 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3156 return INVALID_OPERATION;
3157 }
3158 // create a special patch with no sink and two sources:
3159 // - the second source indicates to PatchPanel through which output mix this patch should
3160 // be connected as well as the stream type for volume control
3161 // - the sink is defined by whatever output device is currently selected for the output
3162 // though which this patch is routed.
3163 patch->num_sinks = 0;
3164 patch->num_sources = 2;
3165 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3166 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3167 patch->sources[1].ext.mix.usecase.stream = stream;
3168 status_t status = mpClientInterface->createAudioPatch(patch,
3169 &afPatchHandle,
3170 0);
3171 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3172 status, afPatchHandle);
3173 if (status != NO_ERROR) {
3174 ALOGW("%s patch panel could not connect device patch, error %d",
3175 __FUNCTION__, status);
3176 return INVALID_OPERATION;
3177 }
3178 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003179 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003180
3181 if (status != NO_ERROR) {
3182 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3183 return status;
3184 }
3185 sourceDesc->mSwOutput = outputDesc;
3186 if (delayMs != 0) {
3187 usleep(delayMs * 1000);
3188 }
3189 }
3190
3191 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3192 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3193
3194 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003195}
3196
Glenn Kasten559d4392016-03-29 13:42:57 -07003197status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003198{
Eric Laurentd60560a2015-04-10 11:31:20 -07003199 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3200 ALOGV("%s handle %d", __FUNCTION__, handle);
3201 if (sourceDesc == 0) {
3202 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3203 return BAD_VALUE;
3204 }
3205 status_t status = disconnectAudioSource(sourceDesc);
3206
3207 mAudioSources.removeItem(handle);
3208 return status;
3209}
3210
Andy Hung2ddee192015-12-18 17:34:44 -08003211status_t AudioPolicyManager::setMasterMono(bool mono)
3212{
3213 if (mMasterMono == mono) {
3214 return NO_ERROR;
3215 }
3216 mMasterMono = mono;
3217 // if enabling mono we close all offloaded devices, which will invalidate the
3218 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3219 // for recreating the new AudioTrack as non-offloaded PCM.
3220 //
3221 // If disabling mono, we leave all tracks as is: we don't know which clients
3222 // and tracks are able to be recreated as offloaded. The next "song" should
3223 // play back offloaded.
3224 if (mMasterMono) {
3225 Vector<audio_io_handle_t> offloaded;
3226 for (size_t i = 0; i < mOutputs.size(); ++i) {
3227 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3228 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3229 offloaded.push(desc->mIoHandle);
3230 }
3231 }
3232 for (size_t i = 0; i < offloaded.size(); ++i) {
3233 closeOutput(offloaded[i]);
3234 }
3235 }
3236 // update master mono for all remaining outputs
3237 for (size_t i = 0; i < mOutputs.size(); ++i) {
3238 updateMono(mOutputs.keyAt(i));
3239 }
3240 return NO_ERROR;
3241}
3242
3243status_t AudioPolicyManager::getMasterMono(bool *mono)
3244{
3245 *mono = mMasterMono;
3246 return NO_ERROR;
3247}
3248
Eric Laurentd60560a2015-04-10 11:31:20 -07003249status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3250{
3251 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3252
3253 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3254 if (patchDesc == 0) {
3255 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3256 sourceDesc->mPatchDesc->mHandle);
3257 return BAD_VALUE;
3258 }
3259 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3260
Eric Laurent28d09f02016-03-08 10:43:05 -08003261 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003262 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3263 if (swOutputDesc != 0) {
3264 stopSource(swOutputDesc, stream, false);
3265 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3266 } else {
3267 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3268 if (hwOutputDesc != 0) {
3269 // release patch between src device and output device
3270 // close Hwoutput and remove from mHwOutputs
3271 } else {
3272 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3273 }
3274 }
3275 return NO_ERROR;
3276}
3277
3278sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3279 audio_io_handle_t output, routing_strategy strategy)
3280{
3281 sp<AudioSourceDescriptor> source;
3282 for (size_t i = 0; i < mAudioSources.size(); i++) {
3283 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3284 routing_strategy sourceStrategy =
3285 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3286 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3287 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3288 source = sourceDesc;
3289 break;
3290 }
3291 }
3292 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003293}
3294
Eric Laurente552edb2014-03-10 17:42:56 -07003295// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003296// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003297// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003298uint32_t AudioPolicyManager::nextAudioPortGeneration()
3299{
3300 return android_atomic_inc(&mAudioPortGeneration);
3301}
3302
Eric Laurente0720872014-03-11 09:30:41 -07003303AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003304 :
3305#ifdef AUDIO_POLICY_TEST
3306 Thread(false),
3307#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003308 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003309 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003310 mAudioPortGeneration(1),
3311 mBeaconMuteRefCount(0),
3312 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003313 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003314 mTtsOutputAvailable(false),
3315 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003316{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003317 mUidCached = getuid();
3318 mpClientInterface = clientInterface;
3319
3320 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3321 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3322 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3323 bool speakerDrcEnabled = false;
3324
3325#ifdef USE_XML_AUDIO_POLICY_CONF
3326 mVolumeCurves = new VolumeCurvesCollection();
3327 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3328 mDefaultOutputDevice, speakerDrcEnabled,
3329 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3330 PolicySerializer serializer;
3331 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3332#else
3333 mVolumeCurves = new StreamDescriptorCollection();
3334 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3335 mDefaultOutputDevice, speakerDrcEnabled);
3336 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3337 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3338#endif
3339 ALOGE("could not load audio policy configuration file, setting defaults");
3340 config.setDefault();
3341 }
3342 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3343 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3344
3345 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003346 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3347 if (!engineInstance) {
3348 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3349 return;
3350 }
3351 // Retrieve the Policy Manager Interface
3352 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3353 if (mEngine == NULL) {
3354 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3355 return;
3356 }
3357 mEngine->setObserver(this);
3358 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003359 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003360 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3361
Eric Laurent3a4311c2014-03-17 12:00:47 -07003362 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003363 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003364 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3365 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003366 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003367 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003368 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003369 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003370 continue;
3371 }
3372 // open all output streams needed to access attached devices
3373 // except for direct output streams that are only opened when they are actually
3374 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003375 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003376 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3377 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003378 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003379
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003380 if (!outProfile->hasSupportedDevices()) {
3381 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003382 continue;
3383 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003384 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003385 mTtsOutputAvailable = true;
3386 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003387
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003388 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003389 continue;
3390 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003391 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003392 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3393 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003394 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003395 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003396 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003397 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003398 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003399 if ((profileType & outputDeviceTypes) == 0) {
3400 continue;
3401 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003402 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3403 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003404 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3405 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3406 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3407 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003408
3409 outputDesc->mDevice = profileType;
3410 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3411 config.sample_rate = outputDesc->mSamplingRate;
3412 config.channel_mask = outputDesc->mChannelMask;
3413 config.format = outputDesc->mFormat;
3414 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003415 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003416 &output,
3417 &config,
3418 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003419 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003420 &outputDesc->mLatency,
3421 outputDesc->mFlags);
3422
3423 if (status != NO_ERROR) {
3424 ALOGW("Cannot open output stream for device %08x on hw module %s",
3425 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003426 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003427 } else {
3428 outputDesc->mSamplingRate = config.sample_rate;
3429 outputDesc->mChannelMask = config.channel_mask;
3430 outputDesc->mFormat = config.format;
3431
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003432 for (size_t k = 0; k < supportedDevices.size(); k++) {
3433 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003434 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003435 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3436 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003437 }
3438 }
3439 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003440 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003441 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003442 }
3443 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003444 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003445 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003446 true,
3447 0,
3448 NULL,
3449 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003450 }
Eric Laurente552edb2014-03-10 17:42:56 -07003451 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003452 // open input streams needed to access attached devices to validate
3453 // mAvailableInputDevices list
3454 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3455 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003456 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003457
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003458 if (!inProfile->hasSupportedDevices()) {
3459 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003460 continue;
3461 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003462 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003463 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003464 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3465
Eric Laurentd78f1532014-09-16 16:38:20 -07003466 if ((profileType & inputDeviceTypes) == 0) {
3467 continue;
3468 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003469 sp<AudioInputDescriptor> inputDesc =
3470 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003471
Eric Laurentd78f1532014-09-16 16:38:20 -07003472 inputDesc->mDevice = profileType;
3473
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003474 // find the address
3475 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3476 // the inputs vector must be of size 1, but we don't want to crash here
3477 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3478 : String8("");
3479 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3480 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3481
Eric Laurentd78f1532014-09-16 16:38:20 -07003482 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3483 config.sample_rate = inputDesc->mSamplingRate;
3484 config.channel_mask = inputDesc->mChannelMask;
3485 config.format = inputDesc->mFormat;
3486 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003487 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003488 &input,
3489 &config,
3490 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003491 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003492 AUDIO_SOURCE_MIC,
3493 AUDIO_INPUT_FLAG_NONE);
3494
3495 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003496 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3497 for (size_t k = 0; k < supportedDevices.size(); k++) {
3498 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003499 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003500 if (index >= 0) {
3501 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3502 if (!devDesc->isAttached()) {
3503 devDesc->attach(mHwModules[i]);
3504 devDesc->importAudioPort(inProfile);
3505 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003506 }
3507 }
3508 mpClientInterface->closeInput(input);
3509 } else {
3510 ALOGW("Cannot open input stream for device %08x on hw module %s",
3511 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003512 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003513 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003514 }
3515 }
3516 // make sure all attached devices have been allocated a unique ID
3517 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003518 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003519 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003520 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3521 continue;
3522 }
François Gaffie2110e042015-03-24 08:41:51 +01003523 // The device is now validated and can be appended to the available devices of the engine
3524 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3525 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003526 i++;
3527 }
3528 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003529 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003530 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003531 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3532 continue;
3533 }
François Gaffie2110e042015-03-24 08:41:51 +01003534 // The device is now validated and can be appended to the available devices of the engine
3535 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3536 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003537 i++;
3538 }
3539 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003540 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003541 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003542 }
Eric Laurente552edb2014-03-10 17:42:56 -07003543
3544 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3545
3546 updateDevicesAndOutputs();
3547
3548#ifdef AUDIO_POLICY_TEST
3549 if (mPrimaryOutput != 0) {
3550 AudioParameter outputCmd = AudioParameter();
3551 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003552 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003553
3554 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3555 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003556 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3557 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003558 mTestLatencyMs = 0;
3559 mCurOutput = 0;
3560 mDirectOutput = false;
3561 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3562 mTestOutputs[i] = 0;
3563 }
3564
3565 const size_t SIZE = 256;
3566 char buffer[SIZE];
3567 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3568 run(buffer, ANDROID_PRIORITY_AUDIO);
3569 }
3570#endif //AUDIO_POLICY_TEST
3571}
3572
Eric Laurente0720872014-03-11 09:30:41 -07003573AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003574{
3575#ifdef AUDIO_POLICY_TEST
3576 exit();
3577#endif //AUDIO_POLICY_TEST
3578 for (size_t i = 0; i < mOutputs.size(); i++) {
3579 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003580 }
3581 for (size_t i = 0; i < mInputs.size(); i++) {
3582 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003583 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003584 mAvailableOutputDevices.clear();
3585 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003586 mOutputs.clear();
3587 mInputs.clear();
3588 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003589}
3590
Eric Laurente0720872014-03-11 09:30:41 -07003591status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003592{
Eric Laurent87ffa392015-05-22 10:32:38 -07003593 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003594}
3595
3596#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003597bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003598{
3599 ALOGV("entering threadLoop()");
3600 while (!exitPending())
3601 {
3602 String8 command;
3603 int valueInt;
3604 String8 value;
3605
3606 Mutex::Autolock _l(mLock);
3607 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3608
3609 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3610 AudioParameter param = AudioParameter(command);
3611
3612 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3613 valueInt != 0) {
3614 ALOGV("Test command %s received", command.string());
3615 String8 target;
3616 if (param.get(String8("target"), target) != NO_ERROR) {
3617 target = "Manager";
3618 }
3619 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3620 param.remove(String8("test_cmd_policy_output"));
3621 mCurOutput = valueInt;
3622 }
3623 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3624 param.remove(String8("test_cmd_policy_direct"));
3625 if (value == "false") {
3626 mDirectOutput = false;
3627 } else if (value == "true") {
3628 mDirectOutput = true;
3629 }
3630 }
3631 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3632 param.remove(String8("test_cmd_policy_input"));
3633 mTestInput = valueInt;
3634 }
3635
3636 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3637 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003638 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003639 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003640 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003641 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003642 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003643 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003644 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003645 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003646 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003647 if (target == "Manager") {
3648 mTestFormat = format;
3649 } else if (mTestOutputs[mCurOutput] != 0) {
3650 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003651 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003652 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3653 }
3654 }
3655 }
3656 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3657 param.remove(String8("test_cmd_policy_channels"));
3658 int channels = 0;
3659
3660 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003661 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003662 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003663 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003664 }
3665 if (channels != 0) {
3666 if (target == "Manager") {
3667 mTestChannels = channels;
3668 } else if (mTestOutputs[mCurOutput] != 0) {
3669 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003670 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003671 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3672 }
3673 }
3674 }
3675 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3676 param.remove(String8("test_cmd_policy_sampleRate"));
3677 if (valueInt >= 0 && valueInt <= 96000) {
3678 int samplingRate = valueInt;
3679 if (target == "Manager") {
3680 mTestSamplingRate = samplingRate;
3681 } else if (mTestOutputs[mCurOutput] != 0) {
3682 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003683 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003684 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3685 }
3686 }
3687 }
3688
3689 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3690 param.remove(String8("test_cmd_policy_reopen"));
3691
Eric Laurentc75307b2015-03-17 15:29:32 -07003692 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003693
Eric Laurentc75307b2015-03-17 15:29:32 -07003694 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003695
Eric Laurentc75307b2015-03-17 15:29:32 -07003696 removeOutput(mPrimaryOutput->mIoHandle);
3697 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3698 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003699 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003700 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3701 config.sample_rate = outputDesc->mSamplingRate;
3702 config.channel_mask = outputDesc->mChannelMask;
3703 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003704 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003705 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003706 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003707 &config,
3708 &outputDesc->mDevice,
3709 String8(""),
3710 &outputDesc->mLatency,
3711 outputDesc->mFlags);
3712 if (status != NO_ERROR) {
3713 ALOGE("Failed to reopen hardware output stream, "
3714 "samplingRate: %d, format %d, channels %d",
3715 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003716 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003717 outputDesc->mSamplingRate = config.sample_rate;
3718 outputDesc->mChannelMask = config.channel_mask;
3719 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003720 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003721 AudioParameter outputCmd = AudioParameter();
3722 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003723 mpClientInterface->setParameters(handle, outputCmd.toString());
3724 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003725 }
3726 }
3727
3728
3729 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3730 }
3731 }
3732 return false;
3733}
3734
Eric Laurente0720872014-03-11 09:30:41 -07003735void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003736{
3737 {
3738 AutoMutex _l(mLock);
3739 requestExit();
3740 mWaitWorkCV.signal();
3741 }
3742 requestExitAndWait();
3743}
3744
Eric Laurente0720872014-03-11 09:30:41 -07003745int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003746{
3747 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3748 if (output == mTestOutputs[i]) return i;
3749 }
3750 return 0;
3751}
3752#endif //AUDIO_POLICY_TEST
3753
3754// ---
3755
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003756void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003757{
François Gaffie98cc1912015-03-18 17:52:40 +01003758 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003759 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003760 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003761 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003762}
3763
François Gaffie53615e22015-03-19 09:24:12 +01003764void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3765{
3766 mOutputs.removeItem(output);
3767}
3768
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003769void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003770{
François Gaffie98cc1912015-03-18 17:52:40 +01003771 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003772 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003773 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003774}
Eric Laurente552edb2014-03-10 17:42:56 -07003775
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003776void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003777 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003778 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003779 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003780 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003781 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003782 if (devDesc != 0) {
3783 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3784 desc->mIoHandle, address.string());
3785 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003786 }
3787}
3788
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003789status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003790 audio_policy_dev_state_t state,
3791 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003792 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003793{
François Gaffie53615e22015-03-19 09:24:12 +01003794 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003795 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003796
3797 if (audio_device_is_digital(device)) {
3798 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003799 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003800 }
Eric Laurente552edb2014-03-10 17:42:56 -07003801
Eric Laurent3b73df72014-03-11 09:06:29 -07003802 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003803 // first list already open outputs that can be routed to this device
3804 for (size_t i = 0; i < mOutputs.size(); i++) {
3805 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003806 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003807 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003808 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3809 outputs.add(mOutputs.keyAt(i));
3810 } else {
3811 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003812 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003813 }
Eric Laurente552edb2014-03-10 17:42:56 -07003814 }
3815 }
3816 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003817 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003818 for (size_t i = 0; i < mHwModules.size(); i++)
3819 {
3820 if (mHwModules[i]->mHandle == 0) {
3821 continue;
3822 }
3823 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3824 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003825 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003826 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003827 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003828 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003829 profiles.add(profile);
3830 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3831 }
Eric Laurente552edb2014-03-10 17:42:56 -07003832 }
3833 }
3834 }
3835
Eric Laurent7b279bb2015-12-14 10:18:23 -08003836 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003837
Eric Laurente552edb2014-03-10 17:42:56 -07003838 if (profiles.isEmpty() && outputs.isEmpty()) {
3839 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3840 return BAD_VALUE;
3841 }
3842
3843 // open outputs for matching profiles if needed. Direct outputs are also opened to
3844 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3845 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003846 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003847
3848 // nothing to do if one output is already opened for this profile
3849 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003850 for (j = 0; j < outputs.size(); j++) {
3851 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003852 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003853 // matching profile: save the sample rates, format and channel masks supported
3854 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003855 if (audio_device_is_digital(device)) {
3856 devDesc->importAudioPort(profile);
3857 }
Eric Laurente552edb2014-03-10 17:42:56 -07003858 break;
3859 }
3860 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003861 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003862 continue;
3863 }
3864
Eric Laurent83b88082014-06-20 18:31:16 -07003865 ALOGV("opening output for device %08x with params %s profile %p",
3866 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003867 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003868 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003869 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3870 config.sample_rate = desc->mSamplingRate;
3871 config.channel_mask = desc->mChannelMask;
3872 config.format = desc->mFormat;
3873 config.offload_info.sample_rate = desc->mSamplingRate;
3874 config.offload_info.channel_mask = desc->mChannelMask;
3875 config.offload_info.format = desc->mFormat;
3876 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003877 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003878 &output,
3879 &config,
3880 &desc->mDevice,
3881 address,
3882 &desc->mLatency,
3883 desc->mFlags);
3884 if (status == NO_ERROR) {
3885 desc->mSamplingRate = config.sample_rate;
3886 desc->mChannelMask = config.channel_mask;
3887 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003888
Eric Laurentd4692962014-05-05 18:13:44 -07003889 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003890 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003891 char *param = audio_device_address_to_parameter(device, address);
3892 mpClientInterface->setParameters(output, String8(param));
3893 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003894 }
Phil Burk00eeb322016-03-31 12:41:00 -07003895 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003896 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003897 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003898 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003899 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003900 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003901 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003902 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003903 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003904 config.offload_info.sample_rate = config.sample_rate;
3905 config.offload_info.channel_mask = config.channel_mask;
3906 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003907 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003908 &output,
3909 &config,
3910 &desc->mDevice,
3911 address,
3912 &desc->mLatency,
3913 desc->mFlags);
3914 if (status == NO_ERROR) {
3915 desc->mSamplingRate = config.sample_rate;
3916 desc->mChannelMask = config.channel_mask;
3917 desc->mFormat = config.format;
3918 } else {
3919 output = AUDIO_IO_HANDLE_NONE;
3920 }
Eric Laurentd4692962014-05-05 18:13:44 -07003921 }
3922
Eric Laurentcf2c0212014-07-25 16:20:43 -07003923 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003924 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003925 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003926 sp<AudioPolicyMix> policyMix;
3927 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003928 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3929 address.string());
3930 }
François Gaffie036e1e92015-03-19 10:16:24 +01003931 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003932 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003933
Eric Laurent87ffa392015-05-22 10:32:38 -07003934 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3935 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003936 // no duplicated output for direct outputs and
3937 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003938 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003939
Eric Laurentd4692962014-05-05 18:13:44 -07003940 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003941 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003942
Eric Laurentd4692962014-05-05 18:13:44 -07003943 //TODO: configure audio effect output stage here
3944
3945 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003946 duplicatedOutput =
3947 mpClientInterface->openDuplicateOutput(output,
3948 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003949 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003950 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003951 sp<SwAudioOutputDescriptor> dupOutputDesc =
3952 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3953 dupOutputDesc->mOutput1 = mPrimaryOutput;
3954 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003955 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3956 dupOutputDesc->mFormat = desc->mFormat;
3957 dupOutputDesc->mChannelMask = desc->mChannelMask;
3958 dupOutputDesc->mLatency = desc->mLatency;
3959 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003960 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003961 } else {
3962 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003963 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003964 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003965 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003966 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003967 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003968 }
Eric Laurente552edb2014-03-10 17:42:56 -07003969 }
3970 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003971 } else {
3972 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003973 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003974 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003975 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003976 profiles.removeAt(profile_index);
3977 profile_index--;
3978 } else {
3979 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003980 // Load digital format info only for digital devices
3981 if (audio_device_is_digital(device)) {
3982 devDesc->importAudioPort(profile);
3983 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003984
François Gaffie53615e22015-03-19 09:24:12 +01003985 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003986 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3987 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003988 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003989 NULL/*patch handle*/, address.string());
3990 }
Eric Laurente552edb2014-03-10 17:42:56 -07003991 ALOGV("checkOutputsForDevice(): adding output %d", output);
3992 }
3993 }
3994
3995 if (profiles.isEmpty()) {
3996 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3997 return BAD_VALUE;
3998 }
Eric Laurentd4692962014-05-05 18:13:44 -07003999 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004000 // check if one opened output is not needed any more after disconnecting one device
4001 for (size_t i = 0; i < mOutputs.size(); i++) {
4002 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004003 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004004 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004005 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004006 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004007 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004008 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004009 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4010 mOutputs.keyAt(i));
4011 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004012 }
Eric Laurente552edb2014-03-10 17:42:56 -07004013 }
4014 }
Eric Laurentd4692962014-05-05 18:13:44 -07004015 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004016 for (size_t i = 0; i < mHwModules.size(); i++)
4017 {
4018 if (mHwModules[i]->mHandle == 0) {
4019 continue;
4020 }
4021 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4022 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004023 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004024 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004025 ALOGV("checkOutputsForDevice(): "
4026 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004027 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004028 }
4029 }
4030 }
4031 }
4032 return NO_ERROR;
4033}
4034
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004035status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004036 audio_policy_dev_state_t state,
4037 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004038 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004039{
Paul McLean9080a4c2015-06-18 08:24:02 -07004040 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004041 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004042
4043 if (audio_device_is_digital(device)) {
4044 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004045 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004046 }
4047
Eric Laurentd4692962014-05-05 18:13:44 -07004048 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4049 // first list already open inputs that can be routed to this device
4050 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4051 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004052 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004053 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4054 inputs.add(mInputs.keyAt(input_index));
4055 }
4056 }
4057
4058 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004059 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004060 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4061 {
4062 if (mHwModules[module_idx]->mHandle == 0) {
4063 continue;
4064 }
4065 for (size_t profile_index = 0;
4066 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4067 profile_index++)
4068 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004069 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4070
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004071 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004072 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004073 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004074 profiles.add(profile);
4075 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4076 profile_index, module_idx);
4077 }
Eric Laurentd4692962014-05-05 18:13:44 -07004078 }
4079 }
4080 }
4081
4082 if (profiles.isEmpty() && inputs.isEmpty()) {
4083 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4084 return BAD_VALUE;
4085 }
4086
4087 // open inputs for matching profiles if needed. Direct inputs are also opened to
4088 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4089 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4090
Eric Laurent1c333e22014-05-20 10:48:17 -07004091 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004092 // nothing to do if one input is already opened for this profile
4093 size_t input_index;
4094 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4095 desc = mInputs.valueAt(input_index);
4096 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004097 if (audio_device_is_digital(device)) {
4098 devDesc->importAudioPort(profile);
4099 }
Eric Laurentd4692962014-05-05 18:13:44 -07004100 break;
4101 }
4102 }
4103 if (input_index != mInputs.size()) {
4104 continue;
4105 }
4106
4107 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4108 desc = new AudioInputDescriptor(profile);
4109 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004110 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4111 config.sample_rate = desc->mSamplingRate;
4112 config.channel_mask = desc->mChannelMask;
4113 config.format = desc->mFormat;
4114 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004115 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004116 &input,
4117 &config,
4118 &desc->mDevice,
4119 address,
4120 AUDIO_SOURCE_MIC,
4121 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004122
Eric Laurentcf2c0212014-07-25 16:20:43 -07004123 if (status == NO_ERROR) {
4124 desc->mSamplingRate = config.sample_rate;
4125 desc->mChannelMask = config.channel_mask;
4126 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004127
Eric Laurentd4692962014-05-05 18:13:44 -07004128 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004129 char *param = audio_device_address_to_parameter(device, address);
4130 mpClientInterface->setParameters(input, String8(param));
4131 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004132 }
Phil Burk00eeb322016-03-31 12:41:00 -07004133 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004134 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004135 ALOGW("checkInputsForDevice() direct input missing param");
4136 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004137 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004138 }
4139
4140 if (input != 0) {
4141 addInput(input, desc);
4142 }
4143 } // endif input != 0
4144
Eric Laurentcf2c0212014-07-25 16:20:43 -07004145 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004146 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004147 profiles.removeAt(profile_index);
4148 profile_index--;
4149 } else {
4150 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004151 if (audio_device_is_digital(device)) {
4152 devDesc->importAudioPort(profile);
4153 }
Eric Laurentd4692962014-05-05 18:13:44 -07004154 ALOGV("checkInputsForDevice(): adding input %d", input);
4155 }
4156 } // end scan profiles
4157
4158 if (profiles.isEmpty()) {
4159 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4160 return BAD_VALUE;
4161 }
4162 } else {
4163 // Disconnect
4164 // check if one opened input is not needed any more after disconnecting one device
4165 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4166 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004167 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004168 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4169 mInputs.keyAt(input_index));
4170 inputs.add(mInputs.keyAt(input_index));
4171 }
4172 }
4173 // Clear any profiles associated with the disconnected device.
4174 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4175 if (mHwModules[module_index]->mHandle == 0) {
4176 continue;
4177 }
4178 for (size_t profile_index = 0;
4179 profile_index < mHwModules[module_index]->mInputProfiles.size();
4180 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004181 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004182 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004183 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004184 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004185 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004186 }
4187 }
4188 }
4189 } // end disconnect
4190
4191 return NO_ERROR;
4192}
4193
4194
Eric Laurente0720872014-03-11 09:30:41 -07004195void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004196{
4197 ALOGV("closeOutput(%d)", output);
4198
Eric Laurentc75307b2015-03-17 15:29:32 -07004199 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004200 if (outputDesc == NULL) {
4201 ALOGW("closeOutput() unknown output %d", output);
4202 return;
4203 }
François Gaffie036e1e92015-03-19 10:16:24 +01004204 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004205
Eric Laurente552edb2014-03-10 17:42:56 -07004206 // look for duplicated outputs connected to the output being removed.
4207 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004208 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004209 if (dupOutputDesc->isDuplicated() &&
4210 (dupOutputDesc->mOutput1 == outputDesc ||
4211 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004212 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004213 if (dupOutputDesc->mOutput1 == outputDesc) {
4214 outputDesc2 = dupOutputDesc->mOutput2;
4215 } else {
4216 outputDesc2 = dupOutputDesc->mOutput1;
4217 }
4218 // As all active tracks on duplicated output will be deleted,
4219 // and as they were also referenced on the other output, the reference
4220 // count for their stream type must be adjusted accordingly on
4221 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004222 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004223 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004224 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004225 }
4226 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4227 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4228
4229 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004230 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004231 }
4232 }
4233
Eric Laurent05b90f82014-08-27 15:32:29 -07004234 nextAudioPortGeneration();
4235
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004236 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004237 if (index >= 0) {
4238 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004239 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004240 mAudioPatches.removeItemsAt(index);
4241 mpClientInterface->onAudioPatchListUpdate();
4242 }
4243
Eric Laurente552edb2014-03-10 17:42:56 -07004244 AudioParameter param;
4245 param.add(String8("closing"), String8("true"));
4246 mpClientInterface->setParameters(output, param.toString());
4247
4248 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004249 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004250 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004251}
4252
4253void AudioPolicyManager::closeInput(audio_io_handle_t input)
4254{
4255 ALOGV("closeInput(%d)", input);
4256
4257 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4258 if (inputDesc == NULL) {
4259 ALOGW("closeInput() unknown input %d", input);
4260 return;
4261 }
4262
Eric Laurent6a94d692014-05-20 11:18:06 -07004263 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004264
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004265 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004266 if (index >= 0) {
4267 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004268 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004269 mAudioPatches.removeItemsAt(index);
4270 mpClientInterface->onAudioPatchListUpdate();
4271 }
4272
4273 mpClientInterface->closeInput(input);
4274 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004275}
4276
Eric Laurentc75307b2015-03-17 15:29:32 -07004277SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4278 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004279 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004280{
4281 SortedVector<audio_io_handle_t> outputs;
4282
4283 ALOGVV("getOutputsForDevice() device %04x", device);
4284 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004285 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004286 i, openOutputs.valueAt(i)->isDuplicated(),
4287 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004288 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4289 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4290 outputs.add(openOutputs.keyAt(i));
4291 }
4292 }
4293 return outputs;
4294}
4295
Eric Laurente0720872014-03-11 09:30:41 -07004296bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004297 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004298{
4299 if (outputs1.size() != outputs2.size()) {
4300 return false;
4301 }
4302 for (size_t i = 0; i < outputs1.size(); i++) {
4303 if (outputs1[i] != outputs2[i]) {
4304 return false;
4305 }
4306 }
4307 return true;
4308}
4309
Eric Laurente0720872014-03-11 09:30:41 -07004310void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004311{
4312 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4313 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4314 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4315 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4316
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004317 // also take into account external policy-related changes: add all outputs which are
4318 // associated with policies in the "before" and "after" output vectors
4319 ALOGVV("checkOutputForStrategy(): policy related outputs");
4320 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004321 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004322 if (desc != 0 && desc->mPolicyMix != NULL) {
4323 srcOutputs.add(desc->mIoHandle);
4324 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4325 }
4326 }
4327 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004328 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004329 if (desc != 0 && desc->mPolicyMix != NULL) {
4330 dstOutputs.add(desc->mIoHandle);
4331 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4332 }
4333 }
4334
Eric Laurente552edb2014-03-10 17:42:56 -07004335 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4336 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4337 strategy, srcOutputs[0], dstOutputs[0]);
4338 // mute strategy while moving tracks from one output to another
4339 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004341 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004342 setStrategyMute(strategy, true, desc);
4343 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004345 sp<AudioSourceDescriptor> source =
4346 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4347 if (source != 0){
4348 connectAudioSource(source);
4349 }
Eric Laurente552edb2014-03-10 17:42:56 -07004350 }
4351
4352 // Move effects associated to this strategy from previous output to new output
4353 if (strategy == STRATEGY_MEDIA) {
4354 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4355 SortedVector<audio_io_handle_t> moved;
4356 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004357 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4358 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4359 effectDesc->mIo != fxOutput) {
4360 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004361 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4362 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004363 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004364 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004365 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004366 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004367 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004368 }
4369 }
4370 }
4371 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004372 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004373 if (getStrategy((audio_stream_type_t)i) == strategy) {
4374 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004375 }
4376 }
4377 }
4378}
4379
Eric Laurente0720872014-03-11 09:30:41 -07004380void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004381{
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_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004385 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004386 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004387 checkOutputForStrategy(STRATEGY_SONIFICATION);
4388 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004389 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004390 checkOutputForStrategy(STRATEGY_MEDIA);
4391 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004392 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004393}
4394
Eric Laurente0720872014-03-11 09:30:41 -07004395void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004396{
François Gaffie53615e22015-03-19 09:24:12 +01004397 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004398 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004399 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004400 return;
4401 }
4402
Eric Laurent3a4311c2014-03-17 12:00:47 -07004403 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004404 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4405 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4406 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004407
4408 // if suspended, restore A2DP output if:
4409 // ((SCO device is NOT connected) ||
4410 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4411 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004412 //
Eric Laurentf732e072016-08-03 19:30:28 -07004413 // if not suspended, suspend A2DP output if:
4414 // (SCO device is connected) &&
4415 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4416 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004417 //
4418 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004419 if (!isScoConnected ||
4420 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4421 AUDIO_POLICY_FORCE_BT_SCO) &&
4422 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4423 AUDIO_POLICY_FORCE_BT_SCO) &&
4424 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004425 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004426
4427 mpClientInterface->restoreOutput(a2dpOutput);
4428 mA2dpSuspended = false;
4429 }
4430 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004431 if (isScoConnected &&
4432 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4433 AUDIO_POLICY_FORCE_BT_SCO) ||
4434 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4435 AUDIO_POLICY_FORCE_BT_SCO) ||
4436 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004437 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004438
4439 mpClientInterface->suspendOutput(a2dpOutput);
4440 mA2dpSuspended = true;
4441 }
4442 }
4443}
4444
Eric Laurentc75307b2015-03-17 15:29:32 -07004445audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4446 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004447{
4448 audio_devices_t device = AUDIO_DEVICE_NONE;
4449
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004450 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 if (index >= 0) {
4452 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4453 if (patchDesc->mUid != mUidCached) {
4454 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004455 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004456 return outputDesc->device();
4457 }
4458 }
4459
Eric Laurente552edb2014-03-10 17:42:56 -07004460 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004461 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004462 // use device for strategy enforced audible
4463 // 2: we are in call or the strategy phone is active on the output:
4464 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004465 // 3: the strategy for enforced audible is active but not enforced on the output:
4466 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004467 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004468 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004469 // 5: the strategy accessibility is active on the output:
4470 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004471 // 6: the strategy "respectful" sonification is active on the output:
4472 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004473 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004474 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004475 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004476 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004477 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004478 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004479 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004480 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004481 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4482 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004483 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004484 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004485 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004486 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004487 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004488 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004489 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4490 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004491 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004492 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004493 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004494 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004495 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004496 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004497 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004498 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004499 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004500 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004501 }
4502
Eric Laurent1c333e22014-05-20 10:48:17 -07004503 ALOGV("getNewOutputDevice() selected device %x", device);
4504 return device;
4505}
4506
Eric Laurentfb66dd92016-01-28 18:32:03 -08004507audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004508{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004509 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004510
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004511 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004512 if (index >= 0) {
4513 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4514 if (patchDesc->mUid != mUidCached) {
4515 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004516 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 return inputDesc->mDevice;
4518 }
4519 }
4520
Eric Laurentfb66dd92016-01-28 18:32:03 -08004521 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4522 if (isInCall()) {
4523 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4524 } else if (source != AUDIO_SOURCE_DEFAULT) {
4525 device = getDeviceAndMixForInputSource(source);
4526 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004527
Eric Laurente552edb2014-03-10 17:42:56 -07004528 return device;
4529}
4530
Eric Laurent794fde22016-03-11 09:50:45 -08004531bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4532 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004533 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004534}
4535
Eric Laurente0720872014-03-11 09:30:41 -07004536uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004537 return (uint32_t)getStrategy(stream);
4538}
4539
Eric Laurente0720872014-03-11 09:30:41 -07004540audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004541 // By checking the range of stream before calling getStrategy, we avoid
4542 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4543 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004544 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004545 return AUDIO_DEVICE_NONE;
4546 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004547 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004548 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4549 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004550 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004551 }
Eric Laurent794fde22016-03-11 09:50:45 -08004552 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004553 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004554 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004555 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4556 for (size_t i = 0; i < outputs.size(); i++) {
4557 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004558 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004559 curDevices |= outputDesc->device();
4560 }
4561 }
4562 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004563 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004564
4565 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4566 and doesn't really need to.*/
4567 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4568 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4569 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4570 }
Eric Laurente552edb2014-03-10 17:42:56 -07004571 return devices;
4572}
4573
François Gaffie2110e042015-03-24 08:41:51 +01004574routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4575{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004576 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004577 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004578}
4579
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004580uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4581 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004582 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4583 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4584 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004585 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4586 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4587 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004588 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004589 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004590}
4591
Eric Laurente0720872014-03-11 09:30:41 -07004592void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004593 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004594 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004595 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4596 updateDevicesAndOutputs();
4597 break;
4598 default:
4599 break;
4600 }
4601}
4602
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004603uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004604
4605 // skip beacon mute management if a dedicated TTS output is available
4606 if (mTtsOutputAvailable) {
4607 return 0;
4608 }
4609
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004610 switch(event) {
4611 case STARTING_OUTPUT:
4612 mBeaconMuteRefCount++;
4613 break;
4614 case STOPPING_OUTPUT:
4615 if (mBeaconMuteRefCount > 0) {
4616 mBeaconMuteRefCount--;
4617 }
4618 break;
4619 case STARTING_BEACON:
4620 mBeaconPlayingRefCount++;
4621 break;
4622 case STOPPING_BEACON:
4623 if (mBeaconPlayingRefCount > 0) {
4624 mBeaconPlayingRefCount--;
4625 }
4626 break;
4627 }
4628
4629 if (mBeaconMuteRefCount > 0) {
4630 // any playback causes beacon to be muted
4631 return setBeaconMute(true);
4632 } else {
4633 // no other playback: unmute when beacon starts playing, mute when it stops
4634 return setBeaconMute(mBeaconPlayingRefCount == 0);
4635 }
4636}
4637
4638uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4639 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4640 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4641 // keep track of muted state to avoid repeating mute/unmute operations
4642 if (mBeaconMuted != mute) {
4643 // mute/unmute AUDIO_STREAM_TTS on all outputs
4644 ALOGV("\t muting %d", mute);
4645 uint32_t maxLatency = 0;
4646 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004647 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004648 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004649 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004650 0 /*delay*/, AUDIO_DEVICE_NONE);
4651 const uint32_t latency = desc->latency() * 2;
4652 if (latency > maxLatency) {
4653 maxLatency = latency;
4654 }
4655 }
4656 mBeaconMuted = mute;
4657 return maxLatency;
4658 }
4659 return 0;
4660}
4661
Eric Laurente0720872014-03-11 09:30:41 -07004662audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004663 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004664{
Paul McLeanaa981192015-03-21 09:55:15 -07004665 // Routing
4666 // see if we have an explicit route
4667 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4668 // (getStrategy(stream)).
4669 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4670 // and activity count is non-zero
4671 // the device = the device from the descriptor in the RouteMap, and exit.
4672 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4673 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004674 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4675 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004676 return route->mDeviceDescriptor->type();
4677 }
4678 }
4679
Eric Laurente552edb2014-03-10 17:42:56 -07004680 if (fromCache) {
4681 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4682 strategy, mDeviceForStrategy[strategy]);
4683 return mDeviceForStrategy[strategy];
4684 }
François Gaffie2110e042015-03-24 08:41:51 +01004685 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004686}
4687
Eric Laurente0720872014-03-11 09:30:41 -07004688void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004689{
4690 for (int i = 0; i < NUM_STRATEGIES; i++) {
4691 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4692 }
4693 mPreviousOutputs = mOutputs;
4694}
4695
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004696uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004697 audio_devices_t prevDevice,
4698 uint32_t delayMs)
4699{
4700 // mute/unmute strategies using an incompatible device combination
4701 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4702 // if unmuting, unmute only after the specified delay
4703 if (outputDesc->isDuplicated()) {
4704 return 0;
4705 }
4706
4707 uint32_t muteWaitMs = 0;
4708 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004709 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004710
4711 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4712 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004713 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004714 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4715 bool doMute = false;
4716
4717 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4718 doMute = true;
4719 outputDesc->mStrategyMutedByDevice[i] = true;
4720 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4721 doMute = true;
4722 outputDesc->mStrategyMutedByDevice[i] = false;
4723 }
Eric Laurent99401132014-05-07 19:48:15 -07004724 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004725 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004726 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004727 // skip output if it does not share any device with current output
4728 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4729 == AUDIO_DEVICE_NONE) {
4730 continue;
4731 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004732 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004733 mute ? "muting" : "unmuting", i, curDevice);
4734 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004735 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004736 if (mute) {
4737 // FIXME: should not need to double latency if volume could be applied
4738 // immediately by the audioflinger mixer. We must account for the delay
4739 // between now and the next time the audioflinger thread for this output
4740 // will process a buffer (which corresponds to one buffer size,
4741 // usually 1/2 or 1/4 of the latency).
4742 if (muteWaitMs < desc->latency() * 2) {
4743 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004744 }
4745 }
4746 }
4747 }
4748 }
4749 }
4750
Eric Laurent99401132014-05-07 19:48:15 -07004751 // temporary mute output if device selection changes to avoid volume bursts due to
4752 // different per device volumes
4753 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004754 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4755 // temporary mute duration is conservatively set to 4 times the reported latency
4756 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4757 if (muteWaitMs < tempMuteWaitMs) {
4758 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004759 }
Eric Laurentdc462862016-07-19 12:29:53 -07004760
Eric Laurent99401132014-05-07 19:48:15 -07004761 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004762 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004763 // make sure that we do not start the temporary mute period too early in case of
4764 // delayed device change
4765 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004766 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004767 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004768 }
4769 }
4770 }
4771
Eric Laurente552edb2014-03-10 17:42:56 -07004772 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4773 if (muteWaitMs > delayMs) {
4774 muteWaitMs -= delayMs;
4775 usleep(muteWaitMs * 1000);
4776 return muteWaitMs;
4777 }
4778 return 0;
4779}
4780
Eric Laurentc75307b2015-03-17 15:29:32 -07004781uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004782 audio_devices_t device,
4783 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004784 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004785 audio_patch_handle_t *patchHandle,
4786 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004787{
Eric Laurentc75307b2015-03-17 15:29:32 -07004788 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004789 AudioParameter param;
4790 uint32_t muteWaitMs;
4791
4792 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004793 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4794 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004795 return muteWaitMs;
4796 }
4797 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4798 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004799 if ((device != AUDIO_DEVICE_NONE) &&
4800 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004801 return 0;
4802 }
4803
4804 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004805 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004806
4807 audio_devices_t prevDevice = outputDesc->mDevice;
4808
Paul McLeanaa981192015-03-21 09:55:15 -07004809 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004810
4811 if (device != AUDIO_DEVICE_NONE) {
4812 outputDesc->mDevice = device;
4813 }
4814 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4815
4816 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004817 // the requested device is AUDIO_DEVICE_NONE
4818 // OR the requested device is the same as current device
4819 // AND force is not specified
4820 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004821 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004822 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4823 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004824 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004825 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004826 return muteWaitMs;
4827 }
4828
4829 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004830
Eric Laurente552edb2014-03-10 17:42:56 -07004831 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004832 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004833 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004834 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004835 DeviceVector deviceList;
4836 if ((address == NULL) || (strlen(address) == 0)) {
4837 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4838 } else {
4839 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4840 }
4841
Eric Laurent1c333e22014-05-20 10:48:17 -07004842 if (!deviceList.isEmpty()) {
4843 struct audio_patch patch;
4844 outputDesc->toAudioPortConfig(&patch.sources[0]);
4845 patch.num_sources = 1;
4846 patch.num_sinks = 0;
4847 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4848 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004849 patch.num_sinks++;
4850 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 ssize_t index;
4852 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4853 index = mAudioPatches.indexOfKey(*patchHandle);
4854 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004855 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 }
4857 sp< AudioPatch> patchDesc;
4858 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4859 if (index >= 0) {
4860 patchDesc = mAudioPatches.valueAt(index);
4861 afPatchHandle = patchDesc->mAfPatchHandle;
4862 }
4863
Eric Laurent1c333e22014-05-20 10:48:17 -07004864 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 &afPatchHandle,
4866 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004867 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4868 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004869 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004870 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004871 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004872 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 addAudioPatch(patchDesc->mHandle, patchDesc);
4874 } else {
4875 patchDesc->mPatch = patch;
4876 }
4877 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 if (patchHandle) {
4879 *patchHandle = patchDesc->mHandle;
4880 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004881 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004883 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004884 }
4885 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004886
4887 // inform all input as well
4888 for (size_t i = 0; i < mInputs.size(); i++) {
4889 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004890 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004891 AudioParameter inputCmd = AudioParameter();
4892 ALOGV("%s: inform input %d of device:%d", __func__,
4893 inputDescriptor->mIoHandle, device);
4894 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4895 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4896 inputCmd.toString(),
4897 delayMs);
4898 }
4899 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 }
Eric Laurente552edb2014-03-10 17:42:56 -07004901
4902 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004903 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004904
4905 return muteWaitMs;
4906}
4907
Eric Laurentc75307b2015-03-17 15:29:32 -07004908status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 int delayMs,
4910 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004911{
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 ssize_t index;
4913 if (patchHandle) {
4914 index = mAudioPatches.indexOfKey(*patchHandle);
4915 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004916 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 }
4918 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004919 return INVALID_OPERATION;
4920 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4922 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004923 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004924 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 removeAudioPatch(patchDesc->mHandle);
4926 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004927 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004928 return status;
4929}
4930
4931status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4932 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 bool force,
4934 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004935{
4936 status_t status = NO_ERROR;
4937
Eric Laurent1f2f2232014-06-02 12:01:23 -07004938 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004939 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4940 inputDesc->mDevice = device;
4941
4942 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4943 if (!deviceList.isEmpty()) {
4944 struct audio_patch patch;
4945 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004946 // AUDIO_SOURCE_HOTWORD is for internal use only:
4947 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004948 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004949 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004950 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4951 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004952 patch.num_sinks = 1;
4953 //only one input device for now
4954 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004955 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004956 ssize_t index;
4957 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4958 index = mAudioPatches.indexOfKey(*patchHandle);
4959 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004960 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 }
4962 sp< AudioPatch> patchDesc;
4963 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4964 if (index >= 0) {
4965 patchDesc = mAudioPatches.valueAt(index);
4966 afPatchHandle = patchDesc->mAfPatchHandle;
4967 }
4968
Eric Laurent1c333e22014-05-20 10:48:17 -07004969 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004971 0);
4972 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004974 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004976 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 addAudioPatch(patchDesc->mHandle, patchDesc);
4978 } else {
4979 patchDesc->mPatch = patch;
4980 }
4981 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 if (patchHandle) {
4983 *patchHandle = patchDesc->mHandle;
4984 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004985 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004987 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004988 }
4989 }
4990 }
4991 return status;
4992}
4993
Eric Laurent6a94d692014-05-20 11:18:06 -07004994status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4995 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004996{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004997 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 ssize_t index;
4999 if (patchHandle) {
5000 index = mAudioPatches.indexOfKey(*patchHandle);
5001 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005002 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 }
5004 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005005 return INVALID_OPERATION;
5006 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5008 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005009 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005010 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 removeAudioPatch(patchDesc->mHandle);
5012 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005013 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005014 return status;
5015}
5016
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005017sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005018 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005019 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005020 audio_format_t& format,
5021 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005022 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005023{
5024 // Choose an input profile based on the requested capture parameters: select the first available
5025 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005026 //
5027 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5028 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005029
5030 for (size_t i = 0; i < mHwModules.size(); i++)
5031 {
5032 if (mHwModules[i]->mHandle == 0) {
5033 continue;
5034 }
5035 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5036 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005037 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005038 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005039 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005040 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005041 format,
5042 &format /*updatedFormat*/,
5043 channelMask,
5044 &channelMask /*updatedChannelMask*/,
5045 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005046
Eric Laurente552edb2014-03-10 17:42:56 -07005047 return profile;
5048 }
5049 }
5050 }
5051 return NULL;
5052}
5053
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005054
5055audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005056 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005057{
François Gaffie036e1e92015-03-19 10:16:24 +01005058 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5059 audio_devices_t selectedDeviceFromMix =
5060 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005061
François Gaffie036e1e92015-03-19 10:16:24 +01005062 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5063 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005064 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005065 return getDeviceForInputSource(inputSource);
5066}
5067
5068audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5069{
Paul McLean466dc8e2015-04-17 13:15:36 -06005070 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5071 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005072 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005073 return route->mDeviceDescriptor->type();
5074 }
5075 }
5076
5077 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005078}
5079
Eric Laurente0720872014-03-11 09:30:41 -07005080float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005081 int index,
5082 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005083{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005084 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005085
5086 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5087 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5088 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5089 // the ringtone volume
5090 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5091 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5092 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5093 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5094 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5095 }
5096
Eric Laurente552edb2014-03-10 17:42:56 -07005097 // if a headset is connected, apply the following rules to ring tones and notifications
5098 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005099 // - always attenuate notifications volume by 6dB
5100 // - attenuate ring tones volume by 6dB unless music is not playing and
5101 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005102 // - if music is playing, always limit the volume to current music volume,
5103 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005104 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005105 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5106 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5107 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5108 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5109 ((stream_strategy == STRATEGY_SONIFICATION)
5110 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005111 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005112 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005113 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005114 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005115 // when the phone is ringing we must consider that music could have been paused just before
5116 // by the music application and behave as if music was active if the last music track was
5117 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005118 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005119 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005120 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005121 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005122 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005123 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5124 musicDevice),
5125 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005126 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5127 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005128 if (volumeDB > minVolDB) {
5129 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005130 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005131 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005132 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5133 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5134 // on A2DP, also ensure notification volume is not too low compared to media when
5135 // intended to be played
5136 if ((volumeDB > -96.0f) &&
5137 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5138 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5139 stream, device,
5140 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5141 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5142 }
5143 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005144 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5145 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005146 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005147 }
5148 }
5149
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005150 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005151}
5152
Eric Laurente0720872014-03-11 09:30:41 -07005153status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005154 int index,
5155 const sp<AudioOutputDescriptor>& outputDesc,
5156 audio_devices_t device,
5157 int delayMs,
5158 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005159{
Eric Laurente552edb2014-03-10 17:42:56 -07005160 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005161 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005162 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005163 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005164 return NO_ERROR;
5165 }
François Gaffie2110e042015-03-24 08:41:51 +01005166 audio_policy_forced_cfg_t forceUseForComm =
5167 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005168 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005169 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5170 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005171 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005172 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005173 return INVALID_OPERATION;
5174 }
5175
Eric Laurentc75307b2015-03-17 15:29:32 -07005176 if (device == AUDIO_DEVICE_NONE) {
5177 device = outputDesc->device();
5178 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005179
Eric Laurentffbc80f2015-03-18 18:30:19 -07005180 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005181 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005182 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005183 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005184
Eric Laurentffbc80f2015-03-18 18:30:19 -07005185 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005186
Eric Laurent3b73df72014-03-11 09:06:29 -07005187 if (stream == AUDIO_STREAM_VOICE_CALL ||
5188 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005189 float voiceVolume;
5190 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005191 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005192 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005193 } else {
5194 voiceVolume = 1.0;
5195 }
5196
Eric Laurent18fba842016-03-31 14:41:26 -07005197 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005198 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5199 mLastVoiceVolume = voiceVolume;
5200 }
5201 }
5202
5203 return NO_ERROR;
5204}
5205
Eric Laurentc75307b2015-03-17 15:29:32 -07005206void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5207 audio_devices_t device,
5208 int delayMs,
5209 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005210{
Eric Laurentc75307b2015-03-17 15:29:32 -07005211 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005212
Eric Laurent794fde22016-03-11 09:50:45 -08005213 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005214 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005215 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005216 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005217 device,
5218 delayMs,
5219 force);
5220 }
5221}
5222
Eric Laurente0720872014-03-11 09:30:41 -07005223void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005224 bool on,
5225 const sp<AudioOutputDescriptor>& outputDesc,
5226 int delayMs,
5227 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005228{
Eric Laurent72249d52015-06-08 11:12:15 -07005229 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5230 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005231 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005232 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005233 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005234 }
5235 }
5236}
5237
Eric Laurente0720872014-03-11 09:30:41 -07005238void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005239 bool on,
5240 const sp<AudioOutputDescriptor>& outputDesc,
5241 int delayMs,
5242 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005243{
Eric Laurente552edb2014-03-10 17:42:56 -07005244 if (device == AUDIO_DEVICE_NONE) {
5245 device = outputDesc->device();
5246 }
5247
Eric Laurentc75307b2015-03-17 15:29:32 -07005248 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5249 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005250
5251 if (on) {
5252 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005253 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005254 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005255 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005256 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005257 }
5258 }
5259 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5260 outputDesc->mMuteCount[stream]++;
5261 } else {
5262 if (outputDesc->mMuteCount[stream] == 0) {
5263 ALOGV("setStreamMute() unmuting non muted stream!");
5264 return;
5265 }
5266 if (--outputDesc->mMuteCount[stream] == 0) {
5267 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005268 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005269 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005270 device,
5271 delayMs);
5272 }
5273 }
5274}
5275
Eric Laurente0720872014-03-11 09:30:41 -07005276void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005277 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005278{
Eric Laurent87ffa392015-05-22 10:32:38 -07005279 if(!hasPrimaryOutput()) {
5280 return;
5281 }
5282
Eric Laurente552edb2014-03-10 17:42:56 -07005283 // if the stream pertains to sonification strategy and we are in call we must
5284 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5285 // in the device used for phone strategy and play the tone if the selected device does not
5286 // interfere with the device used for phone strategy
5287 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5288 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005289 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005290 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5291 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005292 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005293 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5294 stream, starting, outputDesc->mDevice, stateChange);
5295 if (outputDesc->mRefCount[stream]) {
5296 int muteCount = 1;
5297 if (stateChange) {
5298 muteCount = outputDesc->mRefCount[stream];
5299 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005300 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005301 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5302 for (int i = 0; i < muteCount; i++) {
5303 setStreamMute(stream, starting, mPrimaryOutput);
5304 }
5305 } else {
5306 ALOGV("handleIncallSonification() high visibility");
5307 if (outputDesc->device() &
5308 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5309 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5310 for (int i = 0; i < muteCount; i++) {
5311 setStreamMute(stream, starting, mPrimaryOutput);
5312 }
5313 }
5314 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005315 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5316 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005317 } else {
5318 mpClientInterface->stopTone();
5319 }
5320 }
5321 }
5322 }
5323}
5324
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005325audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5326{
5327 // flags to stream type mapping
5328 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5329 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5330 }
5331 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5332 return AUDIO_STREAM_BLUETOOTH_SCO;
5333 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005334 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5335 return AUDIO_STREAM_TTS;
5336 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005337
5338 // usage to stream type mapping
5339 switch (attr->usage) {
5340 case AUDIO_USAGE_MEDIA:
5341 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005342 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005343 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5344 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005345 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5346 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005347 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5348 return AUDIO_STREAM_SYSTEM;
5349 case AUDIO_USAGE_VOICE_COMMUNICATION:
5350 return AUDIO_STREAM_VOICE_CALL;
5351
5352 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5353 return AUDIO_STREAM_DTMF;
5354
5355 case AUDIO_USAGE_ALARM:
5356 return AUDIO_STREAM_ALARM;
5357 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5358 return AUDIO_STREAM_RING;
5359
5360 case AUDIO_USAGE_NOTIFICATION:
5361 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5362 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5363 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5364 case AUDIO_USAGE_NOTIFICATION_EVENT:
5365 return AUDIO_STREAM_NOTIFICATION;
5366
5367 case AUDIO_USAGE_UNKNOWN:
5368 default:
5369 return AUDIO_STREAM_MUSIC;
5370 }
5371}
Eric Laurente83b55d2014-11-14 10:06:21 -08005372
François Gaffie53615e22015-03-19 09:24:12 +01005373bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5374{
Eric Laurente83b55d2014-11-14 10:06:21 -08005375 // has flags that map to a strategy?
5376 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5377 return true;
5378 }
5379
5380 // has known usage?
5381 switch (paa->usage) {
5382 case AUDIO_USAGE_UNKNOWN:
5383 case AUDIO_USAGE_MEDIA:
5384 case AUDIO_USAGE_VOICE_COMMUNICATION:
5385 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5386 case AUDIO_USAGE_ALARM:
5387 case AUDIO_USAGE_NOTIFICATION:
5388 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5389 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5390 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5391 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5392 case AUDIO_USAGE_NOTIFICATION_EVENT:
5393 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5394 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5395 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5396 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005397 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005398 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005399 break;
5400 default:
5401 return false;
5402 }
5403 return true;
5404}
5405
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005406bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005407 routing_strategy strategy, uint32_t inPastMs,
5408 nsecs_t sysTime) const
5409{
5410 if ((sysTime == 0) && (inPastMs != 0)) {
5411 sysTime = systemTime();
5412 }
Eric Laurent794fde22016-03-11 09:50:45 -08005413 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005414 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5415 (NUM_STRATEGIES == strategy)) &&
5416 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5417 return true;
5418 }
5419 }
5420 return false;
5421}
5422
François Gaffie2110e042015-03-24 08:41:51 +01005423audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5424{
5425 return mEngine->getForceUse(usage);
5426}
5427
5428bool AudioPolicyManager::isInCall()
5429{
5430 return isStateInCall(mEngine->getPhoneState());
5431}
5432
5433bool AudioPolicyManager::isStateInCall(int state)
5434{
5435 return is_state_in_call(state);
5436}
5437
Eric Laurentd60560a2015-04-10 11:31:20 -07005438void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5439{
5440 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5441 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5442 if (sourceDesc->mDevice->equals(deviceDesc)) {
5443 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5444 stopAudioSource(sourceDesc->getHandle());
5445 }
5446 }
5447
5448 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5449 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5450 bool release = false;
5451 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5452 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5453 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5454 source->ext.device.type == deviceDesc->type()) {
5455 release = true;
5456 }
5457 }
5458 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5459 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5460 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5461 sink->ext.device.type == deviceDesc->type()) {
5462 release = true;
5463 }
5464 }
5465 if (release) {
5466 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5467 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5468 }
5469 }
5470}
5471
Phil Burk09bc4612016-02-24 15:58:15 -08005472// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005473void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5474 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005475 // TODO Set this based on Config properties.
5476 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005477
5478 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5479 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005480 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005481
5482 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005483 bool supportsAC3 = false;
5484 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005485 bool supportsIEC61937 = false;
5486 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5487 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005488 switch (format) {
5489 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005490 supportsAC3 = true;
5491 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005492 case AUDIO_FORMAT_E_AC3:
5493 case AUDIO_FORMAT_DTS:
5494 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005495 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005496 break;
5497 case AUDIO_FORMAT_IEC61937:
5498 supportsIEC61937 = true;
5499 break;
5500 default:
5501 break;
5502 }
5503 }
Phil Burk09bc4612016-02-24 15:58:15 -08005504
5505 // Modify formats based on surround preferences.
5506 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005507 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5508 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5509 // Remove surround sound related formats.
5510 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5511 audio_format_t format = formats[formatIndex];
5512 switch(format) {
5513 case AUDIO_FORMAT_AC3:
5514 case AUDIO_FORMAT_E_AC3:
5515 case AUDIO_FORMAT_DTS:
5516 case AUDIO_FORMAT_DTS_HD:
5517 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005518 formats.removeAt(formatIndex);
5519 break;
5520 default:
5521 formatIndex++; // keep it
5522 break;
5523 }
Phil Burk09bc4612016-02-24 15:58:15 -08005524 }
Phil Burk07ac1142016-03-25 13:39:29 -07005525 supportsAC3 = false;
5526 supportsOtherSurround = false;
5527 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005528 }
Phil Burk07ac1142016-03-25 13:39:29 -07005529 } else { // AUTO or ALWAYS
5530 // Most TVs support AC3 even if they do not report it in the EDID.
5531 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5532 && !supportsAC3) {
5533 formats.add(AUDIO_FORMAT_AC3);
5534 supportsAC3 = true;
5535 }
5536
5537 // If ALWAYS, add support for raw surround formats if all are missing.
5538 // This assumes that if any of these formats are reported by the HAL
5539 // then the report is valid and should not be modified.
5540 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5541 && !supportsOtherSurround) {
5542 formats.add(AUDIO_FORMAT_E_AC3);
5543 formats.add(AUDIO_FORMAT_DTS);
5544 formats.add(AUDIO_FORMAT_DTS_HD);
5545 supportsOtherSurround = true;
5546 }
5547
5548 // Add support for IEC61937 if any raw surround supported.
5549 // The HAL could do this but add it here, just in case.
5550 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5551 formats.add(AUDIO_FORMAT_IEC61937);
5552 supportsIEC61937 = true;
5553 }
Phil Burk09bc4612016-02-24 15:58:15 -08005554 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005555}
5556
5557// Modify the list of channel masks supported.
5558void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5559 ChannelsVector &channelMasks = *channelMasksPtr;
5560 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5561 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5562
5563 // If NEVER, then remove support for channelMasks > stereo.
5564 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5565 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5566 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5567 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5568 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5569 channelMasks.removeAt(maskIndex);
5570 } else {
5571 maskIndex++;
5572 }
5573 }
5574 // If ALWAYS, then make sure we at least support 5.1
5575 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5576 bool supports5dot1 = false;
5577 // Are there any channel masks that can be considered "surround"?
5578 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5579 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5580 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5581 supports5dot1 = true;
5582 break;
5583 }
5584 }
5585 // If not then add 5.1 support.
5586 if (!supports5dot1) {
5587 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5588 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5589 }
Phil Burk09bc4612016-02-24 15:58:15 -08005590 }
5591}
5592
Phil Burk00eeb322016-03-31 12:41:00 -07005593void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5594 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005595 AudioProfileVector &profiles)
5596{
5597 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005598
François Gaffie112b0af2015-11-19 16:13:25 +01005599 // Format MUST be checked first to update the list of AudioProfile
5600 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005601 reply = mpClientInterface->getParameters(
5602 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005603 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005604 AudioParameter repliedParameters(reply);
5605 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005606 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005607 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5608 return;
5609 }
Phil Burk09bc4612016-02-24 15:58:15 -08005610 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005611 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005612 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005613 }
Phil Burk09bc4612016-02-24 15:58:15 -08005614 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005615 }
5616 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5617
Eric Laurent20eb3a42016-01-26 18:39:17 -08005618 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005619 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005620 ChannelsVector channelMasks;
5621 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005622 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005623 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005624
5625 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005626 reply = mpClientInterface->getParameters(
5627 ioHandle,
5628 requestedParameters.toString() + ";" +
5629 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005630 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005631 AudioParameter repliedParameters(reply);
5632 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005633 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005634 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005635 }
5636 }
5637 if (profiles.hasDynamicChannelsFor(format)) {
5638 reply = mpClientInterface->getParameters(ioHandle,
5639 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005640 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005641 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005642 AudioParameter repliedParameters(reply);
5643 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005644 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005645 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005646 if (device == AUDIO_DEVICE_OUT_HDMI) {
5647 filterSurroundChannelMasks(&channelMasks);
5648 }
François Gaffie112b0af2015-11-19 16:13:25 +01005649 }
5650 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005651 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005652 }
5653}
Eric Laurentd60560a2015-04-10 11:31:20 -07005654
Eric Laurente552edb2014-03-10 17:42:56 -07005655}; // namespace android