blob: c2b282eb8f972440ccc9b0179ed5520b87e7425f [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
Eric Laurentdc462862016-07-19 12:29:53 -0700336uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700337{
338 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 status_t status;
340 audio_patch_handle_t afPatchHandle;
341 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700342 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700343
Eric Laurent87ffa392015-05-22 10:32:38 -0700344 if(!hasPrimaryOutput()) {
Eric Laurentdc462862016-07-19 12:29:53 -0700345 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700346 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800347 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700348 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
349
350 // release existing RX patch if any
351 if (mCallRxPatch != 0) {
352 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
353 mCallRxPatch.clear();
354 }
355 // release TX patch if any
356 if (mCallTxPatch != 0) {
357 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
358 mCallTxPatch.clear();
359 }
360
361 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
362 // via setOutputDevice() on primary output.
363 // Otherwise, create two audio patches for TX and RX path.
364 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700365 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700366 // If the TX device is also on the primary HW module, setOutputDevice() will take care
367 // of it due to legacy implementation. If not, create a patch.
368 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
369 == AUDIO_DEVICE_NONE) {
370 createTxPatch = true;
371 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700372 } else { // create RX path audio patch
373 struct audio_patch patch;
374
375 patch.num_sources = 1;
376 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700377 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
378 ALOG_ASSERT(!deviceList.isEmpty(),
379 "updateCallRouting() selected device not in output device list");
380 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
381 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
382 ALOG_ASSERT(!deviceList.isEmpty(),
383 "updateCallRouting() no telephony RX device");
384 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
385
386 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
387 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
388
389 // request to reuse existing output stream if one is already opened to reach the RX device
390 SortedVector<audio_io_handle_t> outputs =
391 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700392 audio_io_handle_t output = selectOutput(outputs,
393 AUDIO_OUTPUT_FLAG_NONE,
394 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700395 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700396 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700397 ALOG_ASSERT(!outputDesc->isDuplicated(),
398 "updateCallRouting() RX device output is duplicated");
399 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700400 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700401 patch.num_sources = 2;
402 }
403
404 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700405 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700406 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
407 status);
408 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100409 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700410 mCallRxPatch->mAfPatchHandle = afPatchHandle;
411 mCallRxPatch->mUid = mUidCached;
412 }
413 createTxPatch = true;
414 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700415 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700416 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700417
Eric Laurentc2730ba2014-07-20 15:47:07 -0700418 patch.num_sources = 1;
419 patch.num_sinks = 1;
420 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
421 ALOG_ASSERT(!deviceList.isEmpty(),
422 "updateCallRouting() selected device not in input device list");
423 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
424 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
425 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
426 ALOG_ASSERT(!deviceList.isEmpty(),
427 "updateCallRouting() no telephony TX device");
428 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
429 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
430
431 SortedVector<audio_io_handle_t> outputs =
432 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700433 audio_io_handle_t output = selectOutput(outputs,
434 AUDIO_OUTPUT_FLAG_NONE,
435 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436 // request to reuse existing output stream if one is already opened to reach the TX
437 // path output device
438 if (output != AUDIO_IO_HANDLE_NONE) {
439 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
440 ALOG_ASSERT(!outputDesc->isDuplicated(),
441 "updateCallRouting() RX device output is duplicated");
442 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700443 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700444 patch.num_sources = 2;
445 }
446
Eric Laurentc0a889f2015-10-14 14:36:34 -0700447 // terminate active capture if on the same HW module as the call TX source device
448 // FIXME: would be better to refine to only inputs whose profile connects to the
449 // call TX device but this information is not in the audio patch and logic here must be
450 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800451 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
452 for (size_t i = 0; i < activeInputs.size(); i++) {
453 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
454 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
455 AudioSessionCollection activeSessions =
456 activeDesc->getAudioSessions(true /*activeOnly*/);
457 for (size_t j = 0; j < activeSessions.size(); j++) {
458 audio_session_t activeSession = activeSessions.keyAt(j);
459 stopInput(activeDesc->mIoHandle, activeSession);
460 releaseInput(activeDesc->mIoHandle, activeSession);
461 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700462 }
463 }
464
Eric Laurentc2730ba2014-07-20 15:47:07 -0700465 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700466 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700467 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
468 status);
469 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100470 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700471 mCallTxPatch->mAfPatchHandle = afPatchHandle;
472 mCallTxPatch->mUid = mUidCached;
473 }
474 }
Eric Laurentdc462862016-07-19 12:29:53 -0700475
476 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700477}
478
Eric Laurente0720872014-03-11 09:30:41 -0700479void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700480{
481 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100482 // store previous phone state for management of sonification strategy below
483 int oldState = mEngine->getPhoneState();
484
485 if (mEngine->setPhoneState(state) != NO_ERROR) {
486 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700487 return;
488 }
François Gaffie2110e042015-03-24 08:41:51 +0100489 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700490 // if leaving call state, handle special case of active streams
491 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700492 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700493 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800494 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700495 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700496 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800497
Eric Laurent63dea1d2015-07-02 17:10:28 -0700498 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800499 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700500 }
501
François Gaffie2110e042015-03-24 08:41:51 +0100502 /**
503 * Switching to or from incall state or switching between telephony and VoIP lead to force
504 * routing command.
505 */
506 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
507 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700508
509 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700510 checkA2dpSuspend();
511 checkOutputForAllStrategies();
512 updateDevicesAndOutputs();
513
Eric Laurente552edb2014-03-10 17:42:56 -0700514 int delayMs = 0;
515 if (isStateInCall(state)) {
516 nsecs_t sysTime = systemTime();
517 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700518 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700519 // mute media and sonification strategies and delay device switch by the largest
520 // latency of any output where either strategy is active.
521 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100522 if ((isStrategyActive(desc, STRATEGY_MEDIA,
523 SONIFICATION_HEADSET_MUSIC_DELAY,
524 sysTime) ||
525 isStrategyActive(desc, STRATEGY_SONIFICATION,
526 SONIFICATION_HEADSET_MUSIC_DELAY,
527 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700528 (delayMs < (int)desc->latency()*2)) {
529 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700530 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700531 setStrategyMute(STRATEGY_MEDIA, true, desc);
532 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700533 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700534 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
535 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700536 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
537 }
538 }
539
Eric Laurent87ffa392015-05-22 10:32:38 -0700540 if (hasPrimaryOutput()) {
541 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
542 // the device returned is not necessarily reachable via this output
543 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
544 // force routing command to audio hardware when ending call
545 // even if no device change is needed
546 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
547 rxDevice = mPrimaryOutput->device();
548 }
Eric Laurente552edb2014-03-10 17:42:56 -0700549
Eric Laurent87ffa392015-05-22 10:32:38 -0700550 if (state == AUDIO_MODE_IN_CALL) {
551 updateCallRouting(rxDevice, delayMs);
552 } else if (oldState == AUDIO_MODE_IN_CALL) {
553 if (mCallRxPatch != 0) {
554 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
555 mCallRxPatch.clear();
556 }
557 if (mCallTxPatch != 0) {
558 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
559 mCallTxPatch.clear();
560 }
561 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
562 } else {
563 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700564 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700565 }
Eric Laurente552edb2014-03-10 17:42:56 -0700566 // if entering in call state, handle special case of active streams
567 // pertaining to sonification strategy see handleIncallSonification()
568 if (isStateInCall(state)) {
569 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800570 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700571 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700572 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700573
574 // force reevaluating accessibility routing when call starts
575 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700576 }
577
578 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700579 if (state == AUDIO_MODE_RINGTONE &&
580 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700581 mLimitRingtoneVolume = true;
582 } else {
583 mLimitRingtoneVolume = false;
584 }
585}
586
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700587audio_mode_t AudioPolicyManager::getPhoneState() {
588 return mEngine->getPhoneState();
589}
590
Eric Laurente0720872014-03-11 09:30:41 -0700591void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700592 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700593{
François Gaffie2110e042015-03-24 08:41:51 +0100594 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700595
François Gaffie2110e042015-03-24 08:41:51 +0100596 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
597 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
598 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
François Gaffie2110e042015-03-24 08:41:51 +0100600 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
601 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
602 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700603
604 // check for device and output changes triggered by new force usage
605 checkA2dpSuspend();
606 checkOutputForAllStrategies();
607 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800608
Eric Laurentdc462862016-07-19 12:29:53 -0700609 //FIXME: workaround for truncated touch sounds
610 // to be removed when the problem is handled by system UI
611 uint32_t delayMs = 0;
612 uint32_t waitMs = 0;
613 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
614 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
615 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700616 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700618 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 }
Eric Laurente552edb2014-03-10 17:42:56 -0700620 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700621 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
622 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
623 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700624 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
625 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700626 }
Eric Laurente552edb2014-03-10 17:42:56 -0700627 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700628 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700629 }
630 }
631
Eric Laurentfb66dd92016-01-28 18:32:03 -0800632 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
633 for (size_t i = 0; i < activeInputs.size(); i++) {
634 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
635 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700636 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800637 if (activeDesc->mProfile->getSupportedDevices().types() &
638 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
639 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700640 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800641 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700642 }
Eric Laurente552edb2014-03-10 17:42:56 -0700643 }
Eric Laurente552edb2014-03-10 17:42:56 -0700644}
645
Eric Laurente0720872014-03-11 09:30:41 -0700646void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700647{
648 ALOGV("setSystemProperty() property %s, value %s", property, value);
649}
650
651// Find a direct output profile compatible with the parameters passed, even if the input flags do
652// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800653sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700654 audio_devices_t device,
655 uint32_t samplingRate,
656 audio_format_t format,
657 audio_channel_mask_t channelMask,
658 audio_output_flags_t flags)
659{
Eric Laurent861a6282015-05-18 15:40:16 -0700660 // only retain flags that will drive the direct output profile selection
661 // if explicitly requested
662 static const uint32_t kRelevantFlags =
663 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
664 flags =
665 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
666
667 sp<IOProfile> profile;
668
Eric Laurente552edb2014-03-10 17:42:56 -0700669 for (size_t i = 0; i < mHwModules.size(); i++) {
670 if (mHwModules[i]->mHandle == 0) {
671 continue;
672 }
673 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700674 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
675 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700676 samplingRate, NULL /*updatedSamplingRate*/,
677 format, NULL /*updatedFormat*/,
678 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700679 flags)) {
680 continue;
681 }
682 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100683 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700684 continue;
685 }
686 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100687 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700688 continue;
689 }
690 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100691 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700692 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700693 }
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
695 }
Eric Laurent861a6282015-05-18 15:40:16 -0700696 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700697}
698
Eric Laurente0720872014-03-11 09:30:41 -0700699audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100700 uint32_t samplingRate,
701 audio_format_t format,
702 audio_channel_mask_t channelMask,
703 audio_output_flags_t flags,
704 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700705{
Eric Laurent3b73df72014-03-11 09:06:29 -0700706 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700707 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
708 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
709 device, stream, samplingRate, format, channelMask, flags);
710
Eric Laurente83b55d2014-11-14 10:06:21 -0800711 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
712 stream, samplingRate,format, channelMask,
713 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700714}
715
Eric Laurente83b55d2014-11-14 10:06:21 -0800716status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
717 audio_io_handle_t *output,
718 audio_session_t session,
719 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700720 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800721 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800722 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700723 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800724 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700725{
Eric Laurente83b55d2014-11-14 10:06:21 -0800726 audio_attributes_t attributes;
727 if (attr != NULL) {
728 if (!isValidAttributes(attr)) {
729 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
730 attr->usage, attr->content_type, attr->flags,
731 attr->tags);
732 return BAD_VALUE;
733 }
734 attributes = *attr;
735 } else {
736 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
737 ALOGE("getOutputForAttr(): invalid stream type");
738 return BAD_VALUE;
739 }
740 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700741 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800742
743 // TODO: check for existing client for this port ID
744 if (*portId == AUDIO_PORT_HANDLE_NONE) {
745 *portId = AudioPort::getNextUniqueId();
746 }
747
Eric Laurentc75307b2015-03-17 15:29:32 -0700748 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800749 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100750 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800751 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100752 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800753 }
François Gaffie036e1e92015-03-19 10:16:24 +0100754 *stream = streamTypefromAttributesInt(&attributes);
755 *output = desc->mIoHandle;
756 ALOGV("getOutputForAttr() returns output %d", *output);
757 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800758 }
759 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
760 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
761 return BAD_VALUE;
762 }
763
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700764 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
765 " session %d selectedDeviceId %d",
766 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
767 session, selectedDeviceId);
768
769 *stream = streamTypefromAttributesInt(&attributes);
770
771 // Explicit routing?
772 sp<DeviceDescriptor> deviceDesc;
773 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
774 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
775 deviceDesc = mAvailableOutputDevices[i];
776 break;
777 }
778 }
779 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700780
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700782 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700783
Eric Laurente83b55d2014-11-14 10:06:21 -0800784 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700785 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
786 }
787
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700788 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800789 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700790
Eric Laurente83b55d2014-11-14 10:06:21 -0800791 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800792 config->sample_rate, config->format, config->channel_mask,
793 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800794 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700795 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800796 return INVALID_OPERATION;
797 }
Paul McLeanaa981192015-03-21 09:55:15 -0700798
Eric Laurente83b55d2014-11-14 10:06:21 -0800799 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700800}
801
802audio_io_handle_t AudioPolicyManager::getOutputForDevice(
803 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800804 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700805 audio_stream_type_t stream,
806 uint32_t samplingRate,
807 audio_format_t format,
808 audio_channel_mask_t channelMask,
809 audio_output_flags_t flags,
810 const audio_offload_info_t *offloadInfo)
811{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700812 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700813 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700814
Eric Laurente552edb2014-03-10 17:42:56 -0700815#ifdef AUDIO_POLICY_TEST
816 if (mCurOutput != 0) {
817 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
818 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
819
820 if (mTestOutputs[mCurOutput] == 0) {
821 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700822 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
823 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700825 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700826 outputDesc->mFlags =
827 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700828 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700829 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
830 config.sample_rate = mTestSamplingRate;
831 config.channel_mask = mTestChannels;
832 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700833 if (offloadInfo != NULL) {
834 config.offload_info = *offloadInfo;
835 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700836 status = mpClientInterface->openOutput(0,
837 &mTestOutputs[mCurOutput],
838 &config,
839 &outputDesc->mDevice,
840 String8(""),
841 &outputDesc->mLatency,
842 outputDesc->mFlags);
843 if (status == NO_ERROR) {
844 outputDesc->mSamplingRate = config.sample_rate;
845 outputDesc->mFormat = config.format;
846 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700847 AudioParameter outputCmd = AudioParameter();
848 outputCmd.addInt(String8("set_id"),mCurOutput);
849 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
850 addOutput(mTestOutputs[mCurOutput], outputDesc);
851 }
852 }
853 return mTestOutputs[mCurOutput];
854 }
855#endif //AUDIO_POLICY_TEST
856
857 // open a direct output if required by specified parameters
858 //force direct flag if offload flag is set: offloading implies a direct output stream
859 // and all common behaviors are driven by checking only the direct flag
860 // this should normally be set appropriately in the policy configuration file
861 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700862 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700863 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700864 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
865 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
866 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800867 // only allow deep buffering for music stream type
868 if (stream != AUDIO_STREAM_MUSIC) {
869 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700870 } else if (/* stream == AUDIO_STREAM_MUSIC && */
871 flags == AUDIO_OUTPUT_FLAG_NONE &&
872 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
873 // use DEEP_BUFFER as default output for music stream type
874 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800875 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700876 if (stream == AUDIO_STREAM_TTS) {
877 flags = AUDIO_OUTPUT_FLAG_TTS;
878 }
Eric Laurente552edb2014-03-10 17:42:56 -0700879
Eric Laurentb732cf52014-09-24 19:08:21 -0700880 sp<IOProfile> profile;
881
882 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700883 // and not explicitly requested
884 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800885 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700886 audio_channel_count_from_out_mask(channelMask) <= 2) {
887 goto non_direct_output;
888 }
889
Andy Hung2ddee192015-12-18 17:34:44 -0800890 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
891 // This prevents creating an offloaded track and tearing it down immediately after start
892 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700893 // FIXME: We should check the audio session here but we do not have it in this context.
894 // This may prevent offloading in rare situations where effects are left active by apps
895 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700896
Eric Laurente552edb2014-03-10 17:42:56 -0700897 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800898 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700899 profile = getProfileForDirectOutput(device,
900 samplingRate,
901 format,
902 channelMask,
903 (audio_output_flags_t)flags);
904 }
905
Eric Laurent1c333e22014-05-20 10:48:17 -0700906 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700907 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700908
909 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700910 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700911 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
912 outputDesc = desc;
913 // reuse direct output if currently open and configured with same parameters
914 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800915 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700916 (channelMask == outputDesc->mChannelMask)) {
917 outputDesc->mDirectOpenCount++;
918 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
919 return mOutputs.keyAt(i);
920 }
921 }
922 }
923 // close direct output if currently open and configured with different parameters
924 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700925 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700926 }
Eric Laurent861a6282015-05-18 15:40:16 -0700927
928 // if the selected profile is offloaded and no offload info was specified,
929 // create a default one
930 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100931 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700932 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
933 defaultOffloadInfo.sample_rate = samplingRate;
934 defaultOffloadInfo.channel_mask = channelMask;
935 defaultOffloadInfo.format = format;
936 defaultOffloadInfo.stream_type = stream;
937 defaultOffloadInfo.bit_rate = 0;
938 defaultOffloadInfo.duration_us = -1;
939 defaultOffloadInfo.has_video = true; // conservative
940 defaultOffloadInfo.is_streaming = true; // likely
941 offloadInfo = &defaultOffloadInfo;
942 }
943
Eric Laurentc75307b2015-03-17 15:29:32 -0700944 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700945 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700946 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700947 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700948 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
949 config.sample_rate = samplingRate;
950 config.channel_mask = channelMask;
951 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700952 if (offloadInfo != NULL) {
953 config.offload_info = *offloadInfo;
954 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700955 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700956 &output,
957 &config,
958 &outputDesc->mDevice,
959 String8(""),
960 &outputDesc->mLatency,
961 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700962
963 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700964 if (status != NO_ERROR ||
965 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800966 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700967 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700968 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
969 "format %d %d, channelMask %04x %04x", output, samplingRate,
970 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
971 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700973 mpClientInterface->closeOutput(output);
974 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800975 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800976 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800977 goto non_direct_output;
978 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700979 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700981 outputDesc->mSamplingRate = config.sample_rate;
982 outputDesc->mChannelMask = config.channel_mask;
983 outputDesc->mFormat = config.format;
984 outputDesc->mRefCount[stream] = 0;
985 outputDesc->mStopTime[stream] = 0;
986 outputDesc->mDirectOpenCount = 1;
987
Eric Laurente552edb2014-03-10 17:42:56 -0700988 audio_io_handle_t srcOutput = getOutputForEffect();
989 addOutput(output, outputDesc);
990 audio_io_handle_t dstOutput = getOutputForEffect();
991 if (dstOutput == output) {
992 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
993 }
994 mPreviousOutputs = mOutputs;
995 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700996 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700997 return output;
998 }
999
Eric Laurentb732cf52014-09-24 19:08:21 -07001000non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001001
1002 // A request for HW A/V sync cannot fallback to a mixed output because time
1003 // stamps are embedded in audio data
1004 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1005 return AUDIO_IO_HANDLE_NONE;
1006 }
1007
Eric Laurente552edb2014-03-10 17:42:56 -07001008 // ignoring channel mask due to downmix capability in mixer
1009
1010 // open a non direct output
1011
1012 // for non direct outputs, only PCM is supported
1013 if (audio_is_linear_pcm(format)) {
1014 // get which output is suitable for the specified stream. The actual
1015 // routing change will happen when startOutput() will be called
1016 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1017
Eric Laurent8838a382014-09-08 16:44:28 -07001018 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1019 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1020 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001021 }
1022 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1023 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1024
Paul McLeanaa981192015-03-21 09:55:15 -07001025 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001026
1027 return output;
1028}
1029
Eric Laurente0720872014-03-11 09:30:41 -07001030audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001031 audio_output_flags_t flags,
1032 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001033{
1034 // select one output among several that provide a path to a particular device or set of
1035 // devices (the list was previously build by getOutputsForDevice()).
1036 // The priority is as follows:
1037 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001038 // 2: the output with the bit depth the closest to the requested one
1039 // 3: the primary output
1040 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001041
1042 if (outputs.size() == 0) {
1043 return 0;
1044 }
1045 if (outputs.size() == 1) {
1046 return outputs[0];
1047 }
1048
1049 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001050 audio_io_handle_t outputForFlags = 0;
1051 audio_io_handle_t outputForPrimary = 0;
1052 audio_io_handle_t outputForFormat = 0;
1053 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1054 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001055
1056 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001057 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001058 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001059 // if a valid format is specified, skip output if not compatible
1060 if (format != AUDIO_FORMAT_INVALID) {
1061 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001062 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001063 continue;
1064 }
1065 } else if (!audio_is_linear_pcm(format)) {
1066 continue;
1067 }
Eric Laurente6930022016-02-11 10:20:40 -08001068 if (AudioPort::isBetterFormatMatch(
1069 outputDesc->mFormat, bestFormat, format)) {
1070 outputForFormat = outputs[i];
1071 bestFormat = outputDesc->mFormat;
1072 }
Eric Laurent8838a382014-09-08 16:44:28 -07001073 }
1074
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001075 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001076 if (commonFlags >= maxCommonFlags) {
1077 if (commonFlags == maxCommonFlags) {
1078 if (AudioPort::isBetterFormatMatch(
1079 outputDesc->mFormat, bestFormatForFlags, format)) {
1080 outputForFlags = outputs[i];
1081 bestFormatForFlags = outputDesc->mFormat;
1082 }
1083 } else {
1084 outputForFlags = outputs[i];
1085 maxCommonFlags = commonFlags;
1086 bestFormatForFlags = outputDesc->mFormat;
1087 }
Eric Laurente552edb2014-03-10 17:42:56 -07001088 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1089 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001090 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001091 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001092 }
1093 }
1094 }
1095
Eric Laurente6930022016-02-11 10:20:40 -08001096 if (outputForFlags != 0) {
1097 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001098 }
Eric Laurente6930022016-02-11 10:20:40 -08001099 if (outputForFormat != 0) {
1100 return outputForFormat;
1101 }
1102 if (outputForPrimary != 0) {
1103 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001104 }
1105
1106 return outputs[0];
1107}
1108
Eric Laurente0720872014-03-11 09:30:41 -07001109status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001110 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001111 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001112{
Paul McLeanaa981192015-03-21 09:55:15 -07001113 ALOGV("startOutput() output %d, stream %d, session %d",
1114 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001115 ssize_t index = mOutputs.indexOfKey(output);
1116 if (index < 0) {
1117 ALOGW("startOutput() unknown output %d", output);
1118 return BAD_VALUE;
1119 }
1120
Eric Laurentc75307b2015-03-17 15:29:32 -07001121 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1122
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001123 // Routing?
1124 mOutputRoutes.incRouteActivity(session);
1125
Eric Laurentc75307b2015-03-17 15:29:32 -07001126 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001127 AudioMix *policyMix = NULL;
1128 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001129 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001130 policyMix = outputDesc->mPolicyMix;
1131 address = policyMix->mDeviceAddress.string();
1132 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1133 newDevice = policyMix->mDeviceType;
1134 } else {
1135 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1136 }
Eric Laurent493404d2015-04-21 15:07:36 -07001137 } else if (mOutputRoutes.hasRouteChanged(session)) {
1138 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001139 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001140 } else {
1141 newDevice = AUDIO_DEVICE_NONE;
1142 }
1143
1144 uint32_t delayMs = 0;
1145
Eric Laurentc40d9692016-04-13 19:14:13 -07001146 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001147
1148 if (status != NO_ERROR) {
1149 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001150 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001151 }
1152 // Automatically enable the remote submix input when output is started on a re routing mix
1153 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001154 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1155 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001156 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1157 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001158 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001159 "remote-submix");
1160 }
1161
1162 if (delayMs != 0) {
1163 usleep(delayMs * 1000);
1164 }
1165
1166 return status;
1167}
1168
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001169status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001170 audio_stream_type_t stream,
1171 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001172 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001173 uint32_t *delayMs)
1174{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001175 // cannot start playback of STREAM_TTS if any other output is being used
1176 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001177
1178 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001179 if (stream == AUDIO_STREAM_TTS) {
1180 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001181 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001182 return INVALID_OPERATION;
1183 } else {
1184 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1185 }
1186 } else {
1187 // some playback other than beacon starts
1188 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1189 }
1190
Eric Laurent77305a62016-07-25 16:39:22 -07001191 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001192 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001193 bool force = !outputDesc->isActive() &&
1194 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001195
Eric Laurente552edb2014-03-10 17:42:56 -07001196 // increment usage count for this stream on the requested output:
1197 // NOTE that the usage count is the same for duplicated output and hardware output which is
1198 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1199 outputDesc->changeRefCount(stream, 1);
1200
Eric Laurent493404d2015-04-21 15:07:36 -07001201 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001202 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001203 if (device == AUDIO_DEVICE_NONE) {
1204 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001205 }
Eric Laurente552edb2014-03-10 17:42:56 -07001206 routing_strategy strategy = getStrategy(stream);
1207 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001208 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1209 (beaconMuteLatency > 0);
1210 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001211 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001212 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001213 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001214 // force a device change if any other output is:
1215 // - managed by the same hw module
1216 // - has a current device selection that differs from selected device.
1217 // - supports currently selected device
1218 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001219 // In this case, the audio HAL must receive the new device selection so that it can
1220 // change the device currently selected by the other active output.
1221 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001222 desc->device() != device &&
1223 desc->supportedDevices() & device &&
1224 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001225 force = true;
1226 }
1227 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001228 // a notification so that audio focus effect can propagate, or that a mute/unmute
1229 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001230 uint32_t latency = desc->latency();
1231 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1232 waitMs = latency;
1233 }
1234 }
1235 }
Eric Laurentdc462862016-07-19 12:29:53 -07001236 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001237
1238 // handle special case for sonification while in call
1239 if (isInCall()) {
1240 handleIncallSonification(stream, true, false);
1241 }
1242
1243 // apply volume rules for current stream and device if necessary
1244 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001245 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001246 outputDesc,
1247 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001248
1249 // update the outputs if starting an output with a stream that can affect notification
1250 // routing
1251 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001252
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001253 // force reevaluating accessibility routing when ringtone or alarm starts
1254 if (strategy == STRATEGY_SONIFICATION) {
1255 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1256 }
Eric Laurentdc462862016-07-19 12:29:53 -07001257
1258 if (waitMs > muteWaitMs) {
1259 *delayMs = waitMs - muteWaitMs;
1260 }
Eric Laurente552edb2014-03-10 17:42:56 -07001261 }
Eric Laurentdc462862016-07-19 12:29:53 -07001262
Eric Laurente552edb2014-03-10 17:42:56 -07001263 return NO_ERROR;
1264}
1265
1266
Eric Laurente0720872014-03-11 09:30:41 -07001267status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001268 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001269 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001270{
1271 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1272 ssize_t index = mOutputs.indexOfKey(output);
1273 if (index < 0) {
1274 ALOGW("stopOutput() unknown output %d", output);
1275 return BAD_VALUE;
1276 }
1277
Eric Laurentc75307b2015-03-17 15:29:32 -07001278 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001279
Eric Laurentc75307b2015-03-17 15:29:32 -07001280 if (outputDesc->mRefCount[stream] == 1) {
1281 // Automatically disable the remote submix input when output is stopped on a
1282 // re routing mix of type MIX_TYPE_RECORDERS
1283 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1284 outputDesc->mPolicyMix != NULL &&
1285 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1286 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1287 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001288 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001289 "remote-submix");
1290 }
1291 }
1292
1293 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001294 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001295 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001296 int activityCount = mOutputRoutes.decRouteActivity(session);
1297 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1298
1299 if (forceDeviceUpdate) {
1300 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1301 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001302 }
1303
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001304 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001305}
1306
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001307status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001308 audio_stream_type_t stream,
1309 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001310{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001311 // always handle stream stop, check which stream type is stopping
1312 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1313
Eric Laurente552edb2014-03-10 17:42:56 -07001314 // handle special case for sonification while in call
1315 if (isInCall()) {
1316 handleIncallSonification(stream, false, false);
1317 }
1318
1319 if (outputDesc->mRefCount[stream] > 0) {
1320 // decrement usage count of this stream on the output
1321 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001322
Eric Laurente552edb2014-03-10 17:42:56 -07001323 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001324 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001325 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001326 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001327 // delay the device switch by twice the latency because stopOutput() is executed when
1328 // the track stop() command is received and at that time the audio track buffer can
1329 // still contain data that needs to be drained. The latency only covers the audio HAL
1330 // and kernel buffers. Also the latency does not always include additional delay in the
1331 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001332 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001333
1334 // force restoring the device selection on other active outputs if it differs from the
1335 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001336 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001337 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001338 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001340 desc->isActive() &&
1341 outputDesc->sharesHwModuleWith(desc) &&
1342 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001343 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1344 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001345 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001346 newDevice2,
1347 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001348 delayMs);
1349 // re-apply device specific volume if not done by setOutputDevice()
1350 if (!force) {
1351 applyStreamVolumes(desc, newDevice2, delayMs);
1352 }
Eric Laurente552edb2014-03-10 17:42:56 -07001353 }
1354 }
1355 // update the outputs if stopping one with a stream that can affect notification routing
1356 handleNotificationRoutingForStream(stream);
1357 }
1358 return NO_ERROR;
1359 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001360 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001361 return INVALID_OPERATION;
1362 }
1363}
1364
Eric Laurente83b55d2014-11-14 10:06:21 -08001365void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001366 audio_stream_type_t stream __unused,
1367 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001368{
1369 ALOGV("releaseOutput() %d", output);
1370 ssize_t index = mOutputs.indexOfKey(output);
1371 if (index < 0) {
1372 ALOGW("releaseOutput() releasing unknown output %d", output);
1373 return;
1374 }
1375
1376#ifdef AUDIO_POLICY_TEST
1377 int testIndex = testOutputIndex(output);
1378 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001379 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001380 if (outputDesc->isActive()) {
1381 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001382 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001383 mTestOutputs[testIndex] = 0;
1384 }
1385 return;
1386 }
1387#endif //AUDIO_POLICY_TEST
1388
Paul McLeanaa981192015-03-21 09:55:15 -07001389 // Routing
1390 mOutputRoutes.removeRoute(session);
1391
Eric Laurentc75307b2015-03-17 15:29:32 -07001392 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001393 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001394 if (desc->mDirectOpenCount <= 0) {
1395 ALOGW("releaseOutput() invalid open count %d for output %d",
1396 desc->mDirectOpenCount, output);
1397 return;
1398 }
1399 if (--desc->mDirectOpenCount == 0) {
1400 closeOutput(output);
1401 // If effects where present on the output, audioflinger moved them to the primary
1402 // output by default: move them back to the appropriate output.
1403 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001404 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001405 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1406 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001407 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001408 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001409 }
1410 }
1411}
1412
1413
Eric Laurentcaf7f482014-11-25 17:50:47 -08001414status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1415 audio_io_handle_t *input,
1416 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001417 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001418 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001419 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001420 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001421 input_type_t *inputType,
1422 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001423{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001424 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1425 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001426 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001427
Eric Laurentcaf7f482014-11-25 17:50:47 -08001428 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001429 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001430
Eric Laurent275e8e92014-11-30 15:14:47 -08001431 audio_devices_t device;
1432 // handle legacy remote submix case where the address was not always specified
1433 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001434 audio_source_t inputSource = attr->source;
1435 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001436 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001437
Eric Laurentc447ded2015-01-06 08:47:05 -08001438 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1439 inputSource = AUDIO_SOURCE_MIC;
1440 }
1441 halInputSource = inputSource;
1442
Eric Laurent20b9ef02016-12-05 11:03:16 -08001443 // TODO: check for existing client for this port ID
1444 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1445 *portId = AudioPort::getNextUniqueId();
1446 }
1447
Paul McLean466dc8e2015-04-17 13:15:36 -06001448 // Explicit routing?
1449 sp<DeviceDescriptor> deviceDesc;
1450 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1451 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1452 deviceDesc = mAvailableInputDevices[i];
1453 break;
1454 }
1455 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001456 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001457
Eric Laurentc447ded2015-01-06 08:47:05 -08001458 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001459 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001460 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001461 if (ret != NO_ERROR) {
1462 return ret;
1463 }
1464 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001465 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1466 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001467 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001468 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001469 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001470 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001471 return BAD_VALUE;
1472 }
Eric Laurentc722f302014-12-10 11:21:49 -08001473 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001474 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001475 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1476 // there is an external policy, but this input is attached to a mix of recorders,
1477 // meaning it receives audio injected into the framework, so the recorder doesn't
1478 // know about it and is therefore considered "legacy"
1479 *inputType = API_INPUT_LEGACY;
1480 } else {
1481 // recording a mix of players defined by an external policy, we're rerouting for
1482 // an external policy
1483 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1484 }
Eric Laurentc722f302014-12-10 11:21:49 -08001485 } else if (audio_is_remote_submix_device(device)) {
1486 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001487 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001488 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1489 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001490 } else {
1491 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001492 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001493
Eric Laurent599c7582015-12-07 18:05:55 -08001494 }
1495
1496 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001497 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001498 policyMix);
1499 if (*input == AUDIO_IO_HANDLE_NONE) {
1500 mInputRoutes.removeRoute(session);
1501 return INVALID_OPERATION;
1502 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001503
Eric Laurent599c7582015-12-07 18:05:55 -08001504 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1505 return NO_ERROR;
1506}
1507
1508
1509audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1510 String8 address,
1511 audio_session_t session,
1512 uid_t uid,
1513 audio_source_t inputSource,
1514 uint32_t samplingRate,
1515 audio_format_t format,
1516 audio_channel_mask_t channelMask,
1517 audio_input_flags_t flags,
1518 AudioMix *policyMix)
1519{
1520 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1521 audio_source_t halInputSource = inputSource;
1522 bool isSoundTrigger = false;
1523
1524 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1525 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1526 if (index >= 0) {
1527 input = mSoundTriggerSessions.valueFor(session);
1528 isSoundTrigger = true;
1529 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1530 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1531 } else {
1532 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001533 }
1534 }
1535
Andy Hungf129b032015-04-07 13:45:50 -07001536 // find a compatible input profile (not necessarily identical in parameters)
1537 sp<IOProfile> profile;
1538 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001539 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001540 audio_format_t profileFormat = format;
1541 audio_channel_mask_t profileChannelMask = channelMask;
1542 audio_input_flags_t profileFlags = flags;
1543 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001544 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001545 profileSamplingRate, profileFormat, profileChannelMask,
1546 profileFlags);
1547 if (profile != 0) {
1548 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001549 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1550 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001551 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1552 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1553 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001554 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1555 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001556 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001557 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001558 }
Eric Laurente552edb2014-03-10 17:42:56 -07001559 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001560 // Pick input sampling rate if not specified by client
1561 if (samplingRate == 0) {
1562 samplingRate = profileSamplingRate;
1563 }
Eric Laurente552edb2014-03-10 17:42:56 -07001564
Eric Laurent322b4d22015-04-03 15:57:54 -07001565 if (profile->getModuleHandle() == 0) {
1566 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001567 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001568 }
1569
Eric Laurent599c7582015-12-07 18:05:55 -08001570 sp<AudioSession> audioSession = new AudioSession(session,
1571 inputSource,
1572 format,
1573 samplingRate,
1574 channelMask,
1575 flags,
1576 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001577 isSoundTrigger,
1578 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001579
Eric Laurentfb66dd92016-01-28 18:32:03 -08001580
Eric Laurent599c7582015-12-07 18:05:55 -08001581 // reuse an open input if possible
1582 for (size_t i = 0; i < mInputs.size(); i++) {
1583 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001584 // reuse input if:
1585 // - it shares the same profile
1586 // AND
1587 // - it is not a reroute submix input
1588 // AND
1589 // - it is: not used for sound trigger
1590 // OR
1591 // used for sound trigger and all clients use the same session ID
1592 //
1593 if ((profile == desc->mProfile) &&
1594 (isSoundTrigger == desc->isSoundTrigger()) &&
1595 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001596
1597 sp<AudioSession> as = desc->getAudioSession(session);
1598 if (as != 0) {
1599 // do not allow unmatching properties on same session
1600 if (as->matches(audioSession)) {
1601 as->changeOpenCount(1);
1602 } else {
1603 ALOGW("getInputForDevice() record with different attributes"
1604 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001605 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001606 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001607 } else if (isSoundTrigger) {
1608 break;
1609 }
1610 // force close input if current source is now the highest priority request on this input
1611 // and current input properties are not exactly as requested.
1612 if ((desc->mSamplingRate != samplingRate ||
1613 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001614 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001615 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1616 source_priority(inputSource))) {
1617 ALOGV("%s: ", __FUNCTION__);
1618 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1619 for (size_t j = 0; j < sessions.size(); j++) {
1620 audio_session_t currentSession = sessions.keyAt(j);
1621 stopInput(desc->mIoHandle, currentSession);
1622 releaseInput(desc->mIoHandle, currentSession);
1623 }
1624 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001625 } else {
1626 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001627 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1628 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001629 }
Eric Laurent599c7582015-12-07 18:05:55 -08001630 }
1631 }
Eric Laurent599c7582015-12-07 18:05:55 -08001632
Eric Laurentcf2c0212014-07-25 16:20:43 -07001633 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001634 config.sample_rate = profileSamplingRate;
1635 config.channel_mask = profileChannelMask;
1636 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001637
Eric Laurent322b4d22015-04-03 15:57:54 -07001638 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001639 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001640 &config,
1641 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001642 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001643 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001644 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001645
1646 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001647 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001648 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001649 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001650 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001651 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1652 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001653 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001654 if (input != AUDIO_IO_HANDLE_NONE) {
1655 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001656 }
Eric Laurent599c7582015-12-07 18:05:55 -08001657 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001658 }
1659
Eric Laurent1f2f2232014-06-02 12:01:23 -07001660 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001661 inputDesc->mSamplingRate = profileSamplingRate;
1662 inputDesc->mFormat = profileFormat;
1663 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001664 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001665 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001666 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001667
Eric Laurent599c7582015-12-07 18:05:55 -08001668 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001669 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001670
Eric Laurent599c7582015-12-07 18:05:55 -08001671 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001672}
1673
Eric Laurentfb66dd92016-01-28 18:32:03 -08001674bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1675 const sp<AudioSession>& audioSession)
1676{
1677 // Do not allow capture if an active voice call is using a software patch and
1678 // the call TX source device is on the same HW module.
1679 // FIXME: would be better to refine to only inputs whose profile connects to the
1680 // call TX device but this information is not in the audio patch
1681 if (mCallTxPatch != 0 &&
1682 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1683 return false;
1684 }
1685
1686 // starting concurrent capture is enabled if:
1687 // 1) capturing for re-routing
1688 // 2) capturing for HOTWORD source
1689 // 3) capturing for FM TUNER source
1690 // 3) All other active captures are either for re-routing or HOTWORD
1691
1692 if (is_virtual_input_device(inputDesc->mDevice) ||
1693 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1694 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1695 return true;
1696 }
1697
1698 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1699 for (size_t i = 0; i < activeInputs.size(); i++) {
1700 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1701 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1702 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1703 !is_virtual_input_device(activeInput->mDevice)) {
1704 return false;
1705 }
1706 }
1707
1708 return true;
1709}
1710
1711
Eric Laurent4dc68062014-07-28 17:26:49 -07001712status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001713 audio_session_t session,
1714 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001715{
1716 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001717 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001718 ssize_t index = mInputs.indexOfKey(input);
1719 if (index < 0) {
1720 ALOGW("startInput() unknown input %d", input);
1721 return BAD_VALUE;
1722 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001723 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001724
Eric Laurent599c7582015-12-07 18:05:55 -08001725 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1726 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001727 ALOGW("startInput() unknown session %d on input %d", session, input);
1728 return BAD_VALUE;
1729 }
1730
Eric Laurentfb66dd92016-01-28 18:32:03 -08001731 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1732 ALOGW("startInput(%d) failed: other input already started", input);
1733 return INVALID_OPERATION;
1734 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001735
Eric Laurentfb66dd92016-01-28 18:32:03 -08001736 if (isInCall()) {
1737 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1738 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001739 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001740 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001741 }
1742
Eric Laurent313d1e72016-01-29 09:56:57 -08001743 // increment activity count before calling getNewInputDevice() below as only active sessions
1744 // are considered for device selection
1745 audioSession->changeActiveCount(1);
1746
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001747 // Routing?
1748 mInputRoutes.incRouteActivity(session);
1749
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001750 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001751 // indicate active capture to sound trigger service if starting capture from a mic on
1752 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001753 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001754 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001755
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001756 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1757 // if input maps to a dynamic policy with an activity listener, notify of state change
1758 if ((inputDesc->mPolicyMix != NULL)
1759 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1760 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1761 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001762 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001763
Eric Laurentf7c50102016-09-30 15:19:43 -07001764 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1765 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001766 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001767 SoundTrigger::setCaptureState(true);
1768 }
1769
1770 // automatically enable the remote submix output when input is started if not
1771 // used by a policy mix of type MIX_TYPE_RECORDERS
1772 // For remote submix (a virtual device), we open only one input per capture request.
1773 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1774 String8 address = String8("");
1775 if (inputDesc->mPolicyMix == NULL) {
1776 address = String8("0");
1777 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1778 address = inputDesc->mPolicyMix->mDeviceAddress;
1779 }
1780 if (address != "") {
1781 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1782 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1783 address, "remote-submix");
1784 }
Eric Laurentc722f302014-12-10 11:21:49 -08001785 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001786 }
Eric Laurente552edb2014-03-10 17:42:56 -07001787 }
1788
Eric Laurent599c7582015-12-07 18:05:55 -08001789 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001790
Eric Laurente552edb2014-03-10 17:42:56 -07001791 return NO_ERROR;
1792}
1793
Eric Laurent4dc68062014-07-28 17:26:49 -07001794status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1795 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001796{
1797 ALOGV("stopInput() input %d", input);
1798 ssize_t index = mInputs.indexOfKey(input);
1799 if (index < 0) {
1800 ALOGW("stopInput() unknown input %d", input);
1801 return BAD_VALUE;
1802 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001803 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001804
Eric Laurent599c7582015-12-07 18:05:55 -08001805 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001806 if (index < 0) {
1807 ALOGW("stopInput() unknown session %d on input %d", session, input);
1808 return BAD_VALUE;
1809 }
1810
Eric Laurent599c7582015-12-07 18:05:55 -08001811 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001812 ALOGW("stopInput() input %d already stopped", input);
1813 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001814 }
1815
Eric Laurent599c7582015-12-07 18:05:55 -08001816 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001817
1818 // Routing?
1819 mInputRoutes.decRouteActivity(session);
1820
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001821 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001822
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001823 if (inputDesc->isActive()) {
1824 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1825 } else {
1826 // if input maps to a dynamic policy with an activity listener, notify of state change
1827 if ((inputDesc->mPolicyMix != NULL)
1828 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1829 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1830 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001831 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001832
1833 // automatically disable the remote submix output when input is stopped if not
1834 // used by a policy mix of type MIX_TYPE_RECORDERS
1835 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1836 String8 address = String8("");
1837 if (inputDesc->mPolicyMix == NULL) {
1838 address = String8("0");
1839 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1840 address = inputDesc->mPolicyMix->mDeviceAddress;
1841 }
1842 if (address != "") {
1843 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1844 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1845 address, "remote-submix");
1846 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001847 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001848
Eric Laurentf7c50102016-09-30 15:19:43 -07001849 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001850 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001851
Eric Laurentf7c50102016-09-30 15:19:43 -07001852 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1853 // primary HW module
1854 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1855 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1856 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001857 SoundTrigger::setCaptureState(false);
1858 }
1859 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001860 }
Eric Laurente552edb2014-03-10 17:42:56 -07001861 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001862 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001863}
1864
Eric Laurent4dc68062014-07-28 17:26:49 -07001865void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1866 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001867{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001868
Eric Laurente552edb2014-03-10 17:42:56 -07001869 ALOGV("releaseInput() %d", input);
1870 ssize_t index = mInputs.indexOfKey(input);
1871 if (index < 0) {
1872 ALOGW("releaseInput() releasing unknown input %d", input);
1873 return;
1874 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001875
1876 // Routing
1877 mInputRoutes.removeRoute(session);
1878
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001879 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1880 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001881
Eric Laurent599c7582015-12-07 18:05:55 -08001882 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001883 if (index < 0) {
1884 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1885 return;
1886 }
Eric Laurent599c7582015-12-07 18:05:55 -08001887
1888 if (audioSession->openCount() == 0) {
1889 ALOGW("releaseInput() invalid open count %d on session %d",
1890 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001891 return;
1892 }
Eric Laurent599c7582015-12-07 18:05:55 -08001893
1894 if (audioSession->changeOpenCount(-1) == 0) {
1895 inputDesc->removeAudioSession(session);
1896 }
1897
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001898 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001899 ALOGV("releaseInput() exit > 0");
1900 return;
1901 }
1902
Eric Laurent05b90f82014-08-27 15:32:29 -07001903 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001904 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001905 ALOGV("releaseInput() exit");
1906}
1907
Eric Laurentd4692962014-05-05 18:13:44 -07001908void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001909 bool patchRemoved = false;
1910
Eric Laurentd4692962014-05-05 18:13:44 -07001911 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001912 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001913 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001914 if (patch_index >= 0) {
1915 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001916 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001917 mAudioPatches.removeItemsAt(patch_index);
1918 patchRemoved = true;
1919 }
Eric Laurentd4692962014-05-05 18:13:44 -07001920 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1921 }
1922 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001923 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001924 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001925
1926 if (patchRemoved) {
1927 mpClientInterface->onAudioPatchListUpdate();
1928 }
Eric Laurentd4692962014-05-05 18:13:44 -07001929}
1930
Eric Laurente0720872014-03-11 09:30:41 -07001931void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001932 int indexMin,
1933 int indexMax)
1934{
1935 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001936 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001937
1938 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001939 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1940 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001941 continue;
1942 }
1943 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001944 }
Eric Laurente552edb2014-03-10 17:42:56 -07001945}
1946
Eric Laurente0720872014-03-11 09:30:41 -07001947status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001948 int index,
1949 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001950{
1951
François Gaffied1ab2bd2015-12-02 18:20:06 +01001952 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1953 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001954 return BAD_VALUE;
1955 }
1956 if (!audio_is_output_device(device)) {
1957 return BAD_VALUE;
1958 }
1959
1960 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001961 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001962
Eric Laurent1fd372e2016-04-06 14:23:53 -07001963 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001964 stream, device, index);
1965
Eric Laurent28d09f02016-03-08 10:43:05 -08001966 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001967 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1968 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001969 continue;
1970 }
1971 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1972 }
Eric Laurente552edb2014-03-10 17:42:56 -07001973
Eric Laurent1fd372e2016-04-06 14:23:53 -07001974 // update volume on all outputs and streams matching the following:
1975 // - The requested stream (or a stream matching for volume control) is active on the output
1976 // - The device (or devices) selected by the strategy corresponding to this stream includes
1977 // the requested device
1978 // - For non default requested device, currently selected device on the output is either the
1979 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001980 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1981 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001982 status_t status = NO_ERROR;
1983 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001984 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1985 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001986 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1987 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001988 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001989 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001990 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1991 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001992 continue;
1993 }
Eric Laurent794fde22016-03-11 09:50:45 -08001994 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07001995 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
1996 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
1997 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001998 continue;
1999 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002000 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002001 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002002 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002003 applyVolume = (curDevice & curStreamDevice) != 0;
2004 } else {
2005 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
2006 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07002007 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002008
Eric Laurente76f29c2016-09-14 17:17:53 -07002009 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002010 //FIXME: workaround for truncated touch sounds
2011 // delayed volume change for system stream to be removed when the problem is
2012 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002013 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002014 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2015 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002016 if (volStatus != NO_ERROR) {
2017 status = volStatus;
2018 }
2019 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002020 }
Eric Laurente552edb2014-03-10 17:42:56 -07002021 }
2022 return status;
2023}
2024
Eric Laurente0720872014-03-11 09:30:41 -07002025status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002026 int *index,
2027 audio_devices_t device)
2028{
2029 if (index == NULL) {
2030 return BAD_VALUE;
2031 }
2032 if (!audio_is_output_device(device)) {
2033 return BAD_VALUE;
2034 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002035 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002036 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002037 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002038 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2039 }
François Gaffiedfd74092015-03-19 12:10:59 +01002040 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002041
François Gaffied1ab2bd2015-12-02 18:20:06 +01002042 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002043 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2044 return NO_ERROR;
2045}
2046
Eric Laurente0720872014-03-11 09:30:41 -07002047audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002048 const SortedVector<audio_io_handle_t>& outputs)
2049{
2050 // select one output among several suitable for global effects.
2051 // The priority is as follows:
2052 // 1: An offloaded output. If the effect ends up not being offloadable,
2053 // AudioFlinger will invalidate the track and the offloaded output
2054 // will be closed causing the effect to be moved to a PCM output.
2055 // 2: A deep buffer output
2056 // 3: the first output in the list
2057
2058 if (outputs.size() == 0) {
2059 return 0;
2060 }
2061
2062 audio_io_handle_t outputOffloaded = 0;
2063 audio_io_handle_t outputDeepBuffer = 0;
2064
2065 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002066 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002067 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002068 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2069 outputOffloaded = outputs[i];
2070 }
2071 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2072 outputDeepBuffer = outputs[i];
2073 }
2074 }
2075
2076 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2077 outputOffloaded, outputDeepBuffer);
2078 if (outputOffloaded != 0) {
2079 return outputOffloaded;
2080 }
2081 if (outputDeepBuffer != 0) {
2082 return outputDeepBuffer;
2083 }
2084
2085 return outputs[0];
2086}
2087
Eric Laurente0720872014-03-11 09:30:41 -07002088audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002089{
2090 // apply simple rule where global effects are attached to the same output as MUSIC streams
2091
Eric Laurent3b73df72014-03-11 09:06:29 -07002092 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002093 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2094 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2095
2096 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2097 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2098 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2099
2100 return output;
2101}
2102
Eric Laurente0720872014-03-11 09:30:41 -07002103status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002104 audio_io_handle_t io,
2105 uint32_t strategy,
2106 int session,
2107 int id)
2108{
2109 ssize_t index = mOutputs.indexOfKey(io);
2110 if (index < 0) {
2111 index = mInputs.indexOfKey(io);
2112 if (index < 0) {
2113 ALOGW("registerEffect() unknown io %d", io);
2114 return INVALID_OPERATION;
2115 }
2116 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002117 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002118}
2119
Eric Laurentc75307b2015-03-17 15:29:32 -07002120bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2121{
Eric Laurent28d09f02016-03-08 10:43:05 -08002122 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002123 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2124 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002125 continue;
2126 }
2127 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2128 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002129 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002130}
2131
2132bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2133{
2134 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2135}
2136
Eric Laurente0720872014-03-11 09:30:41 -07002137bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002138{
2139 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002140 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002141 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002142 return true;
2143 }
2144 }
2145 return false;
2146}
2147
Eric Laurent275e8e92014-11-30 15:14:47 -08002148// Register a list of custom mixes with their attributes and format.
2149// When a mix is registered, corresponding input and output profiles are
2150// added to the remote submix hw module. The profile contains only the
2151// parameters (sampling rate, format...) specified by the mix.
2152// The corresponding input remote submix device is also connected.
2153//
2154// When a remote submix device is connected, the address is checked to select the
2155// appropriate profile and the corresponding input or output stream is opened.
2156//
2157// When capture starts, getInputForAttr() will:
2158// - 1 look for a mix matching the address passed in attribtutes tags if any
2159// - 2 if none found, getDeviceForInputSource() will:
2160// - 2.1 look for a mix matching the attributes source
2161// - 2.2 if none found, default to device selection by policy rules
2162// At this time, the corresponding output remote submix device is also connected
2163// and active playback use cases can be transferred to this mix if needed when reconnecting
2164// after AudioTracks are invalidated
2165//
2166// When playback starts, getOutputForAttr() will:
2167// - 1 look for a mix matching the address passed in attribtutes tags if any
2168// - 2 if none found, look for a mix matching the attributes usage
2169// - 3 if none found, default to device and output selection by policy rules.
2170
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002171status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002172{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002173 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2174 status_t res = NO_ERROR;
2175
2176 sp<HwModule> rSubmixModule;
2177 // examine each mix's route type
2178 for (size_t i = 0; i < mixes.size(); i++) {
2179 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2180 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2181 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002182 break;
2183 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002184 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2185 // Loop back through "remote submix"
2186 if (rSubmixModule == 0) {
2187 for (size_t j = 0; i < mHwModules.size(); j++) {
2188 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2189 && mHwModules[j]->mHandle != 0) {
2190 rSubmixModule = mHwModules[j];
2191 break;
2192 }
2193 }
2194 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002195
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002196 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002197
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002198 if (rSubmixModule == 0) {
2199 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2200 res = INVALID_OPERATION;
2201 break;
2202 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002203
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002204 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002205
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002206 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002207 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002208 res = INVALID_OPERATION;
2209 break;
2210 }
2211 audio_config_t outputConfig = mixes[i].mFormat;
2212 audio_config_t inputConfig = mixes[i].mFormat;
2213 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2214 // stereo and let audio flinger do the channel conversion if needed.
2215 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2216 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2217 rSubmixModule->addOutputProfile(address, &outputConfig,
2218 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2219 rSubmixModule->addInputProfile(address, &inputConfig,
2220 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002221
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002222 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2223 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2224 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2225 address.string(), "remote-submix");
2226 } else {
2227 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2228 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2229 address.string(), "remote-submix");
2230 }
2231 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002232 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002233 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002234 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2235 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002236
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002237 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002238 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2239 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2240 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2241 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2242 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2243 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002244 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2245 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002246 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2247 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002248 } else {
2249 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002250 }
2251 break;
2252 }
2253 }
2254
2255 if (res != NO_ERROR) {
2256 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002257 i, device, address.string());
2258 res = INVALID_OPERATION;
2259 break;
2260 } else if (!foundOutput) {
2261 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2262 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002263 res = INVALID_OPERATION;
2264 break;
2265 }
Eric Laurentc722f302014-12-10 11:21:49 -08002266 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002267 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002268 if (res != NO_ERROR) {
2269 unregisterPolicyMixes(mixes);
2270 }
2271 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002272}
2273
2274status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2275{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002276 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002277 status_t res = NO_ERROR;
2278 sp<HwModule> rSubmixModule;
2279 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002280 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002281 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002282
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002283 if (rSubmixModule == 0) {
2284 for (size_t j = 0; i < mHwModules.size(); j++) {
2285 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2286 && mHwModules[j]->mHandle != 0) {
2287 rSubmixModule = mHwModules[j];
2288 break;
2289 }
2290 }
2291 }
2292 if (rSubmixModule == 0) {
2293 res = INVALID_OPERATION;
2294 continue;
2295 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002296
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002297 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002298
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002299 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2300 res = INVALID_OPERATION;
2301 continue;
2302 }
2303
2304 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2305 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2306 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2307 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2308 address.string(), "remote-submix");
2309 }
2310 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2311 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2312 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2313 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2314 address.string(), "remote-submix");
2315 }
2316 rSubmixModule->removeOutputProfile(address);
2317 rSubmixModule->removeInputProfile(address);
2318
2319 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2320 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2321 res = INVALID_OPERATION;
2322 continue;
2323 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002324 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002325 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002326 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002327}
2328
Eric Laurente552edb2014-03-10 17:42:56 -07002329
Eric Laurente0720872014-03-11 09:30:41 -07002330status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002331{
2332 const size_t SIZE = 256;
2333 char buffer[SIZE];
2334 String8 result;
2335
2336 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2337 result.append(buffer);
2338
Eric Laurent87ffa392015-05-22 10:32:38 -07002339 snprintf(buffer, SIZE, " Primary Output: %d\n",
2340 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002341 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002342 std::string stateLiteral;
2343 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2344 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002345 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002346 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002347 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002348 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002349 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002350 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002351 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002352 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002353 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002354 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002355 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002356 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002357 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002358 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002359 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002360 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2361 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2362 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002363 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2364 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002365 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2366 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002367
François Gaffie2110e042015-03-24 08:41:51 +01002368 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002369
François Gaffie112b0af2015-11-19 16:13:25 +01002370 mAvailableOutputDevices.dump(fd, String8("Available output"));
2371 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002372 mHwModules.dump(fd);
2373 mOutputs.dump(fd);
2374 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002375 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002376 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002377 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002378
2379 return NO_ERROR;
2380}
2381
2382// This function checks for the parameters which can be offloaded.
2383// This can be enhanced depending on the capability of the DSP and policy
2384// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002385bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002386{
2387 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002388 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002389 offloadInfo.sample_rate, offloadInfo.channel_mask,
2390 offloadInfo.format,
2391 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2392 offloadInfo.has_video);
2393
Andy Hung2ddee192015-12-18 17:34:44 -08002394 if (mMasterMono) {
2395 return false; // no offloading if mono is set.
2396 }
2397
Eric Laurente552edb2014-03-10 17:42:56 -07002398 // Check if offload has been disabled
2399 char propValue[PROPERTY_VALUE_MAX];
2400 if (property_get("audio.offload.disable", propValue, "0")) {
2401 if (atoi(propValue) != 0) {
2402 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2403 return false;
2404 }
2405 }
2406
2407 // Check if stream type is music, then only allow offload as of now.
2408 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2409 {
2410 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2411 return false;
2412 }
2413
2414 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002415 const bool allowOffloadWithVideo =
2416 property_get_bool("audio.offload.video", false /* default_value */);
2417 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002418 ALOGV("isOffloadSupported: has_video == true, returning false");
2419 return false;
2420 }
2421
2422 //If duration is less than minimum value defined in property, return false
2423 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2424 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2425 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2426 return false;
2427 }
2428 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2429 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2430 return false;
2431 }
2432
2433 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2434 // creating an offloaded track and tearing it down immediately after start when audioflinger
2435 // detects there is an active non offloadable effect.
2436 // FIXME: We should check the audio session here but we do not have it in this context.
2437 // This may prevent offloading in rare situations where effects are left active by apps
2438 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002439 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002440 return false;
2441 }
2442
2443 // See if there is a profile to support this.
2444 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002445 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002446 offloadInfo.sample_rate,
2447 offloadInfo.format,
2448 offloadInfo.channel_mask,
2449 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002450 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2451 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002452}
2453
Eric Laurent6a94d692014-05-20 11:18:06 -07002454status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2455 audio_port_type_t type,
2456 unsigned int *num_ports,
2457 struct audio_port *ports,
2458 unsigned int *generation)
2459{
2460 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2461 generation == NULL) {
2462 return BAD_VALUE;
2463 }
2464 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2465 if (ports == NULL) {
2466 *num_ports = 0;
2467 }
2468
2469 size_t portsWritten = 0;
2470 size_t portsMax = *num_ports;
2471 *num_ports = 0;
2472 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002473 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2474 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002476 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2477 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2478 continue;
2479 }
2480 if (portsWritten < portsMax) {
2481 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2482 }
2483 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002484 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002485 }
2486 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002487 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2488 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2489 continue;
2490 }
2491 if (portsWritten < portsMax) {
2492 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2493 }
2494 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002495 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002496 }
2497 }
2498 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2499 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2500 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2501 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2502 }
2503 *num_ports += mInputs.size();
2504 }
2505 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002506 size_t numOutputs = 0;
2507 for (size_t i = 0; i < mOutputs.size(); i++) {
2508 if (!mOutputs[i]->isDuplicated()) {
2509 numOutputs++;
2510 if (portsWritten < portsMax) {
2511 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2512 }
2513 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002514 }
Eric Laurent84c70242014-06-23 08:46:27 -07002515 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002516 }
2517 }
2518 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002519 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002520 return NO_ERROR;
2521}
2522
2523status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2524{
2525 return NO_ERROR;
2526}
2527
Eric Laurent6a94d692014-05-20 11:18:06 -07002528status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2529 audio_patch_handle_t *handle,
2530 uid_t uid)
2531{
2532 ALOGV("createAudioPatch()");
2533
2534 if (handle == NULL || patch == NULL) {
2535 return BAD_VALUE;
2536 }
2537 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2538
Eric Laurent874c42872014-08-08 15:13:39 -07002539 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2540 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2541 return BAD_VALUE;
2542 }
2543 // only one source per audio patch supported for now
2544 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002545 return INVALID_OPERATION;
2546 }
Eric Laurent874c42872014-08-08 15:13:39 -07002547
2548 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002549 return INVALID_OPERATION;
2550 }
Eric Laurent874c42872014-08-08 15:13:39 -07002551 for (size_t i = 0; i < patch->num_sinks; i++) {
2552 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2553 return INVALID_OPERATION;
2554 }
2555 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002556
2557 sp<AudioPatch> patchDesc;
2558 ssize_t index = mAudioPatches.indexOfKey(*handle);
2559
Eric Laurent6a94d692014-05-20 11:18:06 -07002560 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2561 patch->sources[0].role,
2562 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002563#if LOG_NDEBUG == 0
2564 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002565 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002566 patch->sinks[i].role,
2567 patch->sinks[i].type);
2568 }
2569#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002570
2571 if (index >= 0) {
2572 patchDesc = mAudioPatches.valueAt(index);
2573 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2574 mUidCached, patchDesc->mUid, uid);
2575 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2576 return INVALID_OPERATION;
2577 }
2578 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002579 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002580 }
2581
2582 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002583 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002584 if (outputDesc == NULL) {
2585 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2586 return BAD_VALUE;
2587 }
Eric Laurent84c70242014-06-23 08:46:27 -07002588 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2589 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002590 if (patchDesc != 0) {
2591 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2592 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2593 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2594 return BAD_VALUE;
2595 }
2596 }
Eric Laurent874c42872014-08-08 15:13:39 -07002597 DeviceVector devices;
2598 for (size_t i = 0; i < patch->num_sinks; i++) {
2599 // Only support mix to devices connection
2600 // TODO add support for mix to mix connection
2601 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2602 ALOGV("createAudioPatch() source mix but sink is not a device");
2603 return INVALID_OPERATION;
2604 }
2605 sp<DeviceDescriptor> devDesc =
2606 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2607 if (devDesc == 0) {
2608 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2609 return BAD_VALUE;
2610 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002611
François Gaffie53615e22015-03-19 09:24:12 +01002612 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002613 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002614 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002615 NULL, // updatedSamplingRate
2616 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002617 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002618 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002619 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002620 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002621 ALOGV("createAudioPatch() profile not supported for device %08x",
2622 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002623 return INVALID_OPERATION;
2624 }
2625 devices.add(devDesc);
2626 }
2627 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002628 return INVALID_OPERATION;
2629 }
Eric Laurent874c42872014-08-08 15:13:39 -07002630
Eric Laurent6a94d692014-05-20 11:18:06 -07002631 // TODO: reconfigure output format and channels here
2632 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002633 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002634 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002635 index = mAudioPatches.indexOfKey(*handle);
2636 if (index >= 0) {
2637 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2638 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2639 }
2640 patchDesc = mAudioPatches.valueAt(index);
2641 patchDesc->mUid = uid;
2642 ALOGV("createAudioPatch() success");
2643 } else {
2644 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2645 return INVALID_OPERATION;
2646 }
2647 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2648 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2649 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002650 // only one sink supported when connecting an input device to a mix
2651 if (patch->num_sinks > 1) {
2652 return INVALID_OPERATION;
2653 }
François Gaffie53615e22015-03-19 09:24:12 +01002654 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002655 if (inputDesc == NULL) {
2656 return BAD_VALUE;
2657 }
2658 if (patchDesc != 0) {
2659 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2660 return BAD_VALUE;
2661 }
2662 }
2663 sp<DeviceDescriptor> devDesc =
2664 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2665 if (devDesc == 0) {
2666 return BAD_VALUE;
2667 }
2668
François Gaffie53615e22015-03-19 09:24:12 +01002669 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002670 devDesc->mAddress,
2671 patch->sinks[0].sample_rate,
2672 NULL, /*updatedSampleRate*/
2673 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002674 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002675 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002676 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002677 // FIXME for the parameter type,
2678 // and the NONE
2679 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002680 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002681 return INVALID_OPERATION;
2682 }
2683 // TODO: reconfigure output format and channels here
2684 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002685 devDesc->type(), inputDesc->mIoHandle);
2686 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002687 index = mAudioPatches.indexOfKey(*handle);
2688 if (index >= 0) {
2689 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2690 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2691 }
2692 patchDesc = mAudioPatches.valueAt(index);
2693 patchDesc->mUid = uid;
2694 ALOGV("createAudioPatch() success");
2695 } else {
2696 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2697 return INVALID_OPERATION;
2698 }
2699 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2700 // device to device connection
2701 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002702 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002703 return BAD_VALUE;
2704 }
2705 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002706 sp<DeviceDescriptor> srcDeviceDesc =
2707 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002708 if (srcDeviceDesc == 0) {
2709 return BAD_VALUE;
2710 }
Eric Laurent874c42872014-08-08 15:13:39 -07002711
Eric Laurent6a94d692014-05-20 11:18:06 -07002712 //update source and sink with our own data as the data passed in the patch may
2713 // be incomplete.
2714 struct audio_patch newPatch = *patch;
2715 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002716
Eric Laurent874c42872014-08-08 15:13:39 -07002717 for (size_t i = 0; i < patch->num_sinks; i++) {
2718 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2719 ALOGV("createAudioPatch() source device but one sink is not a device");
2720 return INVALID_OPERATION;
2721 }
2722
2723 sp<DeviceDescriptor> sinkDeviceDesc =
2724 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2725 if (sinkDeviceDesc == 0) {
2726 return BAD_VALUE;
2727 }
2728 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2729
Eric Laurent3bcf8592015-04-03 12:13:24 -07002730 // create a software bridge in PatchPanel if:
2731 // - source and sink devices are on differnt HW modules OR
2732 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002733 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002734 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002735 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002736 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002737 return INVALID_OPERATION;
2738 }
Eric Laurent874c42872014-08-08 15:13:39 -07002739 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002740 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002741 // if the sink device is reachable via an opened output stream, request to go via
2742 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002743 audio_io_handle_t output = selectOutput(outputs,
2744 AUDIO_OUTPUT_FLAG_NONE,
2745 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002746 if (output != AUDIO_IO_HANDLE_NONE) {
2747 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2748 if (outputDesc->isDuplicated()) {
2749 return INVALID_OPERATION;
2750 }
2751 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002752 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002753 newPatch.num_sources = 2;
2754 }
Eric Laurent83b88082014-06-20 18:31:16 -07002755 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 }
2757 // TODO: check from routing capabilities in config file and other conflicting patches
2758
2759 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2760 if (index >= 0) {
2761 afPatchHandle = patchDesc->mAfPatchHandle;
2762 }
2763
2764 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2765 &afPatchHandle,
2766 0);
2767 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2768 status, afPatchHandle);
2769 if (status == NO_ERROR) {
2770 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002771 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002772 addAudioPatch(patchDesc->mHandle, patchDesc);
2773 } else {
2774 patchDesc->mPatch = newPatch;
2775 }
2776 patchDesc->mAfPatchHandle = afPatchHandle;
2777 *handle = patchDesc->mHandle;
2778 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002779 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002780 } else {
2781 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2782 status);
2783 return INVALID_OPERATION;
2784 }
2785 } else {
2786 return BAD_VALUE;
2787 }
2788 } else {
2789 return BAD_VALUE;
2790 }
2791 return NO_ERROR;
2792}
2793
2794status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2795 uid_t uid)
2796{
2797 ALOGV("releaseAudioPatch() patch %d", handle);
2798
2799 ssize_t index = mAudioPatches.indexOfKey(handle);
2800
2801 if (index < 0) {
2802 return BAD_VALUE;
2803 }
2804 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2805 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2806 mUidCached, patchDesc->mUid, uid);
2807 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2808 return INVALID_OPERATION;
2809 }
2810
2811 struct audio_patch *patch = &patchDesc->mPatch;
2812 patchDesc->mUid = mUidCached;
2813 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002814 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002815 if (outputDesc == NULL) {
2816 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2817 return BAD_VALUE;
2818 }
2819
Eric Laurentc75307b2015-03-17 15:29:32 -07002820 setOutputDevice(outputDesc,
2821 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002822 true,
2823 0,
2824 NULL);
2825 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2826 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002827 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 if (inputDesc == NULL) {
2829 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2830 return BAD_VALUE;
2831 }
2832 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002833 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 true,
2835 NULL);
2836 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002837 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2838 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2839 status, patchDesc->mAfPatchHandle);
2840 removeAudioPatch(patchDesc->mHandle);
2841 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002842 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 } else {
2844 return BAD_VALUE;
2845 }
2846 } else {
2847 return BAD_VALUE;
2848 }
2849 return NO_ERROR;
2850}
2851
2852status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2853 struct audio_patch *patches,
2854 unsigned int *generation)
2855{
François Gaffie53615e22015-03-19 09:24:12 +01002856 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002857 return BAD_VALUE;
2858 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002859 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002860 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002861}
2862
Eric Laurente1715a42014-05-20 11:30:42 -07002863status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002864{
Eric Laurente1715a42014-05-20 11:30:42 -07002865 ALOGV("setAudioPortConfig()");
2866
2867 if (config == NULL) {
2868 return BAD_VALUE;
2869 }
2870 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2871 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002872 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2873 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002874 }
2875
Eric Laurenta121f902014-06-03 13:32:54 -07002876 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002877 if (config->type == AUDIO_PORT_TYPE_MIX) {
2878 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002879 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002880 if (outputDesc == NULL) {
2881 return BAD_VALUE;
2882 }
Eric Laurent84c70242014-06-23 08:46:27 -07002883 ALOG_ASSERT(!outputDesc->isDuplicated(),
2884 "setAudioPortConfig() called on duplicated output %d",
2885 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002886 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002887 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002888 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002889 if (inputDesc == NULL) {
2890 return BAD_VALUE;
2891 }
Eric Laurenta121f902014-06-03 13:32:54 -07002892 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002893 } else {
2894 return BAD_VALUE;
2895 }
2896 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2897 sp<DeviceDescriptor> deviceDesc;
2898 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2899 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2900 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2901 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2902 } else {
2903 return BAD_VALUE;
2904 }
2905 if (deviceDesc == NULL) {
2906 return BAD_VALUE;
2907 }
Eric Laurenta121f902014-06-03 13:32:54 -07002908 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002909 } else {
2910 return BAD_VALUE;
2911 }
2912
Eric Laurenta121f902014-06-03 13:32:54 -07002913 struct audio_port_config backupConfig;
2914 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2915 if (status == NO_ERROR) {
2916 struct audio_port_config newConfig;
2917 audioPortConfig->toAudioPortConfig(&newConfig, config);
2918 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002919 }
Eric Laurenta121f902014-06-03 13:32:54 -07002920 if (status != NO_ERROR) {
2921 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002922 }
Eric Laurente1715a42014-05-20 11:30:42 -07002923
2924 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002925}
2926
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002927void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2928{
Eric Laurentd60560a2015-04-10 11:31:20 -07002929 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002930 clearAudioPatches(uid);
2931 clearSessionRoutes(uid);
2932}
2933
Eric Laurent6a94d692014-05-20 11:18:06 -07002934void AudioPolicyManager::clearAudioPatches(uid_t uid)
2935{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002936 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002937 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2938 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002939 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002940 }
2941 }
2942}
2943
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002944void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2945 audio_io_handle_t ouptutToSkip)
2946{
2947 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2948 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2949 for (size_t j = 0; j < mOutputs.size(); j++) {
2950 if (mOutputs.keyAt(j) == ouptutToSkip) {
2951 continue;
2952 }
2953 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2954 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2955 continue;
2956 }
2957 // If the default device for this strategy is on another output mix,
2958 // invalidate all tracks in this strategy to force re connection.
2959 // Otherwise select new device on the output mix.
2960 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002961 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002962 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2963 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2964 }
2965 }
2966 } else {
2967 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2968 setOutputDevice(outputDesc, newDevice, false);
2969 }
2970 }
2971}
2972
2973void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2974{
2975 // remove output routes associated with this uid
2976 SortedVector<routing_strategy> affectedStrategies;
2977 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2978 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2979 if (route->mUid == uid) {
2980 mOutputRoutes.removeItemsAt(i);
2981 if (route->mDeviceDescriptor != 0) {
2982 affectedStrategies.add(getStrategy(route->mStreamType));
2983 }
2984 }
2985 }
2986 // reroute outputs if necessary
2987 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2988 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2989 }
2990
2991 // remove input routes associated with this uid
2992 SortedVector<audio_source_t> affectedSources;
2993 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2994 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2995 if (route->mUid == uid) {
2996 mInputRoutes.removeItemsAt(i);
2997 if (route->mDeviceDescriptor != 0) {
2998 affectedSources.add(route->mSource);
2999 }
3000 }
3001 }
3002 // reroute inputs if necessary
3003 SortedVector<audio_io_handle_t> inputsToClose;
3004 for (size_t i = 0; i < mInputs.size(); i++) {
3005 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003006 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003007 inputsToClose.add(inputDesc->mIoHandle);
3008 }
3009 }
3010 for (size_t i = 0; i < inputsToClose.size(); i++) {
3011 closeInput(inputsToClose[i]);
3012 }
3013}
3014
Eric Laurentd60560a2015-04-10 11:31:20 -07003015void AudioPolicyManager::clearAudioSources(uid_t uid)
3016{
3017 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3018 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3019 if (sourceDesc->mUid == uid) {
3020 stopAudioSource(mAudioSources.keyAt(i));
3021 }
3022 }
3023}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003024
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003025status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3026 audio_io_handle_t *ioHandle,
3027 audio_devices_t *device)
3028{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003029 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3030 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003031 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003032
François Gaffiedf372692015-03-19 10:43:27 +01003033 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003034}
3035
Eric Laurentd60560a2015-04-10 11:31:20 -07003036status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3037 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003038 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003039 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003040{
Eric Laurentd60560a2015-04-10 11:31:20 -07003041 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3042 if (source == NULL || attributes == NULL || handle == NULL) {
3043 return BAD_VALUE;
3044 }
3045
Glenn Kasten559d4392016-03-29 13:42:57 -07003046 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003047
3048 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3049 source->type != AUDIO_PORT_TYPE_DEVICE) {
3050 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3051 return INVALID_OPERATION;
3052 }
3053
3054 sp<DeviceDescriptor> srcDeviceDesc =
3055 mAvailableInputDevices.getDevice(source->ext.device.type,
3056 String8(source->ext.device.address));
3057 if (srcDeviceDesc == 0) {
3058 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3059 return BAD_VALUE;
3060 }
3061 sp<AudioSourceDescriptor> sourceDesc =
3062 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3063
3064 struct audio_patch dummyPatch;
3065 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3066 sourceDesc->mPatchDesc = patchDesc;
3067
3068 status_t status = connectAudioSource(sourceDesc);
3069 if (status == NO_ERROR) {
3070 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3071 *handle = sourceDesc->getHandle();
3072 }
3073 return status;
3074}
3075
3076status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3077{
3078 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3079
3080 // make sure we only have one patch per source.
3081 disconnectAudioSource(sourceDesc);
3082
3083 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003084 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003085 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3086
3087 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3088 sp<DeviceDescriptor> sinkDeviceDesc =
3089 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3090
3091 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3092 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3093
3094 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3095 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003096 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003097 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3098 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3099 // create patch between src device and output device
3100 // create Hwoutput and add to mHwOutputs
3101 } else {
3102 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3103 audio_io_handle_t output =
3104 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3105 if (output == AUDIO_IO_HANDLE_NONE) {
3106 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3107 return INVALID_OPERATION;
3108 }
3109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3110 if (outputDesc->isDuplicated()) {
3111 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3112 return INVALID_OPERATION;
3113 }
3114 // create a special patch with no sink and two sources:
3115 // - the second source indicates to PatchPanel through which output mix this patch should
3116 // be connected as well as the stream type for volume control
3117 // - the sink is defined by whatever output device is currently selected for the output
3118 // though which this patch is routed.
3119 patch->num_sinks = 0;
3120 patch->num_sources = 2;
3121 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3122 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3123 patch->sources[1].ext.mix.usecase.stream = stream;
3124 status_t status = mpClientInterface->createAudioPatch(patch,
3125 &afPatchHandle,
3126 0);
3127 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3128 status, afPatchHandle);
3129 if (status != NO_ERROR) {
3130 ALOGW("%s patch panel could not connect device patch, error %d",
3131 __FUNCTION__, status);
3132 return INVALID_OPERATION;
3133 }
3134 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003135 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003136
3137 if (status != NO_ERROR) {
3138 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3139 return status;
3140 }
3141 sourceDesc->mSwOutput = outputDesc;
3142 if (delayMs != 0) {
3143 usleep(delayMs * 1000);
3144 }
3145 }
3146
3147 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3148 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3149
3150 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003151}
3152
Glenn Kasten559d4392016-03-29 13:42:57 -07003153status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003154{
Eric Laurentd60560a2015-04-10 11:31:20 -07003155 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3156 ALOGV("%s handle %d", __FUNCTION__, handle);
3157 if (sourceDesc == 0) {
3158 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3159 return BAD_VALUE;
3160 }
3161 status_t status = disconnectAudioSource(sourceDesc);
3162
3163 mAudioSources.removeItem(handle);
3164 return status;
3165}
3166
Andy Hung2ddee192015-12-18 17:34:44 -08003167status_t AudioPolicyManager::setMasterMono(bool mono)
3168{
3169 if (mMasterMono == mono) {
3170 return NO_ERROR;
3171 }
3172 mMasterMono = mono;
3173 // if enabling mono we close all offloaded devices, which will invalidate the
3174 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3175 // for recreating the new AudioTrack as non-offloaded PCM.
3176 //
3177 // If disabling mono, we leave all tracks as is: we don't know which clients
3178 // and tracks are able to be recreated as offloaded. The next "song" should
3179 // play back offloaded.
3180 if (mMasterMono) {
3181 Vector<audio_io_handle_t> offloaded;
3182 for (size_t i = 0; i < mOutputs.size(); ++i) {
3183 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3184 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3185 offloaded.push(desc->mIoHandle);
3186 }
3187 }
3188 for (size_t i = 0; i < offloaded.size(); ++i) {
3189 closeOutput(offloaded[i]);
3190 }
3191 }
3192 // update master mono for all remaining outputs
3193 for (size_t i = 0; i < mOutputs.size(); ++i) {
3194 updateMono(mOutputs.keyAt(i));
3195 }
3196 return NO_ERROR;
3197}
3198
3199status_t AudioPolicyManager::getMasterMono(bool *mono)
3200{
3201 *mono = mMasterMono;
3202 return NO_ERROR;
3203}
3204
Eric Laurentd60560a2015-04-10 11:31:20 -07003205status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3206{
3207 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3208
3209 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3210 if (patchDesc == 0) {
3211 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3212 sourceDesc->mPatchDesc->mHandle);
3213 return BAD_VALUE;
3214 }
3215 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3216
Eric Laurent28d09f02016-03-08 10:43:05 -08003217 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003218 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3219 if (swOutputDesc != 0) {
3220 stopSource(swOutputDesc, stream, false);
3221 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3222 } else {
3223 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3224 if (hwOutputDesc != 0) {
3225 // release patch between src device and output device
3226 // close Hwoutput and remove from mHwOutputs
3227 } else {
3228 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3229 }
3230 }
3231 return NO_ERROR;
3232}
3233
3234sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3235 audio_io_handle_t output, routing_strategy strategy)
3236{
3237 sp<AudioSourceDescriptor> source;
3238 for (size_t i = 0; i < mAudioSources.size(); i++) {
3239 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3240 routing_strategy sourceStrategy =
3241 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3242 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3243 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3244 source = sourceDesc;
3245 break;
3246 }
3247 }
3248 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003249}
3250
Eric Laurente552edb2014-03-10 17:42:56 -07003251// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003252// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003253// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003254uint32_t AudioPolicyManager::nextAudioPortGeneration()
3255{
3256 return android_atomic_inc(&mAudioPortGeneration);
3257}
3258
Eric Laurente0720872014-03-11 09:30:41 -07003259AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003260 :
3261#ifdef AUDIO_POLICY_TEST
3262 Thread(false),
3263#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003264 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003265 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003266 mAudioPortGeneration(1),
3267 mBeaconMuteRefCount(0),
3268 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003269 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003270 mTtsOutputAvailable(false),
3271 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003272{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003273 mUidCached = getuid();
3274 mpClientInterface = clientInterface;
3275
3276 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3277 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3278 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3279 bool speakerDrcEnabled = false;
3280
3281#ifdef USE_XML_AUDIO_POLICY_CONF
3282 mVolumeCurves = new VolumeCurvesCollection();
3283 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3284 mDefaultOutputDevice, speakerDrcEnabled,
3285 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3286 PolicySerializer serializer;
3287 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3288#else
3289 mVolumeCurves = new StreamDescriptorCollection();
3290 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3291 mDefaultOutputDevice, speakerDrcEnabled);
3292 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3293 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3294#endif
3295 ALOGE("could not load audio policy configuration file, setting defaults");
3296 config.setDefault();
3297 }
3298 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3299 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3300
3301 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003302 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3303 if (!engineInstance) {
3304 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3305 return;
3306 }
3307 // Retrieve the Policy Manager Interface
3308 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3309 if (mEngine == NULL) {
3310 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3311 return;
3312 }
3313 mEngine->setObserver(this);
3314 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003315 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003316 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3317
Eric Laurent3a4311c2014-03-17 12:00:47 -07003318 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003319 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003320 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3321 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003322 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003323 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003324 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003325 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003326 continue;
3327 }
3328 // open all output streams needed to access attached devices
3329 // except for direct output streams that are only opened when they are actually
3330 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003331 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003332 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3333 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003334 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003335
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003336 if (!outProfile->hasSupportedDevices()) {
3337 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003338 continue;
3339 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003340 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003341 mTtsOutputAvailable = true;
3342 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003343
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003344 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003345 continue;
3346 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003347 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003348 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3349 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003350 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003351 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003352 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003353 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003354 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003355 if ((profileType & outputDeviceTypes) == 0) {
3356 continue;
3357 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003358 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3359 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003360 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3361 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3362 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3363 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003364
3365 outputDesc->mDevice = profileType;
3366 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3367 config.sample_rate = outputDesc->mSamplingRate;
3368 config.channel_mask = outputDesc->mChannelMask;
3369 config.format = outputDesc->mFormat;
3370 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003371 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003372 &output,
3373 &config,
3374 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003375 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003376 &outputDesc->mLatency,
3377 outputDesc->mFlags);
3378
3379 if (status != NO_ERROR) {
3380 ALOGW("Cannot open output stream for device %08x on hw module %s",
3381 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003382 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003383 } else {
3384 outputDesc->mSamplingRate = config.sample_rate;
3385 outputDesc->mChannelMask = config.channel_mask;
3386 outputDesc->mFormat = config.format;
3387
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003388 for (size_t k = 0; k < supportedDevices.size(); k++) {
3389 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003390 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003391 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3392 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003393 }
3394 }
3395 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003396 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003397 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003398 }
3399 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003400 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003401 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003402 true,
3403 0,
3404 NULL,
3405 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003406 }
Eric Laurente552edb2014-03-10 17:42:56 -07003407 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003408 // open input streams needed to access attached devices to validate
3409 // mAvailableInputDevices list
3410 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3411 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003412 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003413
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003414 if (!inProfile->hasSupportedDevices()) {
3415 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003416 continue;
3417 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003418 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003419 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003420 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3421
Eric Laurentd78f1532014-09-16 16:38:20 -07003422 if ((profileType & inputDeviceTypes) == 0) {
3423 continue;
3424 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003425 sp<AudioInputDescriptor> inputDesc =
3426 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003427
Eric Laurentd78f1532014-09-16 16:38:20 -07003428 inputDesc->mDevice = profileType;
3429
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003430 // find the address
3431 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3432 // the inputs vector must be of size 1, but we don't want to crash here
3433 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3434 : String8("");
3435 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3436 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3437
Eric Laurentd78f1532014-09-16 16:38:20 -07003438 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3439 config.sample_rate = inputDesc->mSamplingRate;
3440 config.channel_mask = inputDesc->mChannelMask;
3441 config.format = inputDesc->mFormat;
3442 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003443 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003444 &input,
3445 &config,
3446 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003447 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003448 AUDIO_SOURCE_MIC,
3449 AUDIO_INPUT_FLAG_NONE);
3450
3451 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003452 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3453 for (size_t k = 0; k < supportedDevices.size(); k++) {
3454 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003455 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003456 if (index >= 0) {
3457 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3458 if (!devDesc->isAttached()) {
3459 devDesc->attach(mHwModules[i]);
3460 devDesc->importAudioPort(inProfile);
3461 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003462 }
3463 }
3464 mpClientInterface->closeInput(input);
3465 } else {
3466 ALOGW("Cannot open input stream for device %08x on hw module %s",
3467 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003468 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003469 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003470 }
3471 }
3472 // make sure all attached devices have been allocated a unique ID
3473 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003474 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003475 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003476 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3477 continue;
3478 }
François Gaffie2110e042015-03-24 08:41:51 +01003479 // The device is now validated and can be appended to the available devices of the engine
3480 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3481 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003482 i++;
3483 }
3484 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003485 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003486 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003487 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3488 continue;
3489 }
François Gaffie2110e042015-03-24 08:41:51 +01003490 // The device is now validated and can be appended to the available devices of the engine
3491 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3492 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003493 i++;
3494 }
3495 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003496 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003497 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003498 }
Eric Laurente552edb2014-03-10 17:42:56 -07003499
3500 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3501
3502 updateDevicesAndOutputs();
3503
3504#ifdef AUDIO_POLICY_TEST
3505 if (mPrimaryOutput != 0) {
3506 AudioParameter outputCmd = AudioParameter();
3507 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003508 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003509
3510 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3511 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003512 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3513 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003514 mTestLatencyMs = 0;
3515 mCurOutput = 0;
3516 mDirectOutput = false;
3517 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3518 mTestOutputs[i] = 0;
3519 }
3520
3521 const size_t SIZE = 256;
3522 char buffer[SIZE];
3523 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3524 run(buffer, ANDROID_PRIORITY_AUDIO);
3525 }
3526#endif //AUDIO_POLICY_TEST
3527}
3528
Eric Laurente0720872014-03-11 09:30:41 -07003529AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003530{
3531#ifdef AUDIO_POLICY_TEST
3532 exit();
3533#endif //AUDIO_POLICY_TEST
3534 for (size_t i = 0; i < mOutputs.size(); i++) {
3535 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003536 }
3537 for (size_t i = 0; i < mInputs.size(); i++) {
3538 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003539 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003540 mAvailableOutputDevices.clear();
3541 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003542 mOutputs.clear();
3543 mInputs.clear();
3544 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003545}
3546
Eric Laurente0720872014-03-11 09:30:41 -07003547status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003548{
Eric Laurent87ffa392015-05-22 10:32:38 -07003549 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003550}
3551
3552#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003553bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003554{
3555 ALOGV("entering threadLoop()");
3556 while (!exitPending())
3557 {
3558 String8 command;
3559 int valueInt;
3560 String8 value;
3561
3562 Mutex::Autolock _l(mLock);
3563 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3564
3565 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3566 AudioParameter param = AudioParameter(command);
3567
3568 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3569 valueInt != 0) {
3570 ALOGV("Test command %s received", command.string());
3571 String8 target;
3572 if (param.get(String8("target"), target) != NO_ERROR) {
3573 target = "Manager";
3574 }
3575 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3576 param.remove(String8("test_cmd_policy_output"));
3577 mCurOutput = valueInt;
3578 }
3579 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3580 param.remove(String8("test_cmd_policy_direct"));
3581 if (value == "false") {
3582 mDirectOutput = false;
3583 } else if (value == "true") {
3584 mDirectOutput = true;
3585 }
3586 }
3587 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3588 param.remove(String8("test_cmd_policy_input"));
3589 mTestInput = valueInt;
3590 }
3591
3592 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3593 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003594 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003595 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003596 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003597 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003598 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003599 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003600 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003601 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003602 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003603 if (target == "Manager") {
3604 mTestFormat = format;
3605 } else if (mTestOutputs[mCurOutput] != 0) {
3606 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003607 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003608 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3609 }
3610 }
3611 }
3612 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3613 param.remove(String8("test_cmd_policy_channels"));
3614 int channels = 0;
3615
3616 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003617 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003618 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003619 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003620 }
3621 if (channels != 0) {
3622 if (target == "Manager") {
3623 mTestChannels = channels;
3624 } else if (mTestOutputs[mCurOutput] != 0) {
3625 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003626 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003627 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3628 }
3629 }
3630 }
3631 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3632 param.remove(String8("test_cmd_policy_sampleRate"));
3633 if (valueInt >= 0 && valueInt <= 96000) {
3634 int samplingRate = valueInt;
3635 if (target == "Manager") {
3636 mTestSamplingRate = samplingRate;
3637 } else if (mTestOutputs[mCurOutput] != 0) {
3638 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003639 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003640 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3641 }
3642 }
3643 }
3644
3645 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3646 param.remove(String8("test_cmd_policy_reopen"));
3647
Eric Laurentc75307b2015-03-17 15:29:32 -07003648 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003649
Eric Laurentc75307b2015-03-17 15:29:32 -07003650 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003651
Eric Laurentc75307b2015-03-17 15:29:32 -07003652 removeOutput(mPrimaryOutput->mIoHandle);
3653 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3654 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003655 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003656 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3657 config.sample_rate = outputDesc->mSamplingRate;
3658 config.channel_mask = outputDesc->mChannelMask;
3659 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003660 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003661 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003662 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003663 &config,
3664 &outputDesc->mDevice,
3665 String8(""),
3666 &outputDesc->mLatency,
3667 outputDesc->mFlags);
3668 if (status != NO_ERROR) {
3669 ALOGE("Failed to reopen hardware output stream, "
3670 "samplingRate: %d, format %d, channels %d",
3671 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003672 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003673 outputDesc->mSamplingRate = config.sample_rate;
3674 outputDesc->mChannelMask = config.channel_mask;
3675 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003676 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003677 AudioParameter outputCmd = AudioParameter();
3678 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003679 mpClientInterface->setParameters(handle, outputCmd.toString());
3680 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003681 }
3682 }
3683
3684
3685 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3686 }
3687 }
3688 return false;
3689}
3690
Eric Laurente0720872014-03-11 09:30:41 -07003691void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003692{
3693 {
3694 AutoMutex _l(mLock);
3695 requestExit();
3696 mWaitWorkCV.signal();
3697 }
3698 requestExitAndWait();
3699}
3700
Eric Laurente0720872014-03-11 09:30:41 -07003701int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003702{
3703 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3704 if (output == mTestOutputs[i]) return i;
3705 }
3706 return 0;
3707}
3708#endif //AUDIO_POLICY_TEST
3709
3710// ---
3711
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003712void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003713{
François Gaffie98cc1912015-03-18 17:52:40 +01003714 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003715 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003716 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003717 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003718}
3719
François Gaffie53615e22015-03-19 09:24:12 +01003720void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3721{
3722 mOutputs.removeItem(output);
3723}
3724
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003725void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003726{
François Gaffie98cc1912015-03-18 17:52:40 +01003727 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003728 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003729 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003730}
Eric Laurente552edb2014-03-10 17:42:56 -07003731
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003732void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003733 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003734 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003735 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003736 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003737 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003738 if (devDesc != 0) {
3739 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3740 desc->mIoHandle, address.string());
3741 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003742 }
3743}
3744
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003745status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003746 audio_policy_dev_state_t state,
3747 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003748 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003749{
François Gaffie53615e22015-03-19 09:24:12 +01003750 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003751 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003752
3753 if (audio_device_is_digital(device)) {
3754 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003755 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003756 }
Eric Laurente552edb2014-03-10 17:42:56 -07003757
Eric Laurent3b73df72014-03-11 09:06:29 -07003758 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003759 // first list already open outputs that can be routed to this device
3760 for (size_t i = 0; i < mOutputs.size(); i++) {
3761 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003762 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003763 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003764 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3765 outputs.add(mOutputs.keyAt(i));
3766 } else {
3767 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003768 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003769 }
Eric Laurente552edb2014-03-10 17:42:56 -07003770 }
3771 }
3772 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003773 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003774 for (size_t i = 0; i < mHwModules.size(); i++)
3775 {
3776 if (mHwModules[i]->mHandle == 0) {
3777 continue;
3778 }
3779 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3780 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003781 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003782 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003783 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003784 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003785 profiles.add(profile);
3786 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3787 }
Eric Laurente552edb2014-03-10 17:42:56 -07003788 }
3789 }
3790 }
3791
Eric Laurent7b279bb2015-12-14 10:18:23 -08003792 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003793
Eric Laurente552edb2014-03-10 17:42:56 -07003794 if (profiles.isEmpty() && outputs.isEmpty()) {
3795 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3796 return BAD_VALUE;
3797 }
3798
3799 // open outputs for matching profiles if needed. Direct outputs are also opened to
3800 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3801 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003802 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003803
3804 // nothing to do if one output is already opened for this profile
3805 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003806 for (j = 0; j < outputs.size(); j++) {
3807 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003808 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003809 // matching profile: save the sample rates, format and channel masks supported
3810 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003811 if (audio_device_is_digital(device)) {
3812 devDesc->importAudioPort(profile);
3813 }
Eric Laurente552edb2014-03-10 17:42:56 -07003814 break;
3815 }
3816 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003817 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003818 continue;
3819 }
3820
Eric Laurent83b88082014-06-20 18:31:16 -07003821 ALOGV("opening output for device %08x with params %s profile %p",
3822 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003823 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003824 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003825 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3826 config.sample_rate = desc->mSamplingRate;
3827 config.channel_mask = desc->mChannelMask;
3828 config.format = desc->mFormat;
3829 config.offload_info.sample_rate = desc->mSamplingRate;
3830 config.offload_info.channel_mask = desc->mChannelMask;
3831 config.offload_info.format = desc->mFormat;
3832 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003833 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003834 &output,
3835 &config,
3836 &desc->mDevice,
3837 address,
3838 &desc->mLatency,
3839 desc->mFlags);
3840 if (status == NO_ERROR) {
3841 desc->mSamplingRate = config.sample_rate;
3842 desc->mChannelMask = config.channel_mask;
3843 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003844
Eric Laurentd4692962014-05-05 18:13:44 -07003845 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003846 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003847 char *param = audio_device_address_to_parameter(device, address);
3848 mpClientInterface->setParameters(output, String8(param));
3849 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003850 }
Phil Burk00eeb322016-03-31 12:41:00 -07003851 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003852 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003853 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003854 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003855 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003856 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003857 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003858 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003859 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003860 config.offload_info.sample_rate = config.sample_rate;
3861 config.offload_info.channel_mask = config.channel_mask;
3862 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003863 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003864 &output,
3865 &config,
3866 &desc->mDevice,
3867 address,
3868 &desc->mLatency,
3869 desc->mFlags);
3870 if (status == NO_ERROR) {
3871 desc->mSamplingRate = config.sample_rate;
3872 desc->mChannelMask = config.channel_mask;
3873 desc->mFormat = config.format;
3874 } else {
3875 output = AUDIO_IO_HANDLE_NONE;
3876 }
Eric Laurentd4692962014-05-05 18:13:44 -07003877 }
3878
Eric Laurentcf2c0212014-07-25 16:20:43 -07003879 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003880 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003881 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003882 sp<AudioPolicyMix> policyMix;
3883 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003884 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3885 address.string());
3886 }
François Gaffie036e1e92015-03-19 10:16:24 +01003887 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003888 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003889
Eric Laurent87ffa392015-05-22 10:32:38 -07003890 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3891 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003892 // no duplicated output for direct outputs and
3893 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003894 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003895
Eric Laurentd4692962014-05-05 18:13:44 -07003896 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003897 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003898
Eric Laurentd4692962014-05-05 18:13:44 -07003899 //TODO: configure audio effect output stage here
3900
3901 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003902 duplicatedOutput =
3903 mpClientInterface->openDuplicateOutput(output,
3904 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003905 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003906 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003907 sp<SwAudioOutputDescriptor> dupOutputDesc =
3908 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3909 dupOutputDesc->mOutput1 = mPrimaryOutput;
3910 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003911 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3912 dupOutputDesc->mFormat = desc->mFormat;
3913 dupOutputDesc->mChannelMask = desc->mChannelMask;
3914 dupOutputDesc->mLatency = desc->mLatency;
3915 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003916 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003917 } else {
3918 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003919 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003920 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003921 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003922 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003923 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003924 }
Eric Laurente552edb2014-03-10 17:42:56 -07003925 }
3926 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003927 } else {
3928 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003929 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003930 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003931 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003932 profiles.removeAt(profile_index);
3933 profile_index--;
3934 } else {
3935 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003936 // Load digital format info only for digital devices
3937 if (audio_device_is_digital(device)) {
3938 devDesc->importAudioPort(profile);
3939 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003940
François Gaffie53615e22015-03-19 09:24:12 +01003941 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003942 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3943 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003944 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003945 NULL/*patch handle*/, address.string());
3946 }
Eric Laurente552edb2014-03-10 17:42:56 -07003947 ALOGV("checkOutputsForDevice(): adding output %d", output);
3948 }
3949 }
3950
3951 if (profiles.isEmpty()) {
3952 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3953 return BAD_VALUE;
3954 }
Eric Laurentd4692962014-05-05 18:13:44 -07003955 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003956 // check if one opened output is not needed any more after disconnecting one device
3957 for (size_t i = 0; i < mOutputs.size(); i++) {
3958 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003959 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003960 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003961 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003962 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003963 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003964 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003965 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3966 mOutputs.keyAt(i));
3967 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003968 }
Eric Laurente552edb2014-03-10 17:42:56 -07003969 }
3970 }
Eric Laurentd4692962014-05-05 18:13:44 -07003971 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003972 for (size_t i = 0; i < mHwModules.size(); i++)
3973 {
3974 if (mHwModules[i]->mHandle == 0) {
3975 continue;
3976 }
3977 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3978 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003979 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003980 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003981 ALOGV("checkOutputsForDevice(): "
3982 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003983 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003984 }
3985 }
3986 }
3987 }
3988 return NO_ERROR;
3989}
3990
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003991status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003992 audio_policy_dev_state_t state,
3993 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003994 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003995{
Paul McLean9080a4c2015-06-18 08:24:02 -07003996 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003997 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003998
3999 if (audio_device_is_digital(device)) {
4000 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004001 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004002 }
4003
Eric Laurentd4692962014-05-05 18:13:44 -07004004 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4005 // first list already open inputs that can be routed to this device
4006 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4007 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004008 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004009 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4010 inputs.add(mInputs.keyAt(input_index));
4011 }
4012 }
4013
4014 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004015 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004016 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4017 {
4018 if (mHwModules[module_idx]->mHandle == 0) {
4019 continue;
4020 }
4021 for (size_t profile_index = 0;
4022 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4023 profile_index++)
4024 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004025 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4026
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004027 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004028 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004029 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004030 profiles.add(profile);
4031 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4032 profile_index, module_idx);
4033 }
Eric Laurentd4692962014-05-05 18:13:44 -07004034 }
4035 }
4036 }
4037
4038 if (profiles.isEmpty() && inputs.isEmpty()) {
4039 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4040 return BAD_VALUE;
4041 }
4042
4043 // open inputs for matching profiles if needed. Direct inputs are also opened to
4044 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4045 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4046
Eric Laurent1c333e22014-05-20 10:48:17 -07004047 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004048 // nothing to do if one input is already opened for this profile
4049 size_t input_index;
4050 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4051 desc = mInputs.valueAt(input_index);
4052 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004053 if (audio_device_is_digital(device)) {
4054 devDesc->importAudioPort(profile);
4055 }
Eric Laurentd4692962014-05-05 18:13:44 -07004056 break;
4057 }
4058 }
4059 if (input_index != mInputs.size()) {
4060 continue;
4061 }
4062
4063 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4064 desc = new AudioInputDescriptor(profile);
4065 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004066 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4067 config.sample_rate = desc->mSamplingRate;
4068 config.channel_mask = desc->mChannelMask;
4069 config.format = desc->mFormat;
4070 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004071 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004072 &input,
4073 &config,
4074 &desc->mDevice,
4075 address,
4076 AUDIO_SOURCE_MIC,
4077 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004078
Eric Laurentcf2c0212014-07-25 16:20:43 -07004079 if (status == NO_ERROR) {
4080 desc->mSamplingRate = config.sample_rate;
4081 desc->mChannelMask = config.channel_mask;
4082 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004083
Eric Laurentd4692962014-05-05 18:13:44 -07004084 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004085 char *param = audio_device_address_to_parameter(device, address);
4086 mpClientInterface->setParameters(input, String8(param));
4087 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004088 }
Phil Burk00eeb322016-03-31 12:41:00 -07004089 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004090 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004091 ALOGW("checkInputsForDevice() direct input missing param");
4092 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004093 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004094 }
4095
4096 if (input != 0) {
4097 addInput(input, desc);
4098 }
4099 } // endif input != 0
4100
Eric Laurentcf2c0212014-07-25 16:20:43 -07004101 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004102 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004103 profiles.removeAt(profile_index);
4104 profile_index--;
4105 } else {
4106 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004107 if (audio_device_is_digital(device)) {
4108 devDesc->importAudioPort(profile);
4109 }
Eric Laurentd4692962014-05-05 18:13:44 -07004110 ALOGV("checkInputsForDevice(): adding input %d", input);
4111 }
4112 } // end scan profiles
4113
4114 if (profiles.isEmpty()) {
4115 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4116 return BAD_VALUE;
4117 }
4118 } else {
4119 // Disconnect
4120 // check if one opened input is not needed any more after disconnecting one device
4121 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4122 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004123 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004124 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4125 mInputs.keyAt(input_index));
4126 inputs.add(mInputs.keyAt(input_index));
4127 }
4128 }
4129 // Clear any profiles associated with the disconnected device.
4130 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4131 if (mHwModules[module_index]->mHandle == 0) {
4132 continue;
4133 }
4134 for (size_t profile_index = 0;
4135 profile_index < mHwModules[module_index]->mInputProfiles.size();
4136 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004137 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004138 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004139 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004140 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004141 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004142 }
4143 }
4144 }
4145 } // end disconnect
4146
4147 return NO_ERROR;
4148}
4149
4150
Eric Laurente0720872014-03-11 09:30:41 -07004151void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004152{
4153 ALOGV("closeOutput(%d)", output);
4154
Eric Laurentc75307b2015-03-17 15:29:32 -07004155 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004156 if (outputDesc == NULL) {
4157 ALOGW("closeOutput() unknown output %d", output);
4158 return;
4159 }
François Gaffie036e1e92015-03-19 10:16:24 +01004160 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004161
Eric Laurente552edb2014-03-10 17:42:56 -07004162 // look for duplicated outputs connected to the output being removed.
4163 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004164 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004165 if (dupOutputDesc->isDuplicated() &&
4166 (dupOutputDesc->mOutput1 == outputDesc ||
4167 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004168 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004169 if (dupOutputDesc->mOutput1 == outputDesc) {
4170 outputDesc2 = dupOutputDesc->mOutput2;
4171 } else {
4172 outputDesc2 = dupOutputDesc->mOutput1;
4173 }
4174 // As all active tracks on duplicated output will be deleted,
4175 // and as they were also referenced on the other output, the reference
4176 // count for their stream type must be adjusted accordingly on
4177 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004178 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004179 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004180 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004181 }
4182 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4183 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4184
4185 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004186 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004187 }
4188 }
4189
Eric Laurent05b90f82014-08-27 15:32:29 -07004190 nextAudioPortGeneration();
4191
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004192 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004193 if (index >= 0) {
4194 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004195 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004196 mAudioPatches.removeItemsAt(index);
4197 mpClientInterface->onAudioPatchListUpdate();
4198 }
4199
Eric Laurente552edb2014-03-10 17:42:56 -07004200 AudioParameter param;
4201 param.add(String8("closing"), String8("true"));
4202 mpClientInterface->setParameters(output, param.toString());
4203
4204 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004205 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004206 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004207}
4208
4209void AudioPolicyManager::closeInput(audio_io_handle_t input)
4210{
4211 ALOGV("closeInput(%d)", input);
4212
4213 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4214 if (inputDesc == NULL) {
4215 ALOGW("closeInput() unknown input %d", input);
4216 return;
4217 }
4218
Eric Laurent6a94d692014-05-20 11:18:06 -07004219 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004220
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004221 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004222 if (index >= 0) {
4223 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004224 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004225 mAudioPatches.removeItemsAt(index);
4226 mpClientInterface->onAudioPatchListUpdate();
4227 }
4228
4229 mpClientInterface->closeInput(input);
4230 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004231}
4232
Eric Laurentc75307b2015-03-17 15:29:32 -07004233SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4234 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004235 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004236{
4237 SortedVector<audio_io_handle_t> outputs;
4238
4239 ALOGVV("getOutputsForDevice() device %04x", device);
4240 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004241 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004242 i, openOutputs.valueAt(i)->isDuplicated(),
4243 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004244 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4245 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4246 outputs.add(openOutputs.keyAt(i));
4247 }
4248 }
4249 return outputs;
4250}
4251
Eric Laurente0720872014-03-11 09:30:41 -07004252bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004253 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004254{
4255 if (outputs1.size() != outputs2.size()) {
4256 return false;
4257 }
4258 for (size_t i = 0; i < outputs1.size(); i++) {
4259 if (outputs1[i] != outputs2[i]) {
4260 return false;
4261 }
4262 }
4263 return true;
4264}
4265
Eric Laurente0720872014-03-11 09:30:41 -07004266void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004267{
4268 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4269 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4270 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4271 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4272
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004273 // also take into account external policy-related changes: add all outputs which are
4274 // associated with policies in the "before" and "after" output vectors
4275 ALOGVV("checkOutputForStrategy(): policy related outputs");
4276 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004277 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004278 if (desc != 0 && desc->mPolicyMix != NULL) {
4279 srcOutputs.add(desc->mIoHandle);
4280 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4281 }
4282 }
4283 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004284 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004285 if (desc != 0 && desc->mPolicyMix != NULL) {
4286 dstOutputs.add(desc->mIoHandle);
4287 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4288 }
4289 }
4290
Eric Laurente552edb2014-03-10 17:42:56 -07004291 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4292 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4293 strategy, srcOutputs[0], dstOutputs[0]);
4294 // mute strategy while moving tracks from one output to another
4295 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004297 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004298 setStrategyMute(strategy, true, desc);
4299 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004300 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004301 sp<AudioSourceDescriptor> source =
4302 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4303 if (source != 0){
4304 connectAudioSource(source);
4305 }
Eric Laurente552edb2014-03-10 17:42:56 -07004306 }
4307
4308 // Move effects associated to this strategy from previous output to new output
4309 if (strategy == STRATEGY_MEDIA) {
4310 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4311 SortedVector<audio_io_handle_t> moved;
4312 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004313 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4314 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4315 effectDesc->mIo != fxOutput) {
4316 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004317 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4318 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004319 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004320 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004321 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004322 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004323 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004324 }
4325 }
4326 }
4327 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004328 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004329 if (getStrategy((audio_stream_type_t)i) == strategy) {
4330 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004331 }
4332 }
4333 }
4334}
4335
Eric Laurente0720872014-03-11 09:30:41 -07004336void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004337{
François Gaffie2110e042015-03-24 08:41:51 +01004338 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004339 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004340 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004341 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004342 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004343 checkOutputForStrategy(STRATEGY_SONIFICATION);
4344 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004345 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004346 checkOutputForStrategy(STRATEGY_MEDIA);
4347 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004348 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004349}
4350
Eric Laurente0720872014-03-11 09:30:41 -07004351void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004352{
François Gaffie53615e22015-03-19 09:24:12 +01004353 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004354 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004355 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004356 return;
4357 }
4358
Eric Laurent3a4311c2014-03-17 12:00:47 -07004359 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004360 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4361 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4362 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004363
4364 // if suspended, restore A2DP output if:
4365 // ((SCO device is NOT connected) ||
4366 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4367 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004368 //
Eric Laurentf732e072016-08-03 19:30:28 -07004369 // if not suspended, suspend A2DP output if:
4370 // (SCO device is connected) &&
4371 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4372 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004373 //
4374 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004375 if (!isScoConnected ||
4376 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4377 AUDIO_POLICY_FORCE_BT_SCO) &&
4378 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4379 AUDIO_POLICY_FORCE_BT_SCO) &&
4380 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004381 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004382
4383 mpClientInterface->restoreOutput(a2dpOutput);
4384 mA2dpSuspended = false;
4385 }
4386 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004387 if (isScoConnected &&
4388 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4389 AUDIO_POLICY_FORCE_BT_SCO) ||
4390 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4391 AUDIO_POLICY_FORCE_BT_SCO) ||
4392 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004393 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004394
4395 mpClientInterface->suspendOutput(a2dpOutput);
4396 mA2dpSuspended = true;
4397 }
4398 }
4399}
4400
Eric Laurentc75307b2015-03-17 15:29:32 -07004401audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4402 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004403{
4404 audio_devices_t device = AUDIO_DEVICE_NONE;
4405
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004406 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 if (index >= 0) {
4408 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4409 if (patchDesc->mUid != mUidCached) {
4410 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004411 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004412 return outputDesc->device();
4413 }
4414 }
4415
Eric Laurente552edb2014-03-10 17:42:56 -07004416 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004417 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004418 // use device for strategy enforced audible
4419 // 2: we are in call or the strategy phone is active on the output:
4420 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004421 // 3: the strategy for enforced audible is active but not enforced on the output:
4422 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004423 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004424 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004425 // 5: the strategy accessibility is active on the output:
4426 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004427 // 6: the strategy "respectful" sonification is active on the output:
4428 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004429 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004430 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004431 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004432 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004433 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004434 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004435 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004436 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004437 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4438 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004439 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004440 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004441 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004442 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004443 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004444 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004445 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4446 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004447 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004448 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004449 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004450 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004451 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004452 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004453 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004454 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004455 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004456 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004457 }
4458
Eric Laurent1c333e22014-05-20 10:48:17 -07004459 ALOGV("getNewOutputDevice() selected device %x", device);
4460 return device;
4461}
4462
Eric Laurentfb66dd92016-01-28 18:32:03 -08004463audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004464{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004465 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004466
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004467 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004468 if (index >= 0) {
4469 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4470 if (patchDesc->mUid != mUidCached) {
4471 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004472 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 return inputDesc->mDevice;
4474 }
4475 }
4476
Eric Laurentfb66dd92016-01-28 18:32:03 -08004477 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4478 if (isInCall()) {
4479 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4480 } else if (source != AUDIO_SOURCE_DEFAULT) {
4481 device = getDeviceAndMixForInputSource(source);
4482 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004483
Eric Laurente552edb2014-03-10 17:42:56 -07004484 return device;
4485}
4486
Eric Laurent794fde22016-03-11 09:50:45 -08004487bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4488 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004489 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004490}
4491
Eric Laurente0720872014-03-11 09:30:41 -07004492uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004493 return (uint32_t)getStrategy(stream);
4494}
4495
Eric Laurente0720872014-03-11 09:30:41 -07004496audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004497 // By checking the range of stream before calling getStrategy, we avoid
4498 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4499 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004500 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004501 return AUDIO_DEVICE_NONE;
4502 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004503 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004504 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4505 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004506 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004507 }
Eric Laurent794fde22016-03-11 09:50:45 -08004508 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004509 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004510 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004511 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4512 for (size_t i = 0; i < outputs.size(); i++) {
4513 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004514 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004515 curDevices |= outputDesc->device();
4516 }
4517 }
4518 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004519 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004520
4521 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4522 and doesn't really need to.*/
4523 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4524 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4525 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4526 }
Eric Laurente552edb2014-03-10 17:42:56 -07004527 return devices;
4528}
4529
François Gaffie2110e042015-03-24 08:41:51 +01004530routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4531{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004532 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004533 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004534}
4535
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004536uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4537 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004538 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4539 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4540 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004541 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4542 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4543 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004544 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004545 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004546}
4547
Eric Laurente0720872014-03-11 09:30:41 -07004548void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004549 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004550 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004551 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4552 updateDevicesAndOutputs();
4553 break;
4554 default:
4555 break;
4556 }
4557}
4558
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004559uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004560
4561 // skip beacon mute management if a dedicated TTS output is available
4562 if (mTtsOutputAvailable) {
4563 return 0;
4564 }
4565
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004566 switch(event) {
4567 case STARTING_OUTPUT:
4568 mBeaconMuteRefCount++;
4569 break;
4570 case STOPPING_OUTPUT:
4571 if (mBeaconMuteRefCount > 0) {
4572 mBeaconMuteRefCount--;
4573 }
4574 break;
4575 case STARTING_BEACON:
4576 mBeaconPlayingRefCount++;
4577 break;
4578 case STOPPING_BEACON:
4579 if (mBeaconPlayingRefCount > 0) {
4580 mBeaconPlayingRefCount--;
4581 }
4582 break;
4583 }
4584
4585 if (mBeaconMuteRefCount > 0) {
4586 // any playback causes beacon to be muted
4587 return setBeaconMute(true);
4588 } else {
4589 // no other playback: unmute when beacon starts playing, mute when it stops
4590 return setBeaconMute(mBeaconPlayingRefCount == 0);
4591 }
4592}
4593
4594uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4595 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4596 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4597 // keep track of muted state to avoid repeating mute/unmute operations
4598 if (mBeaconMuted != mute) {
4599 // mute/unmute AUDIO_STREAM_TTS on all outputs
4600 ALOGV("\t muting %d", mute);
4601 uint32_t maxLatency = 0;
4602 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004603 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004604 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004605 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004606 0 /*delay*/, AUDIO_DEVICE_NONE);
4607 const uint32_t latency = desc->latency() * 2;
4608 if (latency > maxLatency) {
4609 maxLatency = latency;
4610 }
4611 }
4612 mBeaconMuted = mute;
4613 return maxLatency;
4614 }
4615 return 0;
4616}
4617
Eric Laurente0720872014-03-11 09:30:41 -07004618audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004619 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004620{
Paul McLeanaa981192015-03-21 09:55:15 -07004621 // Routing
4622 // see if we have an explicit route
4623 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4624 // (getStrategy(stream)).
4625 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4626 // and activity count is non-zero
4627 // the device = the device from the descriptor in the RouteMap, and exit.
4628 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4629 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004630 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4631 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004632 return route->mDeviceDescriptor->type();
4633 }
4634 }
4635
Eric Laurente552edb2014-03-10 17:42:56 -07004636 if (fromCache) {
4637 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4638 strategy, mDeviceForStrategy[strategy]);
4639 return mDeviceForStrategy[strategy];
4640 }
François Gaffie2110e042015-03-24 08:41:51 +01004641 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004642}
4643
Eric Laurente0720872014-03-11 09:30:41 -07004644void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004645{
4646 for (int i = 0; i < NUM_STRATEGIES; i++) {
4647 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4648 }
4649 mPreviousOutputs = mOutputs;
4650}
4651
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004652uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004653 audio_devices_t prevDevice,
4654 uint32_t delayMs)
4655{
4656 // mute/unmute strategies using an incompatible device combination
4657 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4658 // if unmuting, unmute only after the specified delay
4659 if (outputDesc->isDuplicated()) {
4660 return 0;
4661 }
4662
4663 uint32_t muteWaitMs = 0;
4664 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004665 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004666
4667 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4668 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004669 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004670 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4671 bool doMute = false;
4672
4673 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4674 doMute = true;
4675 outputDesc->mStrategyMutedByDevice[i] = true;
4676 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4677 doMute = true;
4678 outputDesc->mStrategyMutedByDevice[i] = false;
4679 }
Eric Laurent99401132014-05-07 19:48:15 -07004680 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004681 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004682 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004683 // skip output if it does not share any device with current output
4684 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4685 == AUDIO_DEVICE_NONE) {
4686 continue;
4687 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004688 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004689 mute ? "muting" : "unmuting", i, curDevice);
4690 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004691 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004692 if (mute) {
4693 // FIXME: should not need to double latency if volume could be applied
4694 // immediately by the audioflinger mixer. We must account for the delay
4695 // between now and the next time the audioflinger thread for this output
4696 // will process a buffer (which corresponds to one buffer size,
4697 // usually 1/2 or 1/4 of the latency).
4698 if (muteWaitMs < desc->latency() * 2) {
4699 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004700 }
4701 }
4702 }
4703 }
4704 }
4705 }
4706
Eric Laurent99401132014-05-07 19:48:15 -07004707 // temporary mute output if device selection changes to avoid volume bursts due to
4708 // different per device volumes
4709 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004710 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4711 // temporary mute duration is conservatively set to 4 times the reported latency
4712 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4713 if (muteWaitMs < tempMuteWaitMs) {
4714 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004715 }
Eric Laurentdc462862016-07-19 12:29:53 -07004716
Eric Laurent99401132014-05-07 19:48:15 -07004717 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004718 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004719 // make sure that we do not start the temporary mute period too early in case of
4720 // delayed device change
4721 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004722 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004723 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004724 }
4725 }
4726 }
4727
Eric Laurente552edb2014-03-10 17:42:56 -07004728 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4729 if (muteWaitMs > delayMs) {
4730 muteWaitMs -= delayMs;
4731 usleep(muteWaitMs * 1000);
4732 return muteWaitMs;
4733 }
4734 return 0;
4735}
4736
Eric Laurentc75307b2015-03-17 15:29:32 -07004737uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004738 audio_devices_t device,
4739 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004741 audio_patch_handle_t *patchHandle,
4742 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004743{
Eric Laurentc75307b2015-03-17 15:29:32 -07004744 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004745 AudioParameter param;
4746 uint32_t muteWaitMs;
4747
4748 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004749 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4750 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004751 return muteWaitMs;
4752 }
4753 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4754 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004755 if ((device != AUDIO_DEVICE_NONE) &&
4756 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004757 return 0;
4758 }
4759
4760 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004761 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004762
4763 audio_devices_t prevDevice = outputDesc->mDevice;
4764
Paul McLeanaa981192015-03-21 09:55:15 -07004765 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004766
4767 if (device != AUDIO_DEVICE_NONE) {
4768 outputDesc->mDevice = device;
4769 }
4770 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4771
4772 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004773 // the requested device is AUDIO_DEVICE_NONE
4774 // OR the requested device is the same as current device
4775 // AND force is not specified
4776 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004777 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004778 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4779 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004780 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004781 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004782 return muteWaitMs;
4783 }
4784
4785 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004786
Eric Laurente552edb2014-03-10 17:42:56 -07004787 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004788 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004789 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004790 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004791 DeviceVector deviceList;
4792 if ((address == NULL) || (strlen(address) == 0)) {
4793 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4794 } else {
4795 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4796 }
4797
Eric Laurent1c333e22014-05-20 10:48:17 -07004798 if (!deviceList.isEmpty()) {
4799 struct audio_patch patch;
4800 outputDesc->toAudioPortConfig(&patch.sources[0]);
4801 patch.num_sources = 1;
4802 patch.num_sinks = 0;
4803 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4804 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004805 patch.num_sinks++;
4806 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 ssize_t index;
4808 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4809 index = mAudioPatches.indexOfKey(*patchHandle);
4810 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004811 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 }
4813 sp< AudioPatch> patchDesc;
4814 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4815 if (index >= 0) {
4816 patchDesc = mAudioPatches.valueAt(index);
4817 afPatchHandle = patchDesc->mAfPatchHandle;
4818 }
4819
Eric Laurent1c333e22014-05-20 10:48:17 -07004820 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004821 &afPatchHandle,
4822 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004823 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4824 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004825 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004826 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004828 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004829 addAudioPatch(patchDesc->mHandle, patchDesc);
4830 } else {
4831 patchDesc->mPatch = patch;
4832 }
4833 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004834 if (patchHandle) {
4835 *patchHandle = patchDesc->mHandle;
4836 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004837 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004838 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004839 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004840 }
4841 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004842
4843 // inform all input as well
4844 for (size_t i = 0; i < mInputs.size(); i++) {
4845 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004846 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004847 AudioParameter inputCmd = AudioParameter();
4848 ALOGV("%s: inform input %d of device:%d", __func__,
4849 inputDescriptor->mIoHandle, device);
4850 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4851 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4852 inputCmd.toString(),
4853 delayMs);
4854 }
4855 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004856 }
Eric Laurente552edb2014-03-10 17:42:56 -07004857
4858 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004859 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004860
4861 return muteWaitMs;
4862}
4863
Eric Laurentc75307b2015-03-17 15:29:32 -07004864status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 int delayMs,
4866 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004867{
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 ssize_t index;
4869 if (patchHandle) {
4870 index = mAudioPatches.indexOfKey(*patchHandle);
4871 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004872 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 }
4874 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004875 return INVALID_OPERATION;
4876 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4878 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004879 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004880 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 removeAudioPatch(patchDesc->mHandle);
4882 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004883 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004884 return status;
4885}
4886
4887status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4888 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 bool force,
4890 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004891{
4892 status_t status = NO_ERROR;
4893
Eric Laurent1f2f2232014-06-02 12:01:23 -07004894 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004895 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4896 inputDesc->mDevice = device;
4897
4898 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4899 if (!deviceList.isEmpty()) {
4900 struct audio_patch patch;
4901 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004902 // AUDIO_SOURCE_HOTWORD is for internal use only:
4903 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004904 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004905 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004906 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4907 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004908 patch.num_sinks = 1;
4909 //only one input device for now
4910 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004911 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 ssize_t index;
4913 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4914 index = mAudioPatches.indexOfKey(*patchHandle);
4915 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004916 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 }
4918 sp< AudioPatch> patchDesc;
4919 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4920 if (index >= 0) {
4921 patchDesc = mAudioPatches.valueAt(index);
4922 afPatchHandle = patchDesc->mAfPatchHandle;
4923 }
4924
Eric Laurent1c333e22014-05-20 10:48:17 -07004925 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004927 0);
4928 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004930 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004931 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004932 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 addAudioPatch(patchDesc->mHandle, patchDesc);
4934 } else {
4935 patchDesc->mPatch = patch;
4936 }
4937 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 if (patchHandle) {
4939 *patchHandle = patchDesc->mHandle;
4940 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004941 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004942 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004943 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004944 }
4945 }
4946 }
4947 return status;
4948}
4949
Eric Laurent6a94d692014-05-20 11:18:06 -07004950status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4951 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004952{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004953 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 ssize_t index;
4955 if (patchHandle) {
4956 index = mAudioPatches.indexOfKey(*patchHandle);
4957 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004958 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 }
4960 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004961 return INVALID_OPERATION;
4962 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4964 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004965 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004966 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 removeAudioPatch(patchDesc->mHandle);
4968 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004969 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004970 return status;
4971}
4972
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004973sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004974 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004975 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004976 audio_format_t& format,
4977 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004978 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004979{
4980 // Choose an input profile based on the requested capture parameters: select the first available
4981 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004982 //
4983 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4984 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004985
4986 for (size_t i = 0; i < mHwModules.size(); i++)
4987 {
4988 if (mHwModules[i]->mHandle == 0) {
4989 continue;
4990 }
4991 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4992 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004993 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004994 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004995 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004996 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004997 format,
4998 &format /*updatedFormat*/,
4999 channelMask,
5000 &channelMask /*updatedChannelMask*/,
5001 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005002
Eric Laurente552edb2014-03-10 17:42:56 -07005003 return profile;
5004 }
5005 }
5006 }
5007 return NULL;
5008}
5009
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005010
5011audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005012 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005013{
François Gaffie036e1e92015-03-19 10:16:24 +01005014 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5015 audio_devices_t selectedDeviceFromMix =
5016 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005017
François Gaffie036e1e92015-03-19 10:16:24 +01005018 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5019 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005020 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005021 return getDeviceForInputSource(inputSource);
5022}
5023
5024audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5025{
Paul McLean466dc8e2015-04-17 13:15:36 -06005026 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5027 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005028 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005029 return route->mDeviceDescriptor->type();
5030 }
5031 }
5032
5033 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005034}
5035
Eric Laurente0720872014-03-11 09:30:41 -07005036float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005037 int index,
5038 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005039{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005040 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005041
5042 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5043 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5044 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5045 // the ringtone volume
5046 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5047 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5048 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5049 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5050 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5051 }
5052
Eric Laurente552edb2014-03-10 17:42:56 -07005053 // if a headset is connected, apply the following rules to ring tones and notifications
5054 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005055 // - always attenuate notifications volume by 6dB
5056 // - attenuate ring tones volume by 6dB unless music is not playing and
5057 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005058 // - if music is playing, always limit the volume to current music volume,
5059 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005060 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005061 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5062 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5063 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5064 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5065 ((stream_strategy == STRATEGY_SONIFICATION)
5066 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005067 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005068 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005069 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005070 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005071 // when the phone is ringing we must consider that music could have been paused just before
5072 // by the music application and behave as if music was active if the last music track was
5073 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005074 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005075 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005076 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005077 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005078 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005079 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5080 musicDevice),
5081 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005082 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5083 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005084 if (volumeDB > minVolDB) {
5085 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005086 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005087 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005088 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5089 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5090 // on A2DP, also ensure notification volume is not too low compared to media when
5091 // intended to be played
5092 if ((volumeDB > -96.0f) &&
5093 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5094 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5095 stream, device,
5096 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5097 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5098 }
5099 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005100 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5101 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005102 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005103 }
5104 }
5105
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005106 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005107}
5108
Eric Laurente0720872014-03-11 09:30:41 -07005109status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005110 int index,
5111 const sp<AudioOutputDescriptor>& outputDesc,
5112 audio_devices_t device,
5113 int delayMs,
5114 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005115{
Eric Laurente552edb2014-03-10 17:42:56 -07005116 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005117 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005118 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005119 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005120 return NO_ERROR;
5121 }
François Gaffie2110e042015-03-24 08:41:51 +01005122 audio_policy_forced_cfg_t forceUseForComm =
5123 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005124 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005125 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5126 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005127 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005128 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005129 return INVALID_OPERATION;
5130 }
5131
Eric Laurentc75307b2015-03-17 15:29:32 -07005132 if (device == AUDIO_DEVICE_NONE) {
5133 device = outputDesc->device();
5134 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005135
Eric Laurentffbc80f2015-03-18 18:30:19 -07005136 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005137 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005138 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005139 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005140
Eric Laurentffbc80f2015-03-18 18:30:19 -07005141 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005142
Eric Laurent3b73df72014-03-11 09:06:29 -07005143 if (stream == AUDIO_STREAM_VOICE_CALL ||
5144 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005145 float voiceVolume;
5146 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005147 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005148 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005149 } else {
5150 voiceVolume = 1.0;
5151 }
5152
Eric Laurent18fba842016-03-31 14:41:26 -07005153 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005154 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5155 mLastVoiceVolume = voiceVolume;
5156 }
5157 }
5158
5159 return NO_ERROR;
5160}
5161
Eric Laurentc75307b2015-03-17 15:29:32 -07005162void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5163 audio_devices_t device,
5164 int delayMs,
5165 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005166{
Eric Laurentc75307b2015-03-17 15:29:32 -07005167 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005168
Eric Laurent794fde22016-03-11 09:50:45 -08005169 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005170 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005171 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005172 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005173 device,
5174 delayMs,
5175 force);
5176 }
5177}
5178
Eric Laurente0720872014-03-11 09:30:41 -07005179void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005180 bool on,
5181 const sp<AudioOutputDescriptor>& outputDesc,
5182 int delayMs,
5183 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005184{
Eric Laurent72249d52015-06-08 11:12:15 -07005185 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5186 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005187 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005188 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005189 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005190 }
5191 }
5192}
5193
Eric Laurente0720872014-03-11 09:30:41 -07005194void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 bool on,
5196 const sp<AudioOutputDescriptor>& outputDesc,
5197 int delayMs,
5198 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005199{
Eric Laurente552edb2014-03-10 17:42:56 -07005200 if (device == AUDIO_DEVICE_NONE) {
5201 device = outputDesc->device();
5202 }
5203
Eric Laurentc75307b2015-03-17 15:29:32 -07005204 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5205 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005206
5207 if (on) {
5208 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005209 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005210 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005211 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005212 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005213 }
5214 }
5215 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5216 outputDesc->mMuteCount[stream]++;
5217 } else {
5218 if (outputDesc->mMuteCount[stream] == 0) {
5219 ALOGV("setStreamMute() unmuting non muted stream!");
5220 return;
5221 }
5222 if (--outputDesc->mMuteCount[stream] == 0) {
5223 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005224 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005225 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005226 device,
5227 delayMs);
5228 }
5229 }
5230}
5231
Eric Laurente0720872014-03-11 09:30:41 -07005232void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005233 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005234{
Eric Laurent87ffa392015-05-22 10:32:38 -07005235 if(!hasPrimaryOutput()) {
5236 return;
5237 }
5238
Eric Laurente552edb2014-03-10 17:42:56 -07005239 // if the stream pertains to sonification strategy and we are in call we must
5240 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5241 // in the device used for phone strategy and play the tone if the selected device does not
5242 // interfere with the device used for phone strategy
5243 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5244 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005245 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005246 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5247 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005248 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005249 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5250 stream, starting, outputDesc->mDevice, stateChange);
5251 if (outputDesc->mRefCount[stream]) {
5252 int muteCount = 1;
5253 if (stateChange) {
5254 muteCount = outputDesc->mRefCount[stream];
5255 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005256 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005257 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5258 for (int i = 0; i < muteCount; i++) {
5259 setStreamMute(stream, starting, mPrimaryOutput);
5260 }
5261 } else {
5262 ALOGV("handleIncallSonification() high visibility");
5263 if (outputDesc->device() &
5264 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5265 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5266 for (int i = 0; i < muteCount; i++) {
5267 setStreamMute(stream, starting, mPrimaryOutput);
5268 }
5269 }
5270 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005271 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5272 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005273 } else {
5274 mpClientInterface->stopTone();
5275 }
5276 }
5277 }
5278 }
5279}
5280
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005281audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5282{
5283 // flags to stream type mapping
5284 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5285 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5286 }
5287 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5288 return AUDIO_STREAM_BLUETOOTH_SCO;
5289 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005290 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5291 return AUDIO_STREAM_TTS;
5292 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005293
5294 // usage to stream type mapping
5295 switch (attr->usage) {
5296 case AUDIO_USAGE_MEDIA:
5297 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005298 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5299 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005300 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5301 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005302 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5303 return AUDIO_STREAM_SYSTEM;
5304 case AUDIO_USAGE_VOICE_COMMUNICATION:
5305 return AUDIO_STREAM_VOICE_CALL;
5306
5307 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5308 return AUDIO_STREAM_DTMF;
5309
5310 case AUDIO_USAGE_ALARM:
5311 return AUDIO_STREAM_ALARM;
5312 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5313 return AUDIO_STREAM_RING;
5314
5315 case AUDIO_USAGE_NOTIFICATION:
5316 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5317 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5318 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5319 case AUDIO_USAGE_NOTIFICATION_EVENT:
5320 return AUDIO_STREAM_NOTIFICATION;
5321
5322 case AUDIO_USAGE_UNKNOWN:
5323 default:
5324 return AUDIO_STREAM_MUSIC;
5325 }
5326}
Eric Laurente83b55d2014-11-14 10:06:21 -08005327
François Gaffie53615e22015-03-19 09:24:12 +01005328bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5329{
Eric Laurente83b55d2014-11-14 10:06:21 -08005330 // has flags that map to a strategy?
5331 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5332 return true;
5333 }
5334
5335 // has known usage?
5336 switch (paa->usage) {
5337 case AUDIO_USAGE_UNKNOWN:
5338 case AUDIO_USAGE_MEDIA:
5339 case AUDIO_USAGE_VOICE_COMMUNICATION:
5340 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5341 case AUDIO_USAGE_ALARM:
5342 case AUDIO_USAGE_NOTIFICATION:
5343 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5344 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5345 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5346 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5347 case AUDIO_USAGE_NOTIFICATION_EVENT:
5348 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5349 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5350 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5351 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005352 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005353 break;
5354 default:
5355 return false;
5356 }
5357 return true;
5358}
5359
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005360bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005361 routing_strategy strategy, uint32_t inPastMs,
5362 nsecs_t sysTime) const
5363{
5364 if ((sysTime == 0) && (inPastMs != 0)) {
5365 sysTime = systemTime();
5366 }
Eric Laurent794fde22016-03-11 09:50:45 -08005367 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005368 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5369 (NUM_STRATEGIES == strategy)) &&
5370 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5371 return true;
5372 }
5373 }
5374 return false;
5375}
5376
François Gaffie2110e042015-03-24 08:41:51 +01005377audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5378{
5379 return mEngine->getForceUse(usage);
5380}
5381
5382bool AudioPolicyManager::isInCall()
5383{
5384 return isStateInCall(mEngine->getPhoneState());
5385}
5386
5387bool AudioPolicyManager::isStateInCall(int state)
5388{
5389 return is_state_in_call(state);
5390}
5391
Eric Laurentd60560a2015-04-10 11:31:20 -07005392void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5393{
5394 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5395 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5396 if (sourceDesc->mDevice->equals(deviceDesc)) {
5397 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5398 stopAudioSource(sourceDesc->getHandle());
5399 }
5400 }
5401
5402 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5403 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5404 bool release = false;
5405 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5406 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5407 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5408 source->ext.device.type == deviceDesc->type()) {
5409 release = true;
5410 }
5411 }
5412 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5413 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5414 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5415 sink->ext.device.type == deviceDesc->type()) {
5416 release = true;
5417 }
5418 }
5419 if (release) {
5420 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5421 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5422 }
5423 }
5424}
5425
Phil Burk09bc4612016-02-24 15:58:15 -08005426// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005427void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5428 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005429 // TODO Set this based on Config properties.
5430 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005431
5432 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5433 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005434 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005435
5436 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005437 bool supportsAC3 = false;
5438 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005439 bool supportsIEC61937 = false;
5440 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5441 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005442 switch (format) {
5443 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005444 supportsAC3 = true;
5445 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005446 case AUDIO_FORMAT_E_AC3:
5447 case AUDIO_FORMAT_DTS:
5448 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005449 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005450 break;
5451 case AUDIO_FORMAT_IEC61937:
5452 supportsIEC61937 = true;
5453 break;
5454 default:
5455 break;
5456 }
5457 }
Phil Burk09bc4612016-02-24 15:58:15 -08005458
5459 // Modify formats based on surround preferences.
5460 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005461 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5462 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5463 // Remove surround sound related formats.
5464 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5465 audio_format_t format = formats[formatIndex];
5466 switch(format) {
5467 case AUDIO_FORMAT_AC3:
5468 case AUDIO_FORMAT_E_AC3:
5469 case AUDIO_FORMAT_DTS:
5470 case AUDIO_FORMAT_DTS_HD:
5471 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005472 formats.removeAt(formatIndex);
5473 break;
5474 default:
5475 formatIndex++; // keep it
5476 break;
5477 }
Phil Burk09bc4612016-02-24 15:58:15 -08005478 }
Phil Burk07ac1142016-03-25 13:39:29 -07005479 supportsAC3 = false;
5480 supportsOtherSurround = false;
5481 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005482 }
Phil Burk07ac1142016-03-25 13:39:29 -07005483 } else { // AUTO or ALWAYS
5484 // Most TVs support AC3 even if they do not report it in the EDID.
5485 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5486 && !supportsAC3) {
5487 formats.add(AUDIO_FORMAT_AC3);
5488 supportsAC3 = true;
5489 }
5490
5491 // If ALWAYS, add support for raw surround formats if all are missing.
5492 // This assumes that if any of these formats are reported by the HAL
5493 // then the report is valid and should not be modified.
5494 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5495 && !supportsOtherSurround) {
5496 formats.add(AUDIO_FORMAT_E_AC3);
5497 formats.add(AUDIO_FORMAT_DTS);
5498 formats.add(AUDIO_FORMAT_DTS_HD);
5499 supportsOtherSurround = true;
5500 }
5501
5502 // Add support for IEC61937 if any raw surround supported.
5503 // The HAL could do this but add it here, just in case.
5504 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5505 formats.add(AUDIO_FORMAT_IEC61937);
5506 supportsIEC61937 = true;
5507 }
Phil Burk09bc4612016-02-24 15:58:15 -08005508 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005509}
5510
5511// Modify the list of channel masks supported.
5512void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5513 ChannelsVector &channelMasks = *channelMasksPtr;
5514 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5515 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5516
5517 // If NEVER, then remove support for channelMasks > stereo.
5518 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5519 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5520 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5521 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5522 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5523 channelMasks.removeAt(maskIndex);
5524 } else {
5525 maskIndex++;
5526 }
5527 }
5528 // If ALWAYS, then make sure we at least support 5.1
5529 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5530 bool supports5dot1 = false;
5531 // Are there any channel masks that can be considered "surround"?
5532 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5533 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5534 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5535 supports5dot1 = true;
5536 break;
5537 }
5538 }
5539 // If not then add 5.1 support.
5540 if (!supports5dot1) {
5541 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5542 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5543 }
Phil Burk09bc4612016-02-24 15:58:15 -08005544 }
5545}
5546
Phil Burk00eeb322016-03-31 12:41:00 -07005547void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5548 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005549 AudioProfileVector &profiles)
5550{
5551 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005552
François Gaffie112b0af2015-11-19 16:13:25 +01005553 // Format MUST be checked first to update the list of AudioProfile
5554 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005555 reply = mpClientInterface->getParameters(
5556 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005557 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005558 AudioParameter repliedParameters(reply);
5559 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005560 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005561 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5562 return;
5563 }
Phil Burk09bc4612016-02-24 15:58:15 -08005564 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005565 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005566 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005567 }
Phil Burk09bc4612016-02-24 15:58:15 -08005568 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005569 }
5570 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5571
Eric Laurent20eb3a42016-01-26 18:39:17 -08005572 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005573 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005574 ChannelsVector channelMasks;
5575 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005576 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005577 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005578
5579 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005580 reply = mpClientInterface->getParameters(
5581 ioHandle,
5582 requestedParameters.toString() + ";" +
5583 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005584 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005585 AudioParameter repliedParameters(reply);
5586 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005587 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005588 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005589 }
5590 }
5591 if (profiles.hasDynamicChannelsFor(format)) {
5592 reply = mpClientInterface->getParameters(ioHandle,
5593 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005594 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005595 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005596 AudioParameter repliedParameters(reply);
5597 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005598 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005599 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005600 if (device == AUDIO_DEVICE_OUT_HDMI) {
5601 filterSurroundChannelMasks(&channelMasks);
5602 }
François Gaffie112b0af2015-11-19 16:13:25 +01005603 }
5604 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005605 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005606 }
5607}
Eric Laurentd60560a2015-04-10 11:31:20 -07005608
Eric Laurente552edb2014-03-10 17:42:56 -07005609}; // namespace android