blob: 125d4225ff969f7688a2d3f398624594d612681f [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>
Eric Laurentd4692962014-05-05 18:13:44 -070040#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010041#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010042#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010043#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010044#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010045#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010046#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010047#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048
Eric Laurent3b73df72014-03-11 09:06:29 -070049namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurentdc462862016-07-19 12:29:53 -070051//FIXME: workaround for truncated touch sounds
52// to be removed when the problem is handled by system UI
53#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070054// ----------------------------------------------------------------------------
55// AudioPolicyInterface implementation
56// ----------------------------------------------------------------------------
57
Eric Laurente0720872014-03-11 09:30:41 -070058status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080059 audio_policy_dev_state_t state,
60 const char *device_address,
61 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070062{
Paul McLeane743a472015-01-28 11:07:31 -080063 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080064}
65
François Gaffie44481e72016-04-20 07:49:57 +020066void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
67 audio_policy_dev_state_t state,
68 const String8 &device_address)
69{
70 AudioParameter param(device_address);
71 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070072 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020073 param.addInt(key, device);
74 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
75}
76
Eric Laurentc73ca6e2014-12-12 14:34:22 -080077status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080078 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080079 const char *device_address,
80 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080081{
Paul McLeane743a472015-01-28 11:07:31 -080082 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
83- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070084
85 // connect/disconnect only 1 device at a time
86 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
87
François Gaffie53615e22015-03-19 09:24:12 +010088 sp<DeviceDescriptor> devDesc =
89 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080090
Eric Laurente552edb2014-03-10 17:42:56 -070091 // handle output devices
92 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070093 SortedVector <audio_io_handle_t> outputs;
94
Eric Laurent3a4311c2014-03-17 12:00:47 -070095 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
96
Eric Laurente552edb2014-03-10 17:42:56 -070097 // save a copy of the opened output descriptors before any output is opened or closed
98 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
99 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700100 switch (state)
101 {
102 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800103 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700104 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700105 ALOGW("setDeviceConnectionState() device already connected: %x", device);
106 return INVALID_OPERATION;
107 }
108 ALOGV("setDeviceConnectionState() connecting device %x", device);
109
Eric Laurente552edb2014-03-10 17:42:56 -0700110 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700111 index = mAvailableOutputDevices.add(devDesc);
112 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100113 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700114 if (module == 0) {
115 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
116 device);
117 mAvailableOutputDevices.remove(devDesc);
118 return INVALID_OPERATION;
119 }
Paul McLeane743a472015-01-28 11:07:31 -0800120 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700121 } else {
122 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700123 }
124
François Gaffie44481e72016-04-20 07:49:57 +0200125 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
126 // parameters on newly connected devices (instead of opening the outputs...)
127 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
128
Eric Laurenta1d525f2015-01-29 13:36:45 -0800129 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700130 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200131
132 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
133 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700134 return INVALID_OPERATION;
135 }
François Gaffie2110e042015-03-24 08:41:51 +0100136 // Propagate device availability to Engine
137 mEngine->setDeviceConnectionState(devDesc, state);
138
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700139 // outputs should never be empty here
140 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
141 "checkOutputsForDevice() returned no outputs but status OK");
142 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
143 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800144
Eric Laurent3ae5f312015-02-03 17:12:08 -0800145 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700146 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700147 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700148 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700149 ALOGW("setDeviceConnectionState() device not connected: %x", device);
150 return INVALID_OPERATION;
151 }
152
Paul McLean5c477aa2014-08-20 16:47:57 -0700153 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
154
Paul McLeane743a472015-01-28 11:07:31 -0800155 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200156 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700157
Eric Laurente552edb2014-03-10 17:42:56 -0700158 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700159 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700160
Eric Laurenta1d525f2015-01-29 13:36:45 -0800161 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100162
163 // Propagate device availability to Engine
164 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700165 } break;
166
167 default:
168 ALOGE("setDeviceConnectionState() invalid state: %x", state);
169 return BAD_VALUE;
170 }
171
Eric Laurent3a4311c2014-03-17 12:00:47 -0700172 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
173 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700174 checkA2dpSuspend();
175 checkOutputForAllStrategies();
176 // outputs must be closed after checkOutputForAllStrategies() is executed
177 if (!outputs.isEmpty()) {
178 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700179 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700180 // close unused outputs after device disconnection or direct outputs that have been
181 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700182 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700183 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
184 (desc->mDirectOpenCount == 0))) {
185 closeOutput(outputs[i]);
186 }
187 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700188 // check again after closing A2DP output to reset mA2dpSuspended if needed
189 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700190 }
191
192 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700193 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700194 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
195 updateCallRouting(newDevice);
196 }
Eric Laurente552edb2014-03-10 17:42:56 -0700197 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700198 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
199 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
200 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700201 // do not force device change on duplicated output because if device is 0, it will
202 // also force a device 0 for the two outputs it is duplicated to which may override
203 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700204 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100205 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700206 // always force when disconnecting (a non-duplicated device)
207 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700208 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700209 }
Eric Laurente552edb2014-03-10 17:42:56 -0700210 }
211
Eric Laurentd60560a2015-04-10 11:31:20 -0700212 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
213 cleanUpForDevice(devDesc);
214 }
215
Eric Laurent72aa32f2014-05-30 18:51:48 -0700216 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700217 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700218 } // end if is output device
219
Eric Laurente552edb2014-03-10 17:42:56 -0700220 // handle input devices
221 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700222 SortedVector <audio_io_handle_t> inputs;
223
Eric Laurent3a4311c2014-03-17 12:00:47 -0700224 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700225 switch (state)
226 {
227 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700228 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700229 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700230 ALOGW("setDeviceConnectionState() device already connected: %d", device);
231 return INVALID_OPERATION;
232 }
François Gaffie53615e22015-03-19 09:24:12 +0100233 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700234 if (module == NULL) {
235 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
236 device);
237 return INVALID_OPERATION;
238 }
François Gaffie44481e72016-04-20 07:49:57 +0200239
240 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
241 // parameters on newly connected devices (instead of opening the inputs...)
242 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
243
Paul McLean9080a4c2015-06-18 08:24:02 -0700244 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200245 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
246 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700247 return INVALID_OPERATION;
248 }
249
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 index = mAvailableInputDevices.add(devDesc);
251 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800252 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 } else {
254 return NO_MEMORY;
255 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800256
François Gaffie2110e042015-03-24 08:41:51 +0100257 // Propagate device availability to Engine
258 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700259 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700260
261 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700262 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700264 ALOGW("setDeviceConnectionState() device not connected: %d", device);
265 return INVALID_OPERATION;
266 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700267
268 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
269
270 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200271 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700272
Paul McLean9080a4c2015-06-18 08:24:02 -0700273 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700274 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700275
François Gaffie2110e042015-03-24 08:41:51 +0100276 // Propagate device availability to Engine
277 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700278 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700279
280 default:
281 ALOGE("setDeviceConnectionState() invalid state: %x", state);
282 return BAD_VALUE;
283 }
284
Eric Laurentd4692962014-05-05 18:13:44 -0700285 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700286 // As the input device list can impact the output device selection, update
287 // getDeviceForStrategy() cache
288 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700289
Eric Laurent87ffa392015-05-22 10:32:38 -0700290 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700291 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
292 updateCallRouting(newDevice);
293 }
294
Eric Laurentd60560a2015-04-10 11:31:20 -0700295 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
296 cleanUpForDevice(devDesc);
297 }
298
Eric Laurentb52c1522014-05-20 11:27:36 -0700299 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700300 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700301 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700302
303 ALOGW("setDeviceConnectionState() invalid device: %x", device);
304 return BAD_VALUE;
305}
306
Eric Laurente0720872014-03-11 09:30:41 -0700307audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100308 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700309{
Eric Laurent634b7142016-04-20 13:48:02 -0700310 sp<DeviceDescriptor> devDesc =
311 mHwModules.getDeviceDescriptor(device, device_address, "",
312 (strlen(device_address) != 0)/*matchAddress*/);
313
314 if (devDesc == 0) {
315 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
316 device, device_address);
317 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
318 }
François Gaffie53615e22015-03-19 09:24:12 +0100319
Eric Laurent3a4311c2014-03-17 12:00:47 -0700320 DeviceVector *deviceVector;
321
Eric Laurente552edb2014-03-10 17:42:56 -0700322 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700323 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700324 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 deviceVector = &mAvailableInputDevices;
326 } else {
327 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
328 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700329 }
Eric Laurent634b7142016-04-20 13:48:02 -0700330
331 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
332 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800333}
334
Eric Laurentdc462862016-07-19 12:29:53 -0700335uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700336{
337 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700338 status_t status;
339 audio_patch_handle_t afPatchHandle;
340 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700341 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700342
Eric Laurent87ffa392015-05-22 10:32:38 -0700343 if(!hasPrimaryOutput()) {
Eric Laurentdc462862016-07-19 12:29:53 -0700344 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700345 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800346 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700347 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
348
349 // release existing RX patch if any
350 if (mCallRxPatch != 0) {
351 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
352 mCallRxPatch.clear();
353 }
354 // release TX patch if any
355 if (mCallTxPatch != 0) {
356 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
357 mCallTxPatch.clear();
358 }
359
360 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
361 // via setOutputDevice() on primary output.
362 // Otherwise, create two audio patches for TX and RX path.
363 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700364 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700365 // If the TX device is also on the primary HW module, setOutputDevice() will take care
366 // of it due to legacy implementation. If not, create a patch.
367 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
368 == AUDIO_DEVICE_NONE) {
369 createTxPatch = true;
370 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700371 } else { // create RX path audio patch
372 struct audio_patch patch;
373
374 patch.num_sources = 1;
375 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700376 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
377 ALOG_ASSERT(!deviceList.isEmpty(),
378 "updateCallRouting() selected device not in output device list");
379 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
380 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
381 ALOG_ASSERT(!deviceList.isEmpty(),
382 "updateCallRouting() no telephony RX device");
383 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
384
385 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
386 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
387
388 // request to reuse existing output stream if one is already opened to reach the RX device
389 SortedVector<audio_io_handle_t> outputs =
390 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700391 audio_io_handle_t output = selectOutput(outputs,
392 AUDIO_OUTPUT_FLAG_NONE,
393 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700394 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700395 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700396 ALOG_ASSERT(!outputDesc->isDuplicated(),
397 "updateCallRouting() RX device output is duplicated");
398 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700399 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700400 patch.num_sources = 2;
401 }
402
403 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700404 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700405 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
406 status);
407 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100408 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700409 mCallRxPatch->mAfPatchHandle = afPatchHandle;
410 mCallRxPatch->mUid = mUidCached;
411 }
412 createTxPatch = true;
413 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700414 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700415 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700416
Eric Laurentc2730ba2014-07-20 15:47:07 -0700417 patch.num_sources = 1;
418 patch.num_sinks = 1;
419 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
420 ALOG_ASSERT(!deviceList.isEmpty(),
421 "updateCallRouting() selected device not in input device list");
422 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
423 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
424 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
425 ALOG_ASSERT(!deviceList.isEmpty(),
426 "updateCallRouting() no telephony TX device");
427 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
428 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
429
430 SortedVector<audio_io_handle_t> outputs =
431 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700432 audio_io_handle_t output = selectOutput(outputs,
433 AUDIO_OUTPUT_FLAG_NONE,
434 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 // request to reuse existing output stream if one is already opened to reach the TX
436 // path output device
437 if (output != AUDIO_IO_HANDLE_NONE) {
438 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
439 ALOG_ASSERT(!outputDesc->isDuplicated(),
440 "updateCallRouting() RX device output is duplicated");
441 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700442 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700443 patch.num_sources = 2;
444 }
445
Eric Laurentc0a889f2015-10-14 14:36:34 -0700446 // terminate active capture if on the same HW module as the call TX source device
447 // FIXME: would be better to refine to only inputs whose profile connects to the
448 // call TX device but this information is not in the audio patch and logic here must be
449 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800450 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
451 for (size_t i = 0; i < activeInputs.size(); i++) {
452 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
453 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
454 AudioSessionCollection activeSessions =
455 activeDesc->getAudioSessions(true /*activeOnly*/);
456 for (size_t j = 0; j < activeSessions.size(); j++) {
457 audio_session_t activeSession = activeSessions.keyAt(j);
458 stopInput(activeDesc->mIoHandle, activeSession);
459 releaseInput(activeDesc->mIoHandle, activeSession);
460 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700461 }
462 }
463
Eric Laurentc2730ba2014-07-20 15:47:07 -0700464 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700465 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700466 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
467 status);
468 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100469 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700470 mCallTxPatch->mAfPatchHandle = afPatchHandle;
471 mCallTxPatch->mUid = mUidCached;
472 }
473 }
Eric Laurentdc462862016-07-19 12:29:53 -0700474
475 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700476}
477
Eric Laurente0720872014-03-11 09:30:41 -0700478void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700479{
480 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100481 // store previous phone state for management of sonification strategy below
482 int oldState = mEngine->getPhoneState();
483
484 if (mEngine->setPhoneState(state) != NO_ERROR) {
485 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700486 return;
487 }
François Gaffie2110e042015-03-24 08:41:51 +0100488 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700489 // if leaving call state, handle special case of active streams
490 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700491 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700492 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800493 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700494 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700495 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800496
Eric Laurent63dea1d2015-07-02 17:10:28 -0700497 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800498 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700499 }
500
François Gaffie2110e042015-03-24 08:41:51 +0100501 /**
502 * Switching to or from incall state or switching between telephony and VoIP lead to force
503 * routing command.
504 */
505 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
506 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700507
508 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700509 checkA2dpSuspend();
510 checkOutputForAllStrategies();
511 updateDevicesAndOutputs();
512
Eric Laurente552edb2014-03-10 17:42:56 -0700513 int delayMs = 0;
514 if (isStateInCall(state)) {
515 nsecs_t sysTime = systemTime();
516 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700517 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700518 // mute media and sonification strategies and delay device switch by the largest
519 // latency of any output where either strategy is active.
520 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100521 if ((isStrategyActive(desc, STRATEGY_MEDIA,
522 SONIFICATION_HEADSET_MUSIC_DELAY,
523 sysTime) ||
524 isStrategyActive(desc, STRATEGY_SONIFICATION,
525 SONIFICATION_HEADSET_MUSIC_DELAY,
526 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700527 (delayMs < (int)desc->latency()*2)) {
528 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700529 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700530 setStrategyMute(STRATEGY_MEDIA, true, desc);
531 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700532 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700533 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
534 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700535 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
536 }
537 }
538
Eric Laurent87ffa392015-05-22 10:32:38 -0700539 if (hasPrimaryOutput()) {
540 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
541 // the device returned is not necessarily reachable via this output
542 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
543 // force routing command to audio hardware when ending call
544 // even if no device change is needed
545 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
546 rxDevice = mPrimaryOutput->device();
547 }
Eric Laurente552edb2014-03-10 17:42:56 -0700548
Eric Laurent87ffa392015-05-22 10:32:38 -0700549 if (state == AUDIO_MODE_IN_CALL) {
550 updateCallRouting(rxDevice, delayMs);
551 } else if (oldState == AUDIO_MODE_IN_CALL) {
552 if (mCallRxPatch != 0) {
553 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
554 mCallRxPatch.clear();
555 }
556 if (mCallTxPatch != 0) {
557 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
558 mCallTxPatch.clear();
559 }
560 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
561 } else {
562 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700563 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700564 }
Eric Laurente552edb2014-03-10 17:42:56 -0700565 // if entering in call state, handle special case of active streams
566 // pertaining to sonification strategy see handleIncallSonification()
567 if (isStateInCall(state)) {
568 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800569 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700570 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700571 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700572
573 // force reevaluating accessibility routing when call starts
574 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700575 }
576
577 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700578 if (state == AUDIO_MODE_RINGTONE &&
579 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700580 mLimitRingtoneVolume = true;
581 } else {
582 mLimitRingtoneVolume = false;
583 }
584}
585
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700586audio_mode_t AudioPolicyManager::getPhoneState() {
587 return mEngine->getPhoneState();
588}
589
Eric Laurente0720872014-03-11 09:30:41 -0700590void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700591 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700592{
François Gaffie2110e042015-03-24 08:41:51 +0100593 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700594
François Gaffie2110e042015-03-24 08:41:51 +0100595 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
596 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
597 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700598 }
François Gaffie2110e042015-03-24 08:41:51 +0100599 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
600 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
601 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700602
603 // check for device and output changes triggered by new force usage
604 checkA2dpSuspend();
605 checkOutputForAllStrategies();
606 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800607
Eric Laurentdc462862016-07-19 12:29:53 -0700608 //FIXME: workaround for truncated touch sounds
609 // to be removed when the problem is handled by system UI
610 uint32_t delayMs = 0;
611 uint32_t waitMs = 0;
612 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
613 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
614 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700615 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700617 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700618 }
Eric Laurente552edb2014-03-10 17:42:56 -0700619 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700620 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
621 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
622 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700623 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
624 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurente552edb2014-03-10 17:42:56 -0700626 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700627 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700628 }
629 }
630
Eric Laurentfb66dd92016-01-28 18:32:03 -0800631 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
632 for (size_t i = 0; i < activeInputs.size(); i++) {
633 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
634 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700635 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800636 if (activeDesc->mProfile->getSupportedDevices().types() &
637 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
638 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700639 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800640 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700641 }
Eric Laurente552edb2014-03-10 17:42:56 -0700642 }
Eric Laurente552edb2014-03-10 17:42:56 -0700643}
644
Eric Laurente0720872014-03-11 09:30:41 -0700645void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700646{
647 ALOGV("setSystemProperty() property %s, value %s", property, value);
648}
649
650// Find a direct output profile compatible with the parameters passed, even if the input flags do
651// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800652sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700653 audio_devices_t device,
654 uint32_t samplingRate,
655 audio_format_t format,
656 audio_channel_mask_t channelMask,
657 audio_output_flags_t flags)
658{
Eric Laurent861a6282015-05-18 15:40:16 -0700659 // only retain flags that will drive the direct output profile selection
660 // if explicitly requested
661 static const uint32_t kRelevantFlags =
662 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
663 flags =
664 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
665
666 sp<IOProfile> profile;
667
Eric Laurente552edb2014-03-10 17:42:56 -0700668 for (size_t i = 0; i < mHwModules.size(); i++) {
669 if (mHwModules[i]->mHandle == 0) {
670 continue;
671 }
672 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700673 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
674 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700675 samplingRate, NULL /*updatedSamplingRate*/,
676 format, NULL /*updatedFormat*/,
677 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700678 flags)) {
679 continue;
680 }
681 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100682 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700683 continue;
684 }
685 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100686 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700687 continue;
688 }
689 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100690 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700691 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700692 }
Eric Laurente552edb2014-03-10 17:42:56 -0700693 }
694 }
Eric Laurent861a6282015-05-18 15:40:16 -0700695 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700696}
697
Eric Laurente0720872014-03-11 09:30:41 -0700698audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100699 uint32_t samplingRate,
700 audio_format_t format,
701 audio_channel_mask_t channelMask,
702 audio_output_flags_t flags,
703 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700704{
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700706 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
707 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
708 device, stream, samplingRate, format, channelMask, flags);
709
Eric Laurente83b55d2014-11-14 10:06:21 -0800710 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
711 stream, samplingRate,format, channelMask,
712 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700713}
714
Eric Laurente83b55d2014-11-14 10:06:21 -0800715status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
716 audio_io_handle_t *output,
717 audio_session_t session,
718 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700719 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800720 uint32_t samplingRate,
721 audio_format_t format,
722 audio_channel_mask_t channelMask,
723 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700724 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800725 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700726{
Eric Laurente83b55d2014-11-14 10:06:21 -0800727 audio_attributes_t attributes;
728 if (attr != NULL) {
729 if (!isValidAttributes(attr)) {
730 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
731 attr->usage, attr->content_type, attr->flags,
732 attr->tags);
733 return BAD_VALUE;
734 }
735 attributes = *attr;
736 } else {
737 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
738 ALOGE("getOutputForAttr(): invalid stream type");
739 return BAD_VALUE;
740 }
741 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700742 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700743 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800744 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100745 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800746 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100747 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800748 }
François Gaffie036e1e92015-03-19 10:16:24 +0100749 *stream = streamTypefromAttributesInt(&attributes);
750 *output = desc->mIoHandle;
751 ALOGV("getOutputForAttr() returns output %d", *output);
752 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800753 }
754 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
755 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
756 return BAD_VALUE;
757 }
758
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700759 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
760 " session %d selectedDeviceId %d",
761 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
762 session, selectedDeviceId);
763
764 *stream = streamTypefromAttributesInt(&attributes);
765
766 // Explicit routing?
767 sp<DeviceDescriptor> deviceDesc;
768 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
769 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
770 deviceDesc = mAvailableOutputDevices[i];
771 break;
772 }
773 }
774 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775
Eric Laurente83b55d2014-11-14 10:06:21 -0800776 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700777 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700778
Eric Laurente83b55d2014-11-14 10:06:21 -0800779 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700780 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
781 }
782
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700783 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700784 device, samplingRate, format, channelMask, flags);
785
Eric Laurente83b55d2014-11-14 10:06:21 -0800786 *output = getOutputForDevice(device, session, *stream,
787 samplingRate, format, channelMask,
788 flags, offloadInfo);
789 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700790 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800791 return INVALID_OPERATION;
792 }
Paul McLeanaa981192015-03-21 09:55:15 -0700793
Eric Laurente83b55d2014-11-14 10:06:21 -0800794 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700795}
796
797audio_io_handle_t AudioPolicyManager::getOutputForDevice(
798 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800799 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700800 audio_stream_type_t stream,
801 uint32_t samplingRate,
802 audio_format_t format,
803 audio_channel_mask_t channelMask,
804 audio_output_flags_t flags,
805 const audio_offload_info_t *offloadInfo)
806{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700807 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700808 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700809
Eric Laurente552edb2014-03-10 17:42:56 -0700810#ifdef AUDIO_POLICY_TEST
811 if (mCurOutput != 0) {
812 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
813 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
814
815 if (mTestOutputs[mCurOutput] == 0) {
816 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700817 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
818 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700819 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700820 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700821 outputDesc->mFlags =
822 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700823 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700824 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
825 config.sample_rate = mTestSamplingRate;
826 config.channel_mask = mTestChannels;
827 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700828 if (offloadInfo != NULL) {
829 config.offload_info = *offloadInfo;
830 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700831 status = mpClientInterface->openOutput(0,
832 &mTestOutputs[mCurOutput],
833 &config,
834 &outputDesc->mDevice,
835 String8(""),
836 &outputDesc->mLatency,
837 outputDesc->mFlags);
838 if (status == NO_ERROR) {
839 outputDesc->mSamplingRate = config.sample_rate;
840 outputDesc->mFormat = config.format;
841 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700842 AudioParameter outputCmd = AudioParameter();
843 outputCmd.addInt(String8("set_id"),mCurOutput);
844 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
845 addOutput(mTestOutputs[mCurOutput], outputDesc);
846 }
847 }
848 return mTestOutputs[mCurOutput];
849 }
850#endif //AUDIO_POLICY_TEST
851
852 // open a direct output if required by specified parameters
853 //force direct flag if offload flag is set: offloading implies a direct output stream
854 // and all common behaviors are driven by checking only the direct flag
855 // this should normally be set appropriately in the policy configuration file
856 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700857 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700858 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700859 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
860 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
861 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 // only allow deep buffering for music stream type
863 if (stream != AUDIO_STREAM_MUSIC) {
864 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700865 } else if (/* stream == AUDIO_STREAM_MUSIC && */
866 flags == AUDIO_OUTPUT_FLAG_NONE &&
867 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
868 // use DEEP_BUFFER as default output for music stream type
869 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800870 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700871 if (stream == AUDIO_STREAM_TTS) {
872 flags = AUDIO_OUTPUT_FLAG_TTS;
873 }
Eric Laurente552edb2014-03-10 17:42:56 -0700874
Eric Laurentb732cf52014-09-24 19:08:21 -0700875 sp<IOProfile> profile;
876
877 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700878 // and not explicitly requested
879 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800880 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700881 audio_channel_count_from_out_mask(channelMask) <= 2) {
882 goto non_direct_output;
883 }
884
Andy Hung2ddee192015-12-18 17:34:44 -0800885 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
886 // This prevents creating an offloaded track and tearing it down immediately after start
887 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700888 // FIXME: We should check the audio session here but we do not have it in this context.
889 // This may prevent offloading in rare situations where effects are left active by apps
890 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700891
Eric Laurente552edb2014-03-10 17:42:56 -0700892 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800893 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700894 profile = getProfileForDirectOutput(device,
895 samplingRate,
896 format,
897 channelMask,
898 (audio_output_flags_t)flags);
899 }
900
Eric Laurent1c333e22014-05-20 10:48:17 -0700901 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700902 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700903
904 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700905 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700906 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
907 outputDesc = desc;
908 // reuse direct output if currently open and configured with same parameters
909 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800910 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700911 (channelMask == outputDesc->mChannelMask)) {
912 outputDesc->mDirectOpenCount++;
913 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
914 return mOutputs.keyAt(i);
915 }
916 }
917 }
918 // close direct output if currently open and configured with different parameters
919 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700920 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
Eric Laurent861a6282015-05-18 15:40:16 -0700922
923 // if the selected profile is offloaded and no offload info was specified,
924 // create a default one
925 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100926 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
928 defaultOffloadInfo.sample_rate = samplingRate;
929 defaultOffloadInfo.channel_mask = channelMask;
930 defaultOffloadInfo.format = format;
931 defaultOffloadInfo.stream_type = stream;
932 defaultOffloadInfo.bit_rate = 0;
933 defaultOffloadInfo.duration_us = -1;
934 defaultOffloadInfo.has_video = true; // conservative
935 defaultOffloadInfo.is_streaming = true; // likely
936 offloadInfo = &defaultOffloadInfo;
937 }
938
Eric Laurentc75307b2015-03-17 15:29:32 -0700939 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700940 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700941 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700942 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700943 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
944 config.sample_rate = samplingRate;
945 config.channel_mask = channelMask;
946 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700947 if (offloadInfo != NULL) {
948 config.offload_info = *offloadInfo;
949 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700950 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700951 &output,
952 &config,
953 &outputDesc->mDevice,
954 String8(""),
955 &outputDesc->mLatency,
956 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700957
958 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700959 if (status != NO_ERROR ||
960 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800961 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700962 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700963 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
964 "format %d %d, channelMask %04x %04x", output, samplingRate,
965 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
966 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700967 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700968 mpClientInterface->closeOutput(output);
969 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800970 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800971 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800972 goto non_direct_output;
973 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700974 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700975 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700976 outputDesc->mSamplingRate = config.sample_rate;
977 outputDesc->mChannelMask = config.channel_mask;
978 outputDesc->mFormat = config.format;
979 outputDesc->mRefCount[stream] = 0;
980 outputDesc->mStopTime[stream] = 0;
981 outputDesc->mDirectOpenCount = 1;
982
Eric Laurente552edb2014-03-10 17:42:56 -0700983 audio_io_handle_t srcOutput = getOutputForEffect();
984 addOutput(output, outputDesc);
985 audio_io_handle_t dstOutput = getOutputForEffect();
986 if (dstOutput == output) {
987 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
988 }
989 mPreviousOutputs = mOutputs;
990 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700991 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700992 return output;
993 }
994
Eric Laurentb732cf52014-09-24 19:08:21 -0700995non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700996
997 // A request for HW A/V sync cannot fallback to a mixed output because time
998 // stamps are embedded in audio data
999 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1000 return AUDIO_IO_HANDLE_NONE;
1001 }
1002
Eric Laurente552edb2014-03-10 17:42:56 -07001003 // ignoring channel mask due to downmix capability in mixer
1004
1005 // open a non direct output
1006
1007 // for non direct outputs, only PCM is supported
1008 if (audio_is_linear_pcm(format)) {
1009 // get which output is suitable for the specified stream. The actual
1010 // routing change will happen when startOutput() will be called
1011 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1012
Eric Laurent8838a382014-09-08 16:44:28 -07001013 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1014 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1015 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001016 }
1017 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1018 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1019
Paul McLeanaa981192015-03-21 09:55:15 -07001020 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001021
1022 return output;
1023}
1024
Eric Laurente0720872014-03-11 09:30:41 -07001025audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001026 audio_output_flags_t flags,
1027 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001028{
1029 // select one output among several that provide a path to a particular device or set of
1030 // devices (the list was previously build by getOutputsForDevice()).
1031 // The priority is as follows:
1032 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001033 // 2: the output with the bit depth the closest to the requested one
1034 // 3: the primary output
1035 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001036
1037 if (outputs.size() == 0) {
1038 return 0;
1039 }
1040 if (outputs.size() == 1) {
1041 return outputs[0];
1042 }
1043
1044 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001045 audio_io_handle_t outputForFlags = 0;
1046 audio_io_handle_t outputForPrimary = 0;
1047 audio_io_handle_t outputForFormat = 0;
1048 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1049 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001050
1051 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001052 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001053 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001054 // if a valid format is specified, skip output if not compatible
1055 if (format != AUDIO_FORMAT_INVALID) {
1056 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001057 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001058 continue;
1059 }
1060 } else if (!audio_is_linear_pcm(format)) {
1061 continue;
1062 }
Eric Laurente6930022016-02-11 10:20:40 -08001063 if (AudioPort::isBetterFormatMatch(
1064 outputDesc->mFormat, bestFormat, format)) {
1065 outputForFormat = outputs[i];
1066 bestFormat = outputDesc->mFormat;
1067 }
Eric Laurent8838a382014-09-08 16:44:28 -07001068 }
1069
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001070 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001071 if (commonFlags >= maxCommonFlags) {
1072 if (commonFlags == maxCommonFlags) {
1073 if (AudioPort::isBetterFormatMatch(
1074 outputDesc->mFormat, bestFormatForFlags, format)) {
1075 outputForFlags = outputs[i];
1076 bestFormatForFlags = outputDesc->mFormat;
1077 }
1078 } else {
1079 outputForFlags = outputs[i];
1080 maxCommonFlags = commonFlags;
1081 bestFormatForFlags = outputDesc->mFormat;
1082 }
Eric Laurente552edb2014-03-10 17:42:56 -07001083 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1084 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001085 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001086 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
1088 }
1089 }
1090
Eric Laurente6930022016-02-11 10:20:40 -08001091 if (outputForFlags != 0) {
1092 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001093 }
Eric Laurente6930022016-02-11 10:20:40 -08001094 if (outputForFormat != 0) {
1095 return outputForFormat;
1096 }
1097 if (outputForPrimary != 0) {
1098 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001099 }
1100
1101 return outputs[0];
1102}
1103
Eric Laurente0720872014-03-11 09:30:41 -07001104status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001105 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001106 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001107{
Paul McLeanaa981192015-03-21 09:55:15 -07001108 ALOGV("startOutput() output %d, stream %d, session %d",
1109 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001110 ssize_t index = mOutputs.indexOfKey(output);
1111 if (index < 0) {
1112 ALOGW("startOutput() unknown output %d", output);
1113 return BAD_VALUE;
1114 }
1115
Eric Laurentc75307b2015-03-17 15:29:32 -07001116 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1117
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001118 // Routing?
1119 mOutputRoutes.incRouteActivity(session);
1120
Eric Laurentc75307b2015-03-17 15:29:32 -07001121 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001122 AudioMix *policyMix = NULL;
1123 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001124 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001125 policyMix = outputDesc->mPolicyMix;
1126 address = policyMix->mDeviceAddress.string();
1127 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1128 newDevice = policyMix->mDeviceType;
1129 } else {
1130 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1131 }
Eric Laurent493404d2015-04-21 15:07:36 -07001132 } else if (mOutputRoutes.hasRouteChanged(session)) {
1133 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001134 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001135 } else {
1136 newDevice = AUDIO_DEVICE_NONE;
1137 }
1138
1139 uint32_t delayMs = 0;
1140
Eric Laurentc40d9692016-04-13 19:14:13 -07001141 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001142
1143 if (status != NO_ERROR) {
1144 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001145 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001146 }
1147 // Automatically enable the remote submix input when output is started on a re routing mix
1148 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001149 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1150 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001151 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1152 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001153 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001154 "remote-submix");
1155 }
1156
1157 if (delayMs != 0) {
1158 usleep(delayMs * 1000);
1159 }
1160
1161 return status;
1162}
1163
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001164status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001165 audio_stream_type_t stream,
1166 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001167 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001168 uint32_t *delayMs)
1169{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001170 // cannot start playback of STREAM_TTS if any other output is being used
1171 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001172
1173 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001174 if (stream == AUDIO_STREAM_TTS) {
1175 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001176 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001177 return INVALID_OPERATION;
1178 } else {
1179 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1180 }
1181 } else {
1182 // some playback other than beacon starts
1183 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1184 }
1185
Eric Laurent77305a62016-07-25 16:39:22 -07001186 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001187 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001188 bool force = !outputDesc->isActive() &&
1189 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001190
Eric Laurente552edb2014-03-10 17:42:56 -07001191 // increment usage count for this stream on the requested output:
1192 // NOTE that the usage count is the same for duplicated output and hardware output which is
1193 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1194 outputDesc->changeRefCount(stream, 1);
1195
Eric Laurent493404d2015-04-21 15:07:36 -07001196 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001197 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001198 if (device == AUDIO_DEVICE_NONE) {
1199 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001200 }
Eric Laurente552edb2014-03-10 17:42:56 -07001201 routing_strategy strategy = getStrategy(stream);
1202 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001203 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1204 (beaconMuteLatency > 0);
1205 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001206 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001207 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001208 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001209 // force a device change if any other output is:
1210 // - managed by the same hw module
1211 // - has a current device selection that differs from selected device.
1212 // - supports currently selected device
1213 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001214 // In this case, the audio HAL must receive the new device selection so that it can
1215 // change the device currently selected by the other active output.
1216 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001217 desc->device() != device &&
1218 desc->supportedDevices() & device &&
1219 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001220 force = true;
1221 }
1222 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001223 // a notification so that audio focus effect can propagate, or that a mute/unmute
1224 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001225 uint32_t latency = desc->latency();
1226 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1227 waitMs = latency;
1228 }
1229 }
1230 }
Eric Laurentdc462862016-07-19 12:29:53 -07001231 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001232
1233 // handle special case for sonification while in call
1234 if (isInCall()) {
1235 handleIncallSonification(stream, true, false);
1236 }
1237
1238 // apply volume rules for current stream and device if necessary
1239 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001240 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001241 outputDesc,
1242 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001243
1244 // update the outputs if starting an output with a stream that can affect notification
1245 // routing
1246 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001247
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001248 // force reevaluating accessibility routing when ringtone or alarm starts
1249 if (strategy == STRATEGY_SONIFICATION) {
1250 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1251 }
Eric Laurentdc462862016-07-19 12:29:53 -07001252
1253 if (waitMs > muteWaitMs) {
1254 *delayMs = waitMs - muteWaitMs;
1255 }
Eric Laurente552edb2014-03-10 17:42:56 -07001256 }
Eric Laurentdc462862016-07-19 12:29:53 -07001257
Eric Laurente552edb2014-03-10 17:42:56 -07001258 return NO_ERROR;
1259}
1260
1261
Eric Laurente0720872014-03-11 09:30:41 -07001262status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001263 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001264 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001265{
1266 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1267 ssize_t index = mOutputs.indexOfKey(output);
1268 if (index < 0) {
1269 ALOGW("stopOutput() unknown output %d", output);
1270 return BAD_VALUE;
1271 }
1272
Eric Laurentc75307b2015-03-17 15:29:32 -07001273 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001274
Eric Laurentc75307b2015-03-17 15:29:32 -07001275 if (outputDesc->mRefCount[stream] == 1) {
1276 // Automatically disable the remote submix input when output is stopped on a
1277 // re routing mix of type MIX_TYPE_RECORDERS
1278 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1279 outputDesc->mPolicyMix != NULL &&
1280 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1281 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1282 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001283 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001284 "remote-submix");
1285 }
1286 }
1287
1288 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001289 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001290 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001291 int activityCount = mOutputRoutes.decRouteActivity(session);
1292 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1293
1294 if (forceDeviceUpdate) {
1295 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1296 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001297 }
1298
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001299 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001300}
1301
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001302status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001303 audio_stream_type_t stream,
1304 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001305{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001306 // always handle stream stop, check which stream type is stopping
1307 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1308
Eric Laurente552edb2014-03-10 17:42:56 -07001309 // handle special case for sonification while in call
1310 if (isInCall()) {
1311 handleIncallSonification(stream, false, false);
1312 }
1313
1314 if (outputDesc->mRefCount[stream] > 0) {
1315 // decrement usage count of this stream on the output
1316 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001317
Eric Laurente552edb2014-03-10 17:42:56 -07001318 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001319 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001320 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001321 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001322 // delay the device switch by twice the latency because stopOutput() is executed when
1323 // the track stop() command is received and at that time the audio track buffer can
1324 // still contain data that needs to be drained. The latency only covers the audio HAL
1325 // and kernel buffers. Also the latency does not always include additional delay in the
1326 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001327 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001328
1329 // force restoring the device selection on other active outputs if it differs from the
1330 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001331 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001332 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001333 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001334 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001335 desc->isActive() &&
1336 outputDesc->sharesHwModuleWith(desc) &&
1337 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001338 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1339 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001341 newDevice2,
1342 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001343 delayMs);
1344 // re-apply device specific volume if not done by setOutputDevice()
1345 if (!force) {
1346 applyStreamVolumes(desc, newDevice2, delayMs);
1347 }
Eric Laurente552edb2014-03-10 17:42:56 -07001348 }
1349 }
1350 // update the outputs if stopping one with a stream that can affect notification routing
1351 handleNotificationRoutingForStream(stream);
1352 }
1353 return NO_ERROR;
1354 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001355 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001356 return INVALID_OPERATION;
1357 }
1358}
1359
Eric Laurente83b55d2014-11-14 10:06:21 -08001360void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001361 audio_stream_type_t stream __unused,
1362 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001363{
1364 ALOGV("releaseOutput() %d", output);
1365 ssize_t index = mOutputs.indexOfKey(output);
1366 if (index < 0) {
1367 ALOGW("releaseOutput() releasing unknown output %d", output);
1368 return;
1369 }
1370
1371#ifdef AUDIO_POLICY_TEST
1372 int testIndex = testOutputIndex(output);
1373 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001374 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001375 if (outputDesc->isActive()) {
1376 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001377 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001378 mTestOutputs[testIndex] = 0;
1379 }
1380 return;
1381 }
1382#endif //AUDIO_POLICY_TEST
1383
Paul McLeanaa981192015-03-21 09:55:15 -07001384 // Routing
1385 mOutputRoutes.removeRoute(session);
1386
Eric Laurentc75307b2015-03-17 15:29:32 -07001387 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001388 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001389 if (desc->mDirectOpenCount <= 0) {
1390 ALOGW("releaseOutput() invalid open count %d for output %d",
1391 desc->mDirectOpenCount, output);
1392 return;
1393 }
1394 if (--desc->mDirectOpenCount == 0) {
1395 closeOutput(output);
1396 // If effects where present on the output, audioflinger moved them to the primary
1397 // output by default: move them back to the appropriate output.
1398 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001399 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001400 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1401 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001402 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001403 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001404 }
1405 }
1406}
1407
1408
Eric Laurentcaf7f482014-11-25 17:50:47 -08001409status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1410 audio_io_handle_t *input,
1411 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001412 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001413 uint32_t samplingRate,
1414 audio_format_t format,
1415 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001416 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001417 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001418 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001419{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001420 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1421 "session %d, flags %#x",
1422 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001423
Eric Laurentcaf7f482014-11-25 17:50:47 -08001424 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001425 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001426
Eric Laurent275e8e92014-11-30 15:14:47 -08001427 audio_devices_t device;
1428 // handle legacy remote submix case where the address was not always specified
1429 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001430 audio_source_t inputSource = attr->source;
1431 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001432 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001433
Eric Laurentc447ded2015-01-06 08:47:05 -08001434 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1435 inputSource = AUDIO_SOURCE_MIC;
1436 }
1437 halInputSource = inputSource;
1438
Paul McLean466dc8e2015-04-17 13:15:36 -06001439 // Explicit routing?
1440 sp<DeviceDescriptor> deviceDesc;
1441 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1442 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1443 deviceDesc = mAvailableInputDevices[i];
1444 break;
1445 }
1446 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001447 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001448
Eric Laurentc447ded2015-01-06 08:47:05 -08001449 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001450 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001451 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001452 if (ret != NO_ERROR) {
1453 return ret;
1454 }
1455 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001456 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1457 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001458 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001459 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001460 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001461 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001462 return BAD_VALUE;
1463 }
Eric Laurentc722f302014-12-10 11:21:49 -08001464 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001465 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001466 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1467 // there is an external policy, but this input is attached to a mix of recorders,
1468 // meaning it receives audio injected into the framework, so the recorder doesn't
1469 // know about it and is therefore considered "legacy"
1470 *inputType = API_INPUT_LEGACY;
1471 } else {
1472 // recording a mix of players defined by an external policy, we're rerouting for
1473 // an external policy
1474 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1475 }
Eric Laurentc722f302014-12-10 11:21:49 -08001476 } else if (audio_is_remote_submix_device(device)) {
1477 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001478 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001479 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1480 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001481 } else {
1482 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001483 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001484
Eric Laurent599c7582015-12-07 18:05:55 -08001485 }
1486
1487 *input = getInputForDevice(device, address, session, uid, inputSource,
1488 samplingRate, format, channelMask, flags,
1489 policyMix);
1490 if (*input == AUDIO_IO_HANDLE_NONE) {
1491 mInputRoutes.removeRoute(session);
1492 return INVALID_OPERATION;
1493 }
1494 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1495 return NO_ERROR;
1496}
1497
1498
1499audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1500 String8 address,
1501 audio_session_t session,
1502 uid_t uid,
1503 audio_source_t inputSource,
1504 uint32_t samplingRate,
1505 audio_format_t format,
1506 audio_channel_mask_t channelMask,
1507 audio_input_flags_t flags,
1508 AudioMix *policyMix)
1509{
1510 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1511 audio_source_t halInputSource = inputSource;
1512 bool isSoundTrigger = false;
1513
1514 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1515 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1516 if (index >= 0) {
1517 input = mSoundTriggerSessions.valueFor(session);
1518 isSoundTrigger = true;
1519 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1520 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1521 } else {
1522 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001523 }
1524 }
1525
Andy Hungf129b032015-04-07 13:45:50 -07001526 // find a compatible input profile (not necessarily identical in parameters)
1527 sp<IOProfile> profile;
1528 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001529 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001530 audio_format_t profileFormat = format;
1531 audio_channel_mask_t profileChannelMask = channelMask;
1532 audio_input_flags_t profileFlags = flags;
1533 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001534 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001535 profileSamplingRate, profileFormat, profileChannelMask,
1536 profileFlags);
1537 if (profile != 0) {
1538 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001539 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1540 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001541 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1542 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1543 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001544 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1545 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001546 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001547 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001548 }
Eric Laurente552edb2014-03-10 17:42:56 -07001549 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001550 // Pick input sampling rate if not specified by client
1551 if (samplingRate == 0) {
1552 samplingRate = profileSamplingRate;
1553 }
Eric Laurente552edb2014-03-10 17:42:56 -07001554
Eric Laurent322b4d22015-04-03 15:57:54 -07001555 if (profile->getModuleHandle() == 0) {
1556 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001557 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001558 }
1559
Eric Laurent599c7582015-12-07 18:05:55 -08001560 sp<AudioSession> audioSession = new AudioSession(session,
1561 inputSource,
1562 format,
1563 samplingRate,
1564 channelMask,
1565 flags,
1566 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001567 isSoundTrigger,
1568 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001569
Eric Laurentfb66dd92016-01-28 18:32:03 -08001570
Eric Laurent599c7582015-12-07 18:05:55 -08001571 // reuse an open input if possible
1572 for (size_t i = 0; i < mInputs.size(); i++) {
1573 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001574 // reuse input if:
1575 // - it shares the same profile
1576 // AND
1577 // - it is not a reroute submix input
1578 // AND
1579 // - it is: not used for sound trigger
1580 // OR
1581 // used for sound trigger and all clients use the same session ID
1582 //
1583 if ((profile == desc->mProfile) &&
1584 (isSoundTrigger == desc->isSoundTrigger()) &&
1585 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001586
1587 sp<AudioSession> as = desc->getAudioSession(session);
1588 if (as != 0) {
1589 // do not allow unmatching properties on same session
1590 if (as->matches(audioSession)) {
1591 as->changeOpenCount(1);
1592 } else {
1593 ALOGW("getInputForDevice() record with different attributes"
1594 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001595 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001596 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001597 } else if (isSoundTrigger) {
1598 break;
1599 }
1600 // force close input if current source is now the highest priority request on this input
1601 // and current input properties are not exactly as requested.
1602 if ((desc->mSamplingRate != samplingRate ||
1603 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001604 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001605 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1606 source_priority(inputSource))) {
1607 ALOGV("%s: ", __FUNCTION__);
1608 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1609 for (size_t j = 0; j < sessions.size(); j++) {
1610 audio_session_t currentSession = sessions.keyAt(j);
1611 stopInput(desc->mIoHandle, currentSession);
1612 releaseInput(desc->mIoHandle, currentSession);
1613 }
1614 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001615 } else {
1616 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001617 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1618 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001619 }
Eric Laurent599c7582015-12-07 18:05:55 -08001620 }
1621 }
Eric Laurent599c7582015-12-07 18:05:55 -08001622
Eric Laurentcf2c0212014-07-25 16:20:43 -07001623 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001624 config.sample_rate = profileSamplingRate;
1625 config.channel_mask = profileChannelMask;
1626 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001627
Eric Laurent322b4d22015-04-03 15:57:54 -07001628 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001629 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001630 &config,
1631 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001632 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001633 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001634 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001635
1636 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001637 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001638 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001639 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001640 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001641 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1642 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001643 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001644 if (input != AUDIO_IO_HANDLE_NONE) {
1645 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001646 }
Eric Laurent599c7582015-12-07 18:05:55 -08001647 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001648 }
1649
Eric Laurent1f2f2232014-06-02 12:01:23 -07001650 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001651 inputDesc->mSamplingRate = profileSamplingRate;
1652 inputDesc->mFormat = profileFormat;
1653 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001654 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001655 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001656 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001657
Eric Laurent599c7582015-12-07 18:05:55 -08001658 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001659 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001660
Eric Laurent599c7582015-12-07 18:05:55 -08001661 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001662}
1663
Eric Laurentfb66dd92016-01-28 18:32:03 -08001664bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1665 const sp<AudioSession>& audioSession)
1666{
1667 // Do not allow capture if an active voice call is using a software patch and
1668 // the call TX source device is on the same HW module.
1669 // FIXME: would be better to refine to only inputs whose profile connects to the
1670 // call TX device but this information is not in the audio patch
1671 if (mCallTxPatch != 0 &&
1672 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1673 return false;
1674 }
1675
1676 // starting concurrent capture is enabled if:
1677 // 1) capturing for re-routing
1678 // 2) capturing for HOTWORD source
1679 // 3) capturing for FM TUNER source
1680 // 3) All other active captures are either for re-routing or HOTWORD
1681
1682 if (is_virtual_input_device(inputDesc->mDevice) ||
1683 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1684 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1685 return true;
1686 }
1687
1688 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1689 for (size_t i = 0; i < activeInputs.size(); i++) {
1690 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1691 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1692 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1693 !is_virtual_input_device(activeInput->mDevice)) {
1694 return false;
1695 }
1696 }
1697
1698 return true;
1699}
1700
1701
Eric Laurent4dc68062014-07-28 17:26:49 -07001702status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001703 audio_session_t session,
1704 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001705{
1706 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001707 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001708 ssize_t index = mInputs.indexOfKey(input);
1709 if (index < 0) {
1710 ALOGW("startInput() unknown input %d", input);
1711 return BAD_VALUE;
1712 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001713 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001714
Eric Laurent599c7582015-12-07 18:05:55 -08001715 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1716 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001717 ALOGW("startInput() unknown session %d on input %d", session, input);
1718 return BAD_VALUE;
1719 }
1720
Eric Laurentfb66dd92016-01-28 18:32:03 -08001721 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1722 ALOGW("startInput(%d) failed: other input already started", input);
1723 return INVALID_OPERATION;
1724 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001725
Eric Laurentfb66dd92016-01-28 18:32:03 -08001726 if (isInCall()) {
1727 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1728 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001729 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001730 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001731 }
1732
Eric Laurent313d1e72016-01-29 09:56:57 -08001733 // increment activity count before calling getNewInputDevice() below as only active sessions
1734 // are considered for device selection
1735 audioSession->changeActiveCount(1);
1736
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001737 // Routing?
1738 mInputRoutes.incRouteActivity(session);
1739
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001740 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001741 // indicate active capture to sound trigger service if starting capture from a mic on
1742 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001743 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001744 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001745
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001746 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1747 // if input maps to a dynamic policy with an activity listener, notify of state change
1748 if ((inputDesc->mPolicyMix != NULL)
1749 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1750 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1751 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001752 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001753
Eric Laurentf7c50102016-09-30 15:19:43 -07001754 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1755 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1756 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001757 SoundTrigger::setCaptureState(true);
1758 }
1759
1760 // automatically enable the remote submix output when input is started if not
1761 // used by a policy mix of type MIX_TYPE_RECORDERS
1762 // For remote submix (a virtual device), we open only one input per capture request.
1763 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1764 String8 address = String8("");
1765 if (inputDesc->mPolicyMix == NULL) {
1766 address = String8("0");
1767 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1768 address = inputDesc->mPolicyMix->mDeviceAddress;
1769 }
1770 if (address != "") {
1771 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1773 address, "remote-submix");
1774 }
Eric Laurentc722f302014-12-10 11:21:49 -08001775 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001776 }
Eric Laurente552edb2014-03-10 17:42:56 -07001777 }
1778
Eric Laurent599c7582015-12-07 18:05:55 -08001779 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001780
Eric Laurente552edb2014-03-10 17:42:56 -07001781 return NO_ERROR;
1782}
1783
Eric Laurent4dc68062014-07-28 17:26:49 -07001784status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1785 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001786{
1787 ALOGV("stopInput() input %d", input);
1788 ssize_t index = mInputs.indexOfKey(input);
1789 if (index < 0) {
1790 ALOGW("stopInput() unknown input %d", input);
1791 return BAD_VALUE;
1792 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001793 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001794
Eric Laurent599c7582015-12-07 18:05:55 -08001795 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001796 if (index < 0) {
1797 ALOGW("stopInput() unknown session %d on input %d", session, input);
1798 return BAD_VALUE;
1799 }
1800
Eric Laurent599c7582015-12-07 18:05:55 -08001801 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001802 ALOGW("stopInput() input %d already stopped", input);
1803 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001804 }
1805
Eric Laurent599c7582015-12-07 18:05:55 -08001806 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001807
1808 // Routing?
1809 mInputRoutes.decRouteActivity(session);
1810
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001811 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001812
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001813 if (inputDesc->isActive()) {
1814 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1815 } else {
1816 // if input maps to a dynamic policy with an activity listener, notify of state change
1817 if ((inputDesc->mPolicyMix != NULL)
1818 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1819 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1820 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001821 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001822
1823 // automatically disable the remote submix output when input is stopped if not
1824 // used by a policy mix of type MIX_TYPE_RECORDERS
1825 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1826 String8 address = String8("");
1827 if (inputDesc->mPolicyMix == NULL) {
1828 address = String8("0");
1829 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1830 address = inputDesc->mPolicyMix->mDeviceAddress;
1831 }
1832 if (address != "") {
1833 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1834 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1835 address, "remote-submix");
1836 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001837 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001838
Eric Laurentf7c50102016-09-30 15:19:43 -07001839 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001840 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001841
Eric Laurentf7c50102016-09-30 15:19:43 -07001842 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1843 // primary HW module
1844 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1845 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1846 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001847 SoundTrigger::setCaptureState(false);
1848 }
1849 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001850 }
Eric Laurente552edb2014-03-10 17:42:56 -07001851 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001852 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001853}
1854
Eric Laurent4dc68062014-07-28 17:26:49 -07001855void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1856 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001857{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001858
Eric Laurente552edb2014-03-10 17:42:56 -07001859 ALOGV("releaseInput() %d", input);
1860 ssize_t index = mInputs.indexOfKey(input);
1861 if (index < 0) {
1862 ALOGW("releaseInput() releasing unknown input %d", input);
1863 return;
1864 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001865
1866 // Routing
1867 mInputRoutes.removeRoute(session);
1868
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001869 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1870 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001871
Eric Laurent599c7582015-12-07 18:05:55 -08001872 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001873 if (index < 0) {
1874 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1875 return;
1876 }
Eric Laurent599c7582015-12-07 18:05:55 -08001877
1878 if (audioSession->openCount() == 0) {
1879 ALOGW("releaseInput() invalid open count %d on session %d",
1880 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001881 return;
1882 }
Eric Laurent599c7582015-12-07 18:05:55 -08001883
1884 if (audioSession->changeOpenCount(-1) == 0) {
1885 inputDesc->removeAudioSession(session);
1886 }
1887
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001888 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001889 ALOGV("releaseInput() exit > 0");
1890 return;
1891 }
1892
Eric Laurent05b90f82014-08-27 15:32:29 -07001893 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001894 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001895 ALOGV("releaseInput() exit");
1896}
1897
Eric Laurentd4692962014-05-05 18:13:44 -07001898void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001899 bool patchRemoved = false;
1900
Eric Laurentd4692962014-05-05 18:13:44 -07001901 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001902 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001903 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001904 if (patch_index >= 0) {
1905 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001906 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001907 mAudioPatches.removeItemsAt(patch_index);
1908 patchRemoved = true;
1909 }
Eric Laurentd4692962014-05-05 18:13:44 -07001910 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1911 }
1912 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001913 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001914 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001915
1916 if (patchRemoved) {
1917 mpClientInterface->onAudioPatchListUpdate();
1918 }
Eric Laurentd4692962014-05-05 18:13:44 -07001919}
1920
Eric Laurente0720872014-03-11 09:30:41 -07001921void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001922 int indexMin,
1923 int indexMax)
1924{
1925 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001926 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001927
1928 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001929 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1930 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001931 continue;
1932 }
1933 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001934 }
Eric Laurente552edb2014-03-10 17:42:56 -07001935}
1936
Eric Laurente0720872014-03-11 09:30:41 -07001937status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001938 int index,
1939 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001940{
1941
François Gaffied1ab2bd2015-12-02 18:20:06 +01001942 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1943 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001944 return BAD_VALUE;
1945 }
1946 if (!audio_is_output_device(device)) {
1947 return BAD_VALUE;
1948 }
1949
1950 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001951 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001952
Eric Laurent1fd372e2016-04-06 14:23:53 -07001953 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001954 stream, device, index);
1955
Eric Laurent28d09f02016-03-08 10:43:05 -08001956 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001957 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1958 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001959 continue;
1960 }
1961 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1962 }
Eric Laurente552edb2014-03-10 17:42:56 -07001963
Eric Laurent1fd372e2016-04-06 14:23:53 -07001964 // update volume on all outputs and streams matching the following:
1965 // - The requested stream (or a stream matching for volume control) is active on the output
1966 // - The device (or devices) selected by the strategy corresponding to this stream includes
1967 // the requested device
1968 // - For non default requested device, currently selected device on the output is either the
1969 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001970 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1971 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001972 status_t status = NO_ERROR;
1973 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001974 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1975 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001976 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1977 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001978 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001979 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001980 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1981 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001982 continue;
1983 }
Eric Laurent794fde22016-03-11 09:50:45 -08001984 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07001985 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
1986 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
1987 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001988 continue;
1989 }
Eric Laurente76f29c2016-09-14 17:17:53 -07001990 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001991 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001992 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07001993 applyVolume = (curDevice & curStreamDevice) != 0;
1994 } else {
1995 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
1996 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07001997 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001998
Eric Laurente76f29c2016-09-14 17:17:53 -07001999 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002000 //FIXME: workaround for truncated touch sounds
2001 // delayed volume change for system stream to be removed when the problem is
2002 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002003 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002004 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2005 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002006 if (volStatus != NO_ERROR) {
2007 status = volStatus;
2008 }
2009 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002010 }
Eric Laurente552edb2014-03-10 17:42:56 -07002011 }
2012 return status;
2013}
2014
Eric Laurente0720872014-03-11 09:30:41 -07002015status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002016 int *index,
2017 audio_devices_t device)
2018{
2019 if (index == NULL) {
2020 return BAD_VALUE;
2021 }
2022 if (!audio_is_output_device(device)) {
2023 return BAD_VALUE;
2024 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002025 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002026 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002027 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002028 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2029 }
François Gaffiedfd74092015-03-19 12:10:59 +01002030 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002031
François Gaffied1ab2bd2015-12-02 18:20:06 +01002032 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002033 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2034 return NO_ERROR;
2035}
2036
Eric Laurente0720872014-03-11 09:30:41 -07002037audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002038 const SortedVector<audio_io_handle_t>& outputs)
2039{
2040 // select one output among several suitable for global effects.
2041 // The priority is as follows:
2042 // 1: An offloaded output. If the effect ends up not being offloadable,
2043 // AudioFlinger will invalidate the track and the offloaded output
2044 // will be closed causing the effect to be moved to a PCM output.
2045 // 2: A deep buffer output
2046 // 3: the first output in the list
2047
2048 if (outputs.size() == 0) {
2049 return 0;
2050 }
2051
2052 audio_io_handle_t outputOffloaded = 0;
2053 audio_io_handle_t outputDeepBuffer = 0;
2054
2055 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002056 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002057 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002058 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2059 outputOffloaded = outputs[i];
2060 }
2061 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2062 outputDeepBuffer = outputs[i];
2063 }
2064 }
2065
2066 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2067 outputOffloaded, outputDeepBuffer);
2068 if (outputOffloaded != 0) {
2069 return outputOffloaded;
2070 }
2071 if (outputDeepBuffer != 0) {
2072 return outputDeepBuffer;
2073 }
2074
2075 return outputs[0];
2076}
2077
Eric Laurente0720872014-03-11 09:30:41 -07002078audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002079{
2080 // apply simple rule where global effects are attached to the same output as MUSIC streams
2081
Eric Laurent3b73df72014-03-11 09:06:29 -07002082 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002083 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2084 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2085
2086 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2087 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2088 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2089
2090 return output;
2091}
2092
Eric Laurente0720872014-03-11 09:30:41 -07002093status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002094 audio_io_handle_t io,
2095 uint32_t strategy,
2096 int session,
2097 int id)
2098{
2099 ssize_t index = mOutputs.indexOfKey(io);
2100 if (index < 0) {
2101 index = mInputs.indexOfKey(io);
2102 if (index < 0) {
2103 ALOGW("registerEffect() unknown io %d", io);
2104 return INVALID_OPERATION;
2105 }
2106 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002107 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002108}
2109
Eric Laurentc75307b2015-03-17 15:29:32 -07002110bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2111{
Eric Laurent28d09f02016-03-08 10:43:05 -08002112 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002113 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2114 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002115 continue;
2116 }
2117 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2118 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002119 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002120}
2121
2122bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2123{
2124 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2125}
2126
Eric Laurente0720872014-03-11 09:30:41 -07002127bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002128{
2129 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002130 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002131 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002132 return true;
2133 }
2134 }
2135 return false;
2136}
2137
Eric Laurent275e8e92014-11-30 15:14:47 -08002138// Register a list of custom mixes with their attributes and format.
2139// When a mix is registered, corresponding input and output profiles are
2140// added to the remote submix hw module. The profile contains only the
2141// parameters (sampling rate, format...) specified by the mix.
2142// The corresponding input remote submix device is also connected.
2143//
2144// When a remote submix device is connected, the address is checked to select the
2145// appropriate profile and the corresponding input or output stream is opened.
2146//
2147// When capture starts, getInputForAttr() will:
2148// - 1 look for a mix matching the address passed in attribtutes tags if any
2149// - 2 if none found, getDeviceForInputSource() will:
2150// - 2.1 look for a mix matching the attributes source
2151// - 2.2 if none found, default to device selection by policy rules
2152// At this time, the corresponding output remote submix device is also connected
2153// and active playback use cases can be transferred to this mix if needed when reconnecting
2154// after AudioTracks are invalidated
2155//
2156// When playback starts, getOutputForAttr() will:
2157// - 1 look for a mix matching the address passed in attribtutes tags if any
2158// - 2 if none found, look for a mix matching the attributes usage
2159// - 3 if none found, default to device and output selection by policy rules.
2160
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002161status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002162{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002163 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2164 status_t res = NO_ERROR;
2165
2166 sp<HwModule> rSubmixModule;
2167 // examine each mix's route type
2168 for (size_t i = 0; i < mixes.size(); i++) {
2169 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2170 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2171 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002172 break;
2173 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002174 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2175 // Loop back through "remote submix"
2176 if (rSubmixModule == 0) {
2177 for (size_t j = 0; i < mHwModules.size(); j++) {
2178 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2179 && mHwModules[j]->mHandle != 0) {
2180 rSubmixModule = mHwModules[j];
2181 break;
2182 }
2183 }
2184 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002185
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002186 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002187
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002188 if (rSubmixModule == 0) {
2189 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2190 res = INVALID_OPERATION;
2191 break;
2192 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002193
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002194 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002195
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002196 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002197 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002198 res = INVALID_OPERATION;
2199 break;
2200 }
2201 audio_config_t outputConfig = mixes[i].mFormat;
2202 audio_config_t inputConfig = mixes[i].mFormat;
2203 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2204 // stereo and let audio flinger do the channel conversion if needed.
2205 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2206 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2207 rSubmixModule->addOutputProfile(address, &outputConfig,
2208 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2209 rSubmixModule->addInputProfile(address, &inputConfig,
2210 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002211
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002212 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2213 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2214 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2215 address.string(), "remote-submix");
2216 } else {
2217 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2218 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2219 address.string(), "remote-submix");
2220 }
2221 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002222 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002223 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002224 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2225 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002226
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002227 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002228 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2230 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2231 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2232 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2233 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002234 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2235 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002236 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2237 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002238 } else {
2239 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002240 }
2241 break;
2242 }
2243 }
2244
2245 if (res != NO_ERROR) {
2246 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002247 i, device, address.string());
2248 res = INVALID_OPERATION;
2249 break;
2250 } else if (!foundOutput) {
2251 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2252 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002253 res = INVALID_OPERATION;
2254 break;
2255 }
Eric Laurentc722f302014-12-10 11:21:49 -08002256 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002257 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002258 if (res != NO_ERROR) {
2259 unregisterPolicyMixes(mixes);
2260 }
2261 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002262}
2263
2264status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2265{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002266 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002267 status_t res = NO_ERROR;
2268 sp<HwModule> rSubmixModule;
2269 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002270 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002271 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002272
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002273 if (rSubmixModule == 0) {
2274 for (size_t j = 0; i < mHwModules.size(); j++) {
2275 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2276 && mHwModules[j]->mHandle != 0) {
2277 rSubmixModule = mHwModules[j];
2278 break;
2279 }
2280 }
2281 }
2282 if (rSubmixModule == 0) {
2283 res = INVALID_OPERATION;
2284 continue;
2285 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002286
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002287 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002288
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002289 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2290 res = INVALID_OPERATION;
2291 continue;
2292 }
2293
2294 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2295 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2296 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2297 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2298 address.string(), "remote-submix");
2299 }
2300 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2301 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2302 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2303 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2304 address.string(), "remote-submix");
2305 }
2306 rSubmixModule->removeOutputProfile(address);
2307 rSubmixModule->removeInputProfile(address);
2308
2309 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2310 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2311 res = INVALID_OPERATION;
2312 continue;
2313 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002314 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002315 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002316 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002317}
2318
Eric Laurente552edb2014-03-10 17:42:56 -07002319
Eric Laurente0720872014-03-11 09:30:41 -07002320status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002321{
2322 const size_t SIZE = 256;
2323 char buffer[SIZE];
2324 String8 result;
2325
2326 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2327 result.append(buffer);
2328
Eric Laurent87ffa392015-05-22 10:32:38 -07002329 snprintf(buffer, SIZE, " Primary Output: %d\n",
2330 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002331 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002332 std::string stateLiteral;
2333 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2334 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002335 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002336 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002337 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002338 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002339 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002340 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002341 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002342 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002343 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002344 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002345 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002346 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002347 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002348 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002349 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002350 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2351 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2352 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002353 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2354 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002355 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2356 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002357
François Gaffie2110e042015-03-24 08:41:51 +01002358 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002359
François Gaffie112b0af2015-11-19 16:13:25 +01002360 mAvailableOutputDevices.dump(fd, String8("Available output"));
2361 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002362 mHwModules.dump(fd);
2363 mOutputs.dump(fd);
2364 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002365 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002366 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002367 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002368
2369 return NO_ERROR;
2370}
2371
2372// This function checks for the parameters which can be offloaded.
2373// This can be enhanced depending on the capability of the DSP and policy
2374// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002375bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002376{
2377 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002378 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002379 offloadInfo.sample_rate, offloadInfo.channel_mask,
2380 offloadInfo.format,
2381 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2382 offloadInfo.has_video);
2383
Andy Hung2ddee192015-12-18 17:34:44 -08002384 if (mMasterMono) {
2385 return false; // no offloading if mono is set.
2386 }
2387
Eric Laurente552edb2014-03-10 17:42:56 -07002388 // Check if offload has been disabled
2389 char propValue[PROPERTY_VALUE_MAX];
2390 if (property_get("audio.offload.disable", propValue, "0")) {
2391 if (atoi(propValue) != 0) {
2392 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2393 return false;
2394 }
2395 }
2396
2397 // Check if stream type is music, then only allow offload as of now.
2398 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2399 {
2400 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2401 return false;
2402 }
2403
2404 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002405 const bool allowOffloadWithVideo =
2406 property_get_bool("audio.offload.video", false /* default_value */);
2407 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002408 ALOGV("isOffloadSupported: has_video == true, returning false");
2409 return false;
2410 }
2411
2412 //If duration is less than minimum value defined in property, return false
2413 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2414 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2415 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2416 return false;
2417 }
2418 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2419 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2420 return false;
2421 }
2422
2423 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2424 // creating an offloaded track and tearing it down immediately after start when audioflinger
2425 // detects there is an active non offloadable effect.
2426 // FIXME: We should check the audio session here but we do not have it in this context.
2427 // This may prevent offloading in rare situations where effects are left active by apps
2428 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002429 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002430 return false;
2431 }
2432
2433 // See if there is a profile to support this.
2434 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002435 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002436 offloadInfo.sample_rate,
2437 offloadInfo.format,
2438 offloadInfo.channel_mask,
2439 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002440 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2441 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002442}
2443
Eric Laurent6a94d692014-05-20 11:18:06 -07002444status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2445 audio_port_type_t type,
2446 unsigned int *num_ports,
2447 struct audio_port *ports,
2448 unsigned int *generation)
2449{
2450 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2451 generation == NULL) {
2452 return BAD_VALUE;
2453 }
2454 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2455 if (ports == NULL) {
2456 *num_ports = 0;
2457 }
2458
2459 size_t portsWritten = 0;
2460 size_t portsMax = *num_ports;
2461 *num_ports = 0;
2462 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002463 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2464 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002465 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002466 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2467 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2468 continue;
2469 }
2470 if (portsWritten < portsMax) {
2471 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2472 }
2473 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002474 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 }
2476 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002477 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2478 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2479 continue;
2480 }
2481 if (portsWritten < portsMax) {
2482 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2483 }
2484 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002485 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002486 }
2487 }
2488 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2489 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2490 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2491 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2492 }
2493 *num_ports += mInputs.size();
2494 }
2495 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002496 size_t numOutputs = 0;
2497 for (size_t i = 0; i < mOutputs.size(); i++) {
2498 if (!mOutputs[i]->isDuplicated()) {
2499 numOutputs++;
2500 if (portsWritten < portsMax) {
2501 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2502 }
2503 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002504 }
Eric Laurent84c70242014-06-23 08:46:27 -07002505 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002506 }
2507 }
2508 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002509 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002510 return NO_ERROR;
2511}
2512
2513status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2514{
2515 return NO_ERROR;
2516}
2517
Eric Laurent6a94d692014-05-20 11:18:06 -07002518status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2519 audio_patch_handle_t *handle,
2520 uid_t uid)
2521{
2522 ALOGV("createAudioPatch()");
2523
2524 if (handle == NULL || patch == NULL) {
2525 return BAD_VALUE;
2526 }
2527 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2528
Eric Laurent874c42872014-08-08 15:13:39 -07002529 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2530 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2531 return BAD_VALUE;
2532 }
2533 // only one source per audio patch supported for now
2534 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002535 return INVALID_OPERATION;
2536 }
Eric Laurent874c42872014-08-08 15:13:39 -07002537
2538 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002539 return INVALID_OPERATION;
2540 }
Eric Laurent874c42872014-08-08 15:13:39 -07002541 for (size_t i = 0; i < patch->num_sinks; i++) {
2542 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2543 return INVALID_OPERATION;
2544 }
2545 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002546
2547 sp<AudioPatch> patchDesc;
2548 ssize_t index = mAudioPatches.indexOfKey(*handle);
2549
Eric Laurent6a94d692014-05-20 11:18:06 -07002550 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2551 patch->sources[0].role,
2552 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002553#if LOG_NDEBUG == 0
2554 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002555 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002556 patch->sinks[i].role,
2557 patch->sinks[i].type);
2558 }
2559#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002560
2561 if (index >= 0) {
2562 patchDesc = mAudioPatches.valueAt(index);
2563 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2564 mUidCached, patchDesc->mUid, uid);
2565 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2566 return INVALID_OPERATION;
2567 }
2568 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002569 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002570 }
2571
2572 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002573 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002574 if (outputDesc == NULL) {
2575 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2576 return BAD_VALUE;
2577 }
Eric Laurent84c70242014-06-23 08:46:27 -07002578 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2579 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002580 if (patchDesc != 0) {
2581 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2582 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2583 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2584 return BAD_VALUE;
2585 }
2586 }
Eric Laurent874c42872014-08-08 15:13:39 -07002587 DeviceVector devices;
2588 for (size_t i = 0; i < patch->num_sinks; i++) {
2589 // Only support mix to devices connection
2590 // TODO add support for mix to mix connection
2591 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2592 ALOGV("createAudioPatch() source mix but sink is not a device");
2593 return INVALID_OPERATION;
2594 }
2595 sp<DeviceDescriptor> devDesc =
2596 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2597 if (devDesc == 0) {
2598 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2599 return BAD_VALUE;
2600 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002601
François Gaffie53615e22015-03-19 09:24:12 +01002602 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002603 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002604 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002605 NULL, // updatedSamplingRate
2606 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002607 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002608 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002609 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002610 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002611 ALOGV("createAudioPatch() profile not supported for device %08x",
2612 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002613 return INVALID_OPERATION;
2614 }
2615 devices.add(devDesc);
2616 }
2617 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002618 return INVALID_OPERATION;
2619 }
Eric Laurent874c42872014-08-08 15:13:39 -07002620
Eric Laurent6a94d692014-05-20 11:18:06 -07002621 // TODO: reconfigure output format and channels here
2622 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002623 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002624 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002625 index = mAudioPatches.indexOfKey(*handle);
2626 if (index >= 0) {
2627 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2628 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2629 }
2630 patchDesc = mAudioPatches.valueAt(index);
2631 patchDesc->mUid = uid;
2632 ALOGV("createAudioPatch() success");
2633 } else {
2634 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2635 return INVALID_OPERATION;
2636 }
2637 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2638 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2639 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002640 // only one sink supported when connecting an input device to a mix
2641 if (patch->num_sinks > 1) {
2642 return INVALID_OPERATION;
2643 }
François Gaffie53615e22015-03-19 09:24:12 +01002644 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002645 if (inputDesc == NULL) {
2646 return BAD_VALUE;
2647 }
2648 if (patchDesc != 0) {
2649 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2650 return BAD_VALUE;
2651 }
2652 }
2653 sp<DeviceDescriptor> devDesc =
2654 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2655 if (devDesc == 0) {
2656 return BAD_VALUE;
2657 }
2658
François Gaffie53615e22015-03-19 09:24:12 +01002659 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002660 devDesc->mAddress,
2661 patch->sinks[0].sample_rate,
2662 NULL, /*updatedSampleRate*/
2663 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002664 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002665 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002666 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002667 // FIXME for the parameter type,
2668 // and the NONE
2669 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002670 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002671 return INVALID_OPERATION;
2672 }
2673 // TODO: reconfigure output format and channels here
2674 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002675 devDesc->type(), inputDesc->mIoHandle);
2676 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002677 index = mAudioPatches.indexOfKey(*handle);
2678 if (index >= 0) {
2679 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2680 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2681 }
2682 patchDesc = mAudioPatches.valueAt(index);
2683 patchDesc->mUid = uid;
2684 ALOGV("createAudioPatch() success");
2685 } else {
2686 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2687 return INVALID_OPERATION;
2688 }
2689 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2690 // device to device connection
2691 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002692 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002693 return BAD_VALUE;
2694 }
2695 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002696 sp<DeviceDescriptor> srcDeviceDesc =
2697 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002698 if (srcDeviceDesc == 0) {
2699 return BAD_VALUE;
2700 }
Eric Laurent874c42872014-08-08 15:13:39 -07002701
Eric Laurent6a94d692014-05-20 11:18:06 -07002702 //update source and sink with our own data as the data passed in the patch may
2703 // be incomplete.
2704 struct audio_patch newPatch = *patch;
2705 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002706
Eric Laurent874c42872014-08-08 15:13:39 -07002707 for (size_t i = 0; i < patch->num_sinks; i++) {
2708 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2709 ALOGV("createAudioPatch() source device but one sink is not a device");
2710 return INVALID_OPERATION;
2711 }
2712
2713 sp<DeviceDescriptor> sinkDeviceDesc =
2714 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2715 if (sinkDeviceDesc == 0) {
2716 return BAD_VALUE;
2717 }
2718 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2719
Eric Laurent3bcf8592015-04-03 12:13:24 -07002720 // create a software bridge in PatchPanel if:
2721 // - source and sink devices are on differnt HW modules OR
2722 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002723 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002724 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002725 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002726 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002727 return INVALID_OPERATION;
2728 }
Eric Laurent874c42872014-08-08 15:13:39 -07002729 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002730 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002731 // if the sink device is reachable via an opened output stream, request to go via
2732 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002733 audio_io_handle_t output = selectOutput(outputs,
2734 AUDIO_OUTPUT_FLAG_NONE,
2735 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002736 if (output != AUDIO_IO_HANDLE_NONE) {
2737 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2738 if (outputDesc->isDuplicated()) {
2739 return INVALID_OPERATION;
2740 }
2741 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002742 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002743 newPatch.num_sources = 2;
2744 }
Eric Laurent83b88082014-06-20 18:31:16 -07002745 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002746 }
2747 // TODO: check from routing capabilities in config file and other conflicting patches
2748
2749 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2750 if (index >= 0) {
2751 afPatchHandle = patchDesc->mAfPatchHandle;
2752 }
2753
2754 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2755 &afPatchHandle,
2756 0);
2757 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2758 status, afPatchHandle);
2759 if (status == NO_ERROR) {
2760 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002761 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002762 addAudioPatch(patchDesc->mHandle, patchDesc);
2763 } else {
2764 patchDesc->mPatch = newPatch;
2765 }
2766 patchDesc->mAfPatchHandle = afPatchHandle;
2767 *handle = patchDesc->mHandle;
2768 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002769 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002770 } else {
2771 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2772 status);
2773 return INVALID_OPERATION;
2774 }
2775 } else {
2776 return BAD_VALUE;
2777 }
2778 } else {
2779 return BAD_VALUE;
2780 }
2781 return NO_ERROR;
2782}
2783
2784status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2785 uid_t uid)
2786{
2787 ALOGV("releaseAudioPatch() patch %d", handle);
2788
2789 ssize_t index = mAudioPatches.indexOfKey(handle);
2790
2791 if (index < 0) {
2792 return BAD_VALUE;
2793 }
2794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2795 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2796 mUidCached, patchDesc->mUid, uid);
2797 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2798 return INVALID_OPERATION;
2799 }
2800
2801 struct audio_patch *patch = &patchDesc->mPatch;
2802 patchDesc->mUid = mUidCached;
2803 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002804 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 if (outputDesc == NULL) {
2806 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2807 return BAD_VALUE;
2808 }
2809
Eric Laurentc75307b2015-03-17 15:29:32 -07002810 setOutputDevice(outputDesc,
2811 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002812 true,
2813 0,
2814 NULL);
2815 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2816 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002817 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002818 if (inputDesc == NULL) {
2819 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2820 return BAD_VALUE;
2821 }
2822 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002823 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002824 true,
2825 NULL);
2826 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2828 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2829 status, patchDesc->mAfPatchHandle);
2830 removeAudioPatch(patchDesc->mHandle);
2831 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002832 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 } else {
2834 return BAD_VALUE;
2835 }
2836 } else {
2837 return BAD_VALUE;
2838 }
2839 return NO_ERROR;
2840}
2841
2842status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2843 struct audio_patch *patches,
2844 unsigned int *generation)
2845{
François Gaffie53615e22015-03-19 09:24:12 +01002846 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 return BAD_VALUE;
2848 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002849 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002850 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002851}
2852
Eric Laurente1715a42014-05-20 11:30:42 -07002853status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002854{
Eric Laurente1715a42014-05-20 11:30:42 -07002855 ALOGV("setAudioPortConfig()");
2856
2857 if (config == NULL) {
2858 return BAD_VALUE;
2859 }
2860 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2861 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002862 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2863 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002864 }
2865
Eric Laurenta121f902014-06-03 13:32:54 -07002866 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002867 if (config->type == AUDIO_PORT_TYPE_MIX) {
2868 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002869 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002870 if (outputDesc == NULL) {
2871 return BAD_VALUE;
2872 }
Eric Laurent84c70242014-06-23 08:46:27 -07002873 ALOG_ASSERT(!outputDesc->isDuplicated(),
2874 "setAudioPortConfig() called on duplicated output %d",
2875 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002876 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002877 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002878 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002879 if (inputDesc == NULL) {
2880 return BAD_VALUE;
2881 }
Eric Laurenta121f902014-06-03 13:32:54 -07002882 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002883 } else {
2884 return BAD_VALUE;
2885 }
2886 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2887 sp<DeviceDescriptor> deviceDesc;
2888 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2889 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2890 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2891 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2892 } else {
2893 return BAD_VALUE;
2894 }
2895 if (deviceDesc == NULL) {
2896 return BAD_VALUE;
2897 }
Eric Laurenta121f902014-06-03 13:32:54 -07002898 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002899 } else {
2900 return BAD_VALUE;
2901 }
2902
Eric Laurenta121f902014-06-03 13:32:54 -07002903 struct audio_port_config backupConfig;
2904 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2905 if (status == NO_ERROR) {
2906 struct audio_port_config newConfig;
2907 audioPortConfig->toAudioPortConfig(&newConfig, config);
2908 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002909 }
Eric Laurenta121f902014-06-03 13:32:54 -07002910 if (status != NO_ERROR) {
2911 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002912 }
Eric Laurente1715a42014-05-20 11:30:42 -07002913
2914 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002915}
2916
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002917void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2918{
Eric Laurentd60560a2015-04-10 11:31:20 -07002919 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002920 clearAudioPatches(uid);
2921 clearSessionRoutes(uid);
2922}
2923
Eric Laurent6a94d692014-05-20 11:18:06 -07002924void AudioPolicyManager::clearAudioPatches(uid_t uid)
2925{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002926 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002927 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2928 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002929 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 }
2931 }
2932}
2933
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002934void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2935 audio_io_handle_t ouptutToSkip)
2936{
2937 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2938 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2939 for (size_t j = 0; j < mOutputs.size(); j++) {
2940 if (mOutputs.keyAt(j) == ouptutToSkip) {
2941 continue;
2942 }
2943 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2944 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2945 continue;
2946 }
2947 // If the default device for this strategy is on another output mix,
2948 // invalidate all tracks in this strategy to force re connection.
2949 // Otherwise select new device on the output mix.
2950 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002951 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002952 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2953 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2954 }
2955 }
2956 } else {
2957 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2958 setOutputDevice(outputDesc, newDevice, false);
2959 }
2960 }
2961}
2962
2963void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2964{
2965 // remove output routes associated with this uid
2966 SortedVector<routing_strategy> affectedStrategies;
2967 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2968 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2969 if (route->mUid == uid) {
2970 mOutputRoutes.removeItemsAt(i);
2971 if (route->mDeviceDescriptor != 0) {
2972 affectedStrategies.add(getStrategy(route->mStreamType));
2973 }
2974 }
2975 }
2976 // reroute outputs if necessary
2977 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2978 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2979 }
2980
2981 // remove input routes associated with this uid
2982 SortedVector<audio_source_t> affectedSources;
2983 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2984 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2985 if (route->mUid == uid) {
2986 mInputRoutes.removeItemsAt(i);
2987 if (route->mDeviceDescriptor != 0) {
2988 affectedSources.add(route->mSource);
2989 }
2990 }
2991 }
2992 // reroute inputs if necessary
2993 SortedVector<audio_io_handle_t> inputsToClose;
2994 for (size_t i = 0; i < mInputs.size(); i++) {
2995 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002996 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002997 inputsToClose.add(inputDesc->mIoHandle);
2998 }
2999 }
3000 for (size_t i = 0; i < inputsToClose.size(); i++) {
3001 closeInput(inputsToClose[i]);
3002 }
3003}
3004
Eric Laurentd60560a2015-04-10 11:31:20 -07003005void AudioPolicyManager::clearAudioSources(uid_t uid)
3006{
3007 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3008 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3009 if (sourceDesc->mUid == uid) {
3010 stopAudioSource(mAudioSources.keyAt(i));
3011 }
3012 }
3013}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003014
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003015status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3016 audio_io_handle_t *ioHandle,
3017 audio_devices_t *device)
3018{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003019 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3020 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003021 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003022
François Gaffiedf372692015-03-19 10:43:27 +01003023 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003024}
3025
Eric Laurentd60560a2015-04-10 11:31:20 -07003026status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3027 const audio_attributes_t *attributes,
3028 audio_io_handle_t *handle,
3029 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003030{
Eric Laurentd60560a2015-04-10 11:31:20 -07003031 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3032 if (source == NULL || attributes == NULL || handle == NULL) {
3033 return BAD_VALUE;
3034 }
3035
3036 *handle = AUDIO_IO_HANDLE_NONE;
3037
3038 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3039 source->type != AUDIO_PORT_TYPE_DEVICE) {
3040 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3041 return INVALID_OPERATION;
3042 }
3043
3044 sp<DeviceDescriptor> srcDeviceDesc =
3045 mAvailableInputDevices.getDevice(source->ext.device.type,
3046 String8(source->ext.device.address));
3047 if (srcDeviceDesc == 0) {
3048 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3049 return BAD_VALUE;
3050 }
3051 sp<AudioSourceDescriptor> sourceDesc =
3052 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3053
3054 struct audio_patch dummyPatch;
3055 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3056 sourceDesc->mPatchDesc = patchDesc;
3057
3058 status_t status = connectAudioSource(sourceDesc);
3059 if (status == NO_ERROR) {
3060 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3061 *handle = sourceDesc->getHandle();
3062 }
3063 return status;
3064}
3065
3066status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3067{
3068 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3069
3070 // make sure we only have one patch per source.
3071 disconnectAudioSource(sourceDesc);
3072
3073 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003074 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003075 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3076
3077 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3078 sp<DeviceDescriptor> sinkDeviceDesc =
3079 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3080
3081 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3082 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3083
3084 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3085 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003086 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003087 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3088 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3089 // create patch between src device and output device
3090 // create Hwoutput and add to mHwOutputs
3091 } else {
3092 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3093 audio_io_handle_t output =
3094 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3095 if (output == AUDIO_IO_HANDLE_NONE) {
3096 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3097 return INVALID_OPERATION;
3098 }
3099 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3100 if (outputDesc->isDuplicated()) {
3101 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3102 return INVALID_OPERATION;
3103 }
3104 // create a special patch with no sink and two sources:
3105 // - the second source indicates to PatchPanel through which output mix this patch should
3106 // be connected as well as the stream type for volume control
3107 // - the sink is defined by whatever output device is currently selected for the output
3108 // though which this patch is routed.
3109 patch->num_sinks = 0;
3110 patch->num_sources = 2;
3111 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3112 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3113 patch->sources[1].ext.mix.usecase.stream = stream;
3114 status_t status = mpClientInterface->createAudioPatch(patch,
3115 &afPatchHandle,
3116 0);
3117 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3118 status, afPatchHandle);
3119 if (status != NO_ERROR) {
3120 ALOGW("%s patch panel could not connect device patch, error %d",
3121 __FUNCTION__, status);
3122 return INVALID_OPERATION;
3123 }
3124 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003125 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003126
3127 if (status != NO_ERROR) {
3128 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3129 return status;
3130 }
3131 sourceDesc->mSwOutput = outputDesc;
3132 if (delayMs != 0) {
3133 usleep(delayMs * 1000);
3134 }
3135 }
3136
3137 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3138 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3139
3140 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003141}
3142
Eric Laurent493404d2015-04-21 15:07:36 -07003143status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003144{
Eric Laurentd60560a2015-04-10 11:31:20 -07003145 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3146 ALOGV("%s handle %d", __FUNCTION__, handle);
3147 if (sourceDesc == 0) {
3148 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3149 return BAD_VALUE;
3150 }
3151 status_t status = disconnectAudioSource(sourceDesc);
3152
3153 mAudioSources.removeItem(handle);
3154 return status;
3155}
3156
Andy Hung2ddee192015-12-18 17:34:44 -08003157status_t AudioPolicyManager::setMasterMono(bool mono)
3158{
3159 if (mMasterMono == mono) {
3160 return NO_ERROR;
3161 }
3162 mMasterMono = mono;
3163 // if enabling mono we close all offloaded devices, which will invalidate the
3164 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3165 // for recreating the new AudioTrack as non-offloaded PCM.
3166 //
3167 // If disabling mono, we leave all tracks as is: we don't know which clients
3168 // and tracks are able to be recreated as offloaded. The next "song" should
3169 // play back offloaded.
3170 if (mMasterMono) {
3171 Vector<audio_io_handle_t> offloaded;
3172 for (size_t i = 0; i < mOutputs.size(); ++i) {
3173 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3174 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3175 offloaded.push(desc->mIoHandle);
3176 }
3177 }
3178 for (size_t i = 0; i < offloaded.size(); ++i) {
3179 closeOutput(offloaded[i]);
3180 }
3181 }
3182 // update master mono for all remaining outputs
3183 for (size_t i = 0; i < mOutputs.size(); ++i) {
3184 updateMono(mOutputs.keyAt(i));
3185 }
3186 return NO_ERROR;
3187}
3188
3189status_t AudioPolicyManager::getMasterMono(bool *mono)
3190{
3191 *mono = mMasterMono;
3192 return NO_ERROR;
3193}
3194
Eric Laurentd60560a2015-04-10 11:31:20 -07003195status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3196{
3197 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3198
3199 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3200 if (patchDesc == 0) {
3201 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3202 sourceDesc->mPatchDesc->mHandle);
3203 return BAD_VALUE;
3204 }
3205 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3206
Eric Laurent28d09f02016-03-08 10:43:05 -08003207 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003208 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3209 if (swOutputDesc != 0) {
3210 stopSource(swOutputDesc, stream, false);
3211 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3212 } else {
3213 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3214 if (hwOutputDesc != 0) {
3215 // release patch between src device and output device
3216 // close Hwoutput and remove from mHwOutputs
3217 } else {
3218 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3219 }
3220 }
3221 return NO_ERROR;
3222}
3223
3224sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3225 audio_io_handle_t output, routing_strategy strategy)
3226{
3227 sp<AudioSourceDescriptor> source;
3228 for (size_t i = 0; i < mAudioSources.size(); i++) {
3229 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3230 routing_strategy sourceStrategy =
3231 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3232 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3233 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3234 source = sourceDesc;
3235 break;
3236 }
3237 }
3238 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003239}
3240
Eric Laurente552edb2014-03-10 17:42:56 -07003241// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003242// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003243// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003244uint32_t AudioPolicyManager::nextAudioPortGeneration()
3245{
3246 return android_atomic_inc(&mAudioPortGeneration);
3247}
3248
Eric Laurente0720872014-03-11 09:30:41 -07003249AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003250 :
3251#ifdef AUDIO_POLICY_TEST
3252 Thread(false),
3253#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003254 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003255 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003256 mAudioPortGeneration(1),
3257 mBeaconMuteRefCount(0),
3258 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003259 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003260 mTtsOutputAvailable(false),
3261 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003262{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003263 mUidCached = getuid();
3264 mpClientInterface = clientInterface;
3265
3266 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3267 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3268 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3269 bool speakerDrcEnabled = false;
3270
3271#ifdef USE_XML_AUDIO_POLICY_CONF
3272 mVolumeCurves = new VolumeCurvesCollection();
3273 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3274 mDefaultOutputDevice, speakerDrcEnabled,
3275 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3276 PolicySerializer serializer;
3277 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3278#else
3279 mVolumeCurves = new StreamDescriptorCollection();
3280 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3281 mDefaultOutputDevice, speakerDrcEnabled);
3282 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3283 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3284#endif
3285 ALOGE("could not load audio policy configuration file, setting defaults");
3286 config.setDefault();
3287 }
3288 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3289 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3290
3291 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003292 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3293 if (!engineInstance) {
3294 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3295 return;
3296 }
3297 // Retrieve the Policy Manager Interface
3298 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3299 if (mEngine == NULL) {
3300 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3301 return;
3302 }
3303 mEngine->setObserver(this);
3304 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003305 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003306 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3307
Eric Laurent3a4311c2014-03-17 12:00:47 -07003308 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003309 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003310 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3311 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003312 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003313 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003314 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003315 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003316 continue;
3317 }
3318 // open all output streams needed to access attached devices
3319 // except for direct output streams that are only opened when they are actually
3320 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003321 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003322 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3323 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003324 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003325
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003326 if (!outProfile->hasSupportedDevices()) {
3327 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003328 continue;
3329 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003330 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003331 mTtsOutputAvailable = true;
3332 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003333
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003334 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003335 continue;
3336 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003337 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003338 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3339 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003340 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003341 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003342 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003343 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003344 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003345 if ((profileType & outputDeviceTypes) == 0) {
3346 continue;
3347 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003348 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3349 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003350 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3351 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3352 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3353 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003354
3355 outputDesc->mDevice = profileType;
3356 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3357 config.sample_rate = outputDesc->mSamplingRate;
3358 config.channel_mask = outputDesc->mChannelMask;
3359 config.format = outputDesc->mFormat;
3360 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003361 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003362 &output,
3363 &config,
3364 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003365 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003366 &outputDesc->mLatency,
3367 outputDesc->mFlags);
3368
3369 if (status != NO_ERROR) {
3370 ALOGW("Cannot open output stream for device %08x on hw module %s",
3371 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003372 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003373 } else {
3374 outputDesc->mSamplingRate = config.sample_rate;
3375 outputDesc->mChannelMask = config.channel_mask;
3376 outputDesc->mFormat = config.format;
3377
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003378 for (size_t k = 0; k < supportedDevices.size(); k++) {
3379 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003380 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003381 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3382 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003383 }
3384 }
3385 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003386 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003387 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003388 }
3389 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003390 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003391 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003392 true,
3393 0,
3394 NULL,
3395 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003396 }
Eric Laurente552edb2014-03-10 17:42:56 -07003397 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003398 // open input streams needed to access attached devices to validate
3399 // mAvailableInputDevices list
3400 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3401 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003402 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003403
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003404 if (!inProfile->hasSupportedDevices()) {
3405 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003406 continue;
3407 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003408 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003409 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003410 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3411
Eric Laurentd78f1532014-09-16 16:38:20 -07003412 if ((profileType & inputDeviceTypes) == 0) {
3413 continue;
3414 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003415 sp<AudioInputDescriptor> inputDesc =
3416 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003417
Eric Laurentd78f1532014-09-16 16:38:20 -07003418 inputDesc->mDevice = profileType;
3419
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003420 // find the address
3421 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3422 // the inputs vector must be of size 1, but we don't want to crash here
3423 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3424 : String8("");
3425 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3426 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3427
Eric Laurentd78f1532014-09-16 16:38:20 -07003428 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3429 config.sample_rate = inputDesc->mSamplingRate;
3430 config.channel_mask = inputDesc->mChannelMask;
3431 config.format = inputDesc->mFormat;
3432 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003433 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003434 &input,
3435 &config,
3436 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003437 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003438 AUDIO_SOURCE_MIC,
3439 AUDIO_INPUT_FLAG_NONE);
3440
3441 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003442 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3443 for (size_t k = 0; k < supportedDevices.size(); k++) {
3444 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003445 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003446 if (index >= 0) {
3447 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3448 if (!devDesc->isAttached()) {
3449 devDesc->attach(mHwModules[i]);
3450 devDesc->importAudioPort(inProfile);
3451 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003452 }
3453 }
3454 mpClientInterface->closeInput(input);
3455 } else {
3456 ALOGW("Cannot open input stream for device %08x on hw module %s",
3457 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003458 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003459 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003460 }
3461 }
3462 // make sure all attached devices have been allocated a unique ID
3463 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003464 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003465 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003466 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3467 continue;
3468 }
François Gaffie2110e042015-03-24 08:41:51 +01003469 // The device is now validated and can be appended to the available devices of the engine
3470 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3471 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003472 i++;
3473 }
3474 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003475 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003476 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003477 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3478 continue;
3479 }
François Gaffie2110e042015-03-24 08:41:51 +01003480 // The device is now validated and can be appended to the available devices of the engine
3481 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3482 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003483 i++;
3484 }
3485 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003486 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003487 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003488 }
Eric Laurente552edb2014-03-10 17:42:56 -07003489
3490 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3491
3492 updateDevicesAndOutputs();
3493
3494#ifdef AUDIO_POLICY_TEST
3495 if (mPrimaryOutput != 0) {
3496 AudioParameter outputCmd = AudioParameter();
3497 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003498 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003499
3500 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3501 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003502 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3503 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003504 mTestLatencyMs = 0;
3505 mCurOutput = 0;
3506 mDirectOutput = false;
3507 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3508 mTestOutputs[i] = 0;
3509 }
3510
3511 const size_t SIZE = 256;
3512 char buffer[SIZE];
3513 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3514 run(buffer, ANDROID_PRIORITY_AUDIO);
3515 }
3516#endif //AUDIO_POLICY_TEST
3517}
3518
Eric Laurente0720872014-03-11 09:30:41 -07003519AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003520{
3521#ifdef AUDIO_POLICY_TEST
3522 exit();
3523#endif //AUDIO_POLICY_TEST
3524 for (size_t i = 0; i < mOutputs.size(); i++) {
3525 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003526 }
3527 for (size_t i = 0; i < mInputs.size(); i++) {
3528 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003529 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003530 mAvailableOutputDevices.clear();
3531 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003532 mOutputs.clear();
3533 mInputs.clear();
3534 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003535}
3536
Eric Laurente0720872014-03-11 09:30:41 -07003537status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003538{
Eric Laurent87ffa392015-05-22 10:32:38 -07003539 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003540}
3541
3542#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003543bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003544{
3545 ALOGV("entering threadLoop()");
3546 while (!exitPending())
3547 {
3548 String8 command;
3549 int valueInt;
3550 String8 value;
3551
3552 Mutex::Autolock _l(mLock);
3553 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3554
3555 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3556 AudioParameter param = AudioParameter(command);
3557
3558 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3559 valueInt != 0) {
3560 ALOGV("Test command %s received", command.string());
3561 String8 target;
3562 if (param.get(String8("target"), target) != NO_ERROR) {
3563 target = "Manager";
3564 }
3565 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3566 param.remove(String8("test_cmd_policy_output"));
3567 mCurOutput = valueInt;
3568 }
3569 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3570 param.remove(String8("test_cmd_policy_direct"));
3571 if (value == "false") {
3572 mDirectOutput = false;
3573 } else if (value == "true") {
3574 mDirectOutput = true;
3575 }
3576 }
3577 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3578 param.remove(String8("test_cmd_policy_input"));
3579 mTestInput = valueInt;
3580 }
3581
3582 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3583 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003584 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003585 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003586 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003587 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003588 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003589 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003590 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003591 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003592 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003593 if (target == "Manager") {
3594 mTestFormat = format;
3595 } else if (mTestOutputs[mCurOutput] != 0) {
3596 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003597 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003598 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3599 }
3600 }
3601 }
3602 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3603 param.remove(String8("test_cmd_policy_channels"));
3604 int channels = 0;
3605
3606 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003607 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003608 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003609 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003610 }
3611 if (channels != 0) {
3612 if (target == "Manager") {
3613 mTestChannels = channels;
3614 } else if (mTestOutputs[mCurOutput] != 0) {
3615 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003616 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003617 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3618 }
3619 }
3620 }
3621 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3622 param.remove(String8("test_cmd_policy_sampleRate"));
3623 if (valueInt >= 0 && valueInt <= 96000) {
3624 int samplingRate = valueInt;
3625 if (target == "Manager") {
3626 mTestSamplingRate = samplingRate;
3627 } else if (mTestOutputs[mCurOutput] != 0) {
3628 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003629 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003630 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3631 }
3632 }
3633 }
3634
3635 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3636 param.remove(String8("test_cmd_policy_reopen"));
3637
Eric Laurentc75307b2015-03-17 15:29:32 -07003638 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003639
Eric Laurentc75307b2015-03-17 15:29:32 -07003640 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003641
Eric Laurentc75307b2015-03-17 15:29:32 -07003642 removeOutput(mPrimaryOutput->mIoHandle);
3643 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3644 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003645 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003646 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3647 config.sample_rate = outputDesc->mSamplingRate;
3648 config.channel_mask = outputDesc->mChannelMask;
3649 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003650 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003651 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003652 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003653 &config,
3654 &outputDesc->mDevice,
3655 String8(""),
3656 &outputDesc->mLatency,
3657 outputDesc->mFlags);
3658 if (status != NO_ERROR) {
3659 ALOGE("Failed to reopen hardware output stream, "
3660 "samplingRate: %d, format %d, channels %d",
3661 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003662 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003663 outputDesc->mSamplingRate = config.sample_rate;
3664 outputDesc->mChannelMask = config.channel_mask;
3665 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003666 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003667 AudioParameter outputCmd = AudioParameter();
3668 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003669 mpClientInterface->setParameters(handle, outputCmd.toString());
3670 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003671 }
3672 }
3673
3674
3675 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3676 }
3677 }
3678 return false;
3679}
3680
Eric Laurente0720872014-03-11 09:30:41 -07003681void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003682{
3683 {
3684 AutoMutex _l(mLock);
3685 requestExit();
3686 mWaitWorkCV.signal();
3687 }
3688 requestExitAndWait();
3689}
3690
Eric Laurente0720872014-03-11 09:30:41 -07003691int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003692{
3693 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3694 if (output == mTestOutputs[i]) return i;
3695 }
3696 return 0;
3697}
3698#endif //AUDIO_POLICY_TEST
3699
3700// ---
3701
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003702void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003703{
François Gaffie98cc1912015-03-18 17:52:40 +01003704 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003705 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003706 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003707 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003708}
3709
François Gaffie53615e22015-03-19 09:24:12 +01003710void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3711{
3712 mOutputs.removeItem(output);
3713}
3714
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003715void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003716{
François Gaffie98cc1912015-03-18 17:52:40 +01003717 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003718 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003719 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003720}
Eric Laurente552edb2014-03-10 17:42:56 -07003721
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003722void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003723 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003724 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003725 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003726 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003727 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003728 if (devDesc != 0) {
3729 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3730 desc->mIoHandle, address.string());
3731 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003732 }
3733}
3734
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003735status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003736 audio_policy_dev_state_t state,
3737 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003738 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003739{
François Gaffie53615e22015-03-19 09:24:12 +01003740 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003741 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003742
3743 if (audio_device_is_digital(device)) {
3744 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003745 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003746 }
Eric Laurente552edb2014-03-10 17:42:56 -07003747
Eric Laurent3b73df72014-03-11 09:06:29 -07003748 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003749 // first list already open outputs that can be routed to this device
3750 for (size_t i = 0; i < mOutputs.size(); i++) {
3751 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003752 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003753 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003754 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3755 outputs.add(mOutputs.keyAt(i));
3756 } else {
3757 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003758 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003759 }
Eric Laurente552edb2014-03-10 17:42:56 -07003760 }
3761 }
3762 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003763 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003764 for (size_t i = 0; i < mHwModules.size(); i++)
3765 {
3766 if (mHwModules[i]->mHandle == 0) {
3767 continue;
3768 }
3769 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3770 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003771 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003772 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003773 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003774 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003775 profiles.add(profile);
3776 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3777 }
Eric Laurente552edb2014-03-10 17:42:56 -07003778 }
3779 }
3780 }
3781
Eric Laurent7b279bb2015-12-14 10:18:23 -08003782 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003783
Eric Laurente552edb2014-03-10 17:42:56 -07003784 if (profiles.isEmpty() && outputs.isEmpty()) {
3785 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3786 return BAD_VALUE;
3787 }
3788
3789 // open outputs for matching profiles if needed. Direct outputs are also opened to
3790 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3791 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003792 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003793
3794 // nothing to do if one output is already opened for this profile
3795 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003796 for (j = 0; j < outputs.size(); j++) {
3797 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003798 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003799 // matching profile: save the sample rates, format and channel masks supported
3800 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003801 if (audio_device_is_digital(device)) {
3802 devDesc->importAudioPort(profile);
3803 }
Eric Laurente552edb2014-03-10 17:42:56 -07003804 break;
3805 }
3806 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003807 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003808 continue;
3809 }
3810
Eric Laurent83b88082014-06-20 18:31:16 -07003811 ALOGV("opening output for device %08x with params %s profile %p",
3812 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003813 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003814 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003815 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3816 config.sample_rate = desc->mSamplingRate;
3817 config.channel_mask = desc->mChannelMask;
3818 config.format = desc->mFormat;
3819 config.offload_info.sample_rate = desc->mSamplingRate;
3820 config.offload_info.channel_mask = desc->mChannelMask;
3821 config.offload_info.format = desc->mFormat;
3822 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003823 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003824 &output,
3825 &config,
3826 &desc->mDevice,
3827 address,
3828 &desc->mLatency,
3829 desc->mFlags);
3830 if (status == NO_ERROR) {
3831 desc->mSamplingRate = config.sample_rate;
3832 desc->mChannelMask = config.channel_mask;
3833 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003834
Eric Laurentd4692962014-05-05 18:13:44 -07003835 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003836 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003837 char *param = audio_device_address_to_parameter(device, address);
3838 mpClientInterface->setParameters(output, String8(param));
3839 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003840 }
Phil Burk00eeb322016-03-31 12:41:00 -07003841 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003842 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003843 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003844 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003845 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003846 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003847 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003848 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003849 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003850 config.offload_info.sample_rate = config.sample_rate;
3851 config.offload_info.channel_mask = config.channel_mask;
3852 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003853 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003854 &output,
3855 &config,
3856 &desc->mDevice,
3857 address,
3858 &desc->mLatency,
3859 desc->mFlags);
3860 if (status == NO_ERROR) {
3861 desc->mSamplingRate = config.sample_rate;
3862 desc->mChannelMask = config.channel_mask;
3863 desc->mFormat = config.format;
3864 } else {
3865 output = AUDIO_IO_HANDLE_NONE;
3866 }
Eric Laurentd4692962014-05-05 18:13:44 -07003867 }
3868
Eric Laurentcf2c0212014-07-25 16:20:43 -07003869 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003870 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003871 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003872 sp<AudioPolicyMix> policyMix;
3873 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003874 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3875 address.string());
3876 }
François Gaffie036e1e92015-03-19 10:16:24 +01003877 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003878 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003879
Eric Laurent87ffa392015-05-22 10:32:38 -07003880 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3881 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003882 // no duplicated output for direct outputs and
3883 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003884 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003885
Eric Laurentd4692962014-05-05 18:13:44 -07003886 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003887 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003888
Eric Laurentd4692962014-05-05 18:13:44 -07003889 //TODO: configure audio effect output stage here
3890
3891 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003892 duplicatedOutput =
3893 mpClientInterface->openDuplicateOutput(output,
3894 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003895 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003896 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003897 sp<SwAudioOutputDescriptor> dupOutputDesc =
3898 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3899 dupOutputDesc->mOutput1 = mPrimaryOutput;
3900 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003901 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3902 dupOutputDesc->mFormat = desc->mFormat;
3903 dupOutputDesc->mChannelMask = desc->mChannelMask;
3904 dupOutputDesc->mLatency = desc->mLatency;
3905 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003906 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003907 } else {
3908 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003909 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003910 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003911 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003912 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003913 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003914 }
Eric Laurente552edb2014-03-10 17:42:56 -07003915 }
3916 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003917 } else {
3918 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003919 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003920 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003921 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003922 profiles.removeAt(profile_index);
3923 profile_index--;
3924 } else {
3925 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003926 // Load digital format info only for digital devices
3927 if (audio_device_is_digital(device)) {
3928 devDesc->importAudioPort(profile);
3929 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003930
François Gaffie53615e22015-03-19 09:24:12 +01003931 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003932 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3933 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003934 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003935 NULL/*patch handle*/, address.string());
3936 }
Eric Laurente552edb2014-03-10 17:42:56 -07003937 ALOGV("checkOutputsForDevice(): adding output %d", output);
3938 }
3939 }
3940
3941 if (profiles.isEmpty()) {
3942 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3943 return BAD_VALUE;
3944 }
Eric Laurentd4692962014-05-05 18:13:44 -07003945 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003946 // check if one opened output is not needed any more after disconnecting one device
3947 for (size_t i = 0; i < mOutputs.size(); i++) {
3948 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003949 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003950 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003951 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003952 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003953 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003954 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003955 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3956 mOutputs.keyAt(i));
3957 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003958 }
Eric Laurente552edb2014-03-10 17:42:56 -07003959 }
3960 }
Eric Laurentd4692962014-05-05 18:13:44 -07003961 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003962 for (size_t i = 0; i < mHwModules.size(); i++)
3963 {
3964 if (mHwModules[i]->mHandle == 0) {
3965 continue;
3966 }
3967 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3968 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003969 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003970 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003971 ALOGV("checkOutputsForDevice(): "
3972 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003973 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003974 }
3975 }
3976 }
3977 }
3978 return NO_ERROR;
3979}
3980
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003981status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003982 audio_policy_dev_state_t state,
3983 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003984 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003985{
Paul McLean9080a4c2015-06-18 08:24:02 -07003986 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003987 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003988
3989 if (audio_device_is_digital(device)) {
3990 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003991 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003992 }
3993
Eric Laurentd4692962014-05-05 18:13:44 -07003994 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3995 // first list already open inputs that can be routed to this device
3996 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3997 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003998 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003999 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4000 inputs.add(mInputs.keyAt(input_index));
4001 }
4002 }
4003
4004 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004005 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004006 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4007 {
4008 if (mHwModules[module_idx]->mHandle == 0) {
4009 continue;
4010 }
4011 for (size_t profile_index = 0;
4012 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4013 profile_index++)
4014 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004015 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4016
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004017 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004018 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004019 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004020 profiles.add(profile);
4021 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4022 profile_index, module_idx);
4023 }
Eric Laurentd4692962014-05-05 18:13:44 -07004024 }
4025 }
4026 }
4027
4028 if (profiles.isEmpty() && inputs.isEmpty()) {
4029 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4030 return BAD_VALUE;
4031 }
4032
4033 // open inputs for matching profiles if needed. Direct inputs are also opened to
4034 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4035 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4036
Eric Laurent1c333e22014-05-20 10:48:17 -07004037 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004038 // nothing to do if one input is already opened for this profile
4039 size_t input_index;
4040 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4041 desc = mInputs.valueAt(input_index);
4042 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004043 if (audio_device_is_digital(device)) {
4044 devDesc->importAudioPort(profile);
4045 }
Eric Laurentd4692962014-05-05 18:13:44 -07004046 break;
4047 }
4048 }
4049 if (input_index != mInputs.size()) {
4050 continue;
4051 }
4052
4053 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4054 desc = new AudioInputDescriptor(profile);
4055 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004056 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4057 config.sample_rate = desc->mSamplingRate;
4058 config.channel_mask = desc->mChannelMask;
4059 config.format = desc->mFormat;
4060 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004061 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004062 &input,
4063 &config,
4064 &desc->mDevice,
4065 address,
4066 AUDIO_SOURCE_MIC,
4067 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004068
Eric Laurentcf2c0212014-07-25 16:20:43 -07004069 if (status == NO_ERROR) {
4070 desc->mSamplingRate = config.sample_rate;
4071 desc->mChannelMask = config.channel_mask;
4072 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004073
Eric Laurentd4692962014-05-05 18:13:44 -07004074 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004075 char *param = audio_device_address_to_parameter(device, address);
4076 mpClientInterface->setParameters(input, String8(param));
4077 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004078 }
Phil Burk00eeb322016-03-31 12:41:00 -07004079 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004080 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004081 ALOGW("checkInputsForDevice() direct input missing param");
4082 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004083 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004084 }
4085
4086 if (input != 0) {
4087 addInput(input, desc);
4088 }
4089 } // endif input != 0
4090
Eric Laurentcf2c0212014-07-25 16:20:43 -07004091 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004092 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004093 profiles.removeAt(profile_index);
4094 profile_index--;
4095 } else {
4096 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004097 if (audio_device_is_digital(device)) {
4098 devDesc->importAudioPort(profile);
4099 }
Eric Laurentd4692962014-05-05 18:13:44 -07004100 ALOGV("checkInputsForDevice(): adding input %d", input);
4101 }
4102 } // end scan profiles
4103
4104 if (profiles.isEmpty()) {
4105 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4106 return BAD_VALUE;
4107 }
4108 } else {
4109 // Disconnect
4110 // check if one opened input is not needed any more after disconnecting one device
4111 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4112 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004113 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004114 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4115 mInputs.keyAt(input_index));
4116 inputs.add(mInputs.keyAt(input_index));
4117 }
4118 }
4119 // Clear any profiles associated with the disconnected device.
4120 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4121 if (mHwModules[module_index]->mHandle == 0) {
4122 continue;
4123 }
4124 for (size_t profile_index = 0;
4125 profile_index < mHwModules[module_index]->mInputProfiles.size();
4126 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004127 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004128 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004129 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004130 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004131 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004132 }
4133 }
4134 }
4135 } // end disconnect
4136
4137 return NO_ERROR;
4138}
4139
4140
Eric Laurente0720872014-03-11 09:30:41 -07004141void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004142{
4143 ALOGV("closeOutput(%d)", output);
4144
Eric Laurentc75307b2015-03-17 15:29:32 -07004145 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004146 if (outputDesc == NULL) {
4147 ALOGW("closeOutput() unknown output %d", output);
4148 return;
4149 }
François Gaffie036e1e92015-03-19 10:16:24 +01004150 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004151
Eric Laurente552edb2014-03-10 17:42:56 -07004152 // look for duplicated outputs connected to the output being removed.
4153 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004154 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004155 if (dupOutputDesc->isDuplicated() &&
4156 (dupOutputDesc->mOutput1 == outputDesc ||
4157 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004158 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004159 if (dupOutputDesc->mOutput1 == outputDesc) {
4160 outputDesc2 = dupOutputDesc->mOutput2;
4161 } else {
4162 outputDesc2 = dupOutputDesc->mOutput1;
4163 }
4164 // As all active tracks on duplicated output will be deleted,
4165 // and as they were also referenced on the other output, the reference
4166 // count for their stream type must be adjusted accordingly on
4167 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004168 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004169 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004170 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004171 }
4172 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4173 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4174
4175 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004176 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004177 }
4178 }
4179
Eric Laurent05b90f82014-08-27 15:32:29 -07004180 nextAudioPortGeneration();
4181
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004182 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004183 if (index >= 0) {
4184 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004185 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004186 mAudioPatches.removeItemsAt(index);
4187 mpClientInterface->onAudioPatchListUpdate();
4188 }
4189
Eric Laurente552edb2014-03-10 17:42:56 -07004190 AudioParameter param;
4191 param.add(String8("closing"), String8("true"));
4192 mpClientInterface->setParameters(output, param.toString());
4193
4194 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004195 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004196 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004197}
4198
4199void AudioPolicyManager::closeInput(audio_io_handle_t input)
4200{
4201 ALOGV("closeInput(%d)", input);
4202
4203 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4204 if (inputDesc == NULL) {
4205 ALOGW("closeInput() unknown input %d", input);
4206 return;
4207 }
4208
Eric Laurent6a94d692014-05-20 11:18:06 -07004209 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004210
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004211 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004212 if (index >= 0) {
4213 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004214 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004215 mAudioPatches.removeItemsAt(index);
4216 mpClientInterface->onAudioPatchListUpdate();
4217 }
4218
4219 mpClientInterface->closeInput(input);
4220 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004221}
4222
Eric Laurentc75307b2015-03-17 15:29:32 -07004223SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4224 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004225 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004226{
4227 SortedVector<audio_io_handle_t> outputs;
4228
4229 ALOGVV("getOutputsForDevice() device %04x", device);
4230 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004231 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004232 i, openOutputs.valueAt(i)->isDuplicated(),
4233 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004234 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4235 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4236 outputs.add(openOutputs.keyAt(i));
4237 }
4238 }
4239 return outputs;
4240}
4241
Eric Laurente0720872014-03-11 09:30:41 -07004242bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004243 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004244{
4245 if (outputs1.size() != outputs2.size()) {
4246 return false;
4247 }
4248 for (size_t i = 0; i < outputs1.size(); i++) {
4249 if (outputs1[i] != outputs2[i]) {
4250 return false;
4251 }
4252 }
4253 return true;
4254}
4255
Eric Laurente0720872014-03-11 09:30:41 -07004256void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004257{
4258 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4259 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4260 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4261 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4262
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004263 // also take into account external policy-related changes: add all outputs which are
4264 // associated with policies in the "before" and "after" output vectors
4265 ALOGVV("checkOutputForStrategy(): policy related outputs");
4266 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004267 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004268 if (desc != 0 && desc->mPolicyMix != NULL) {
4269 srcOutputs.add(desc->mIoHandle);
4270 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4271 }
4272 }
4273 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004274 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004275 if (desc != 0 && desc->mPolicyMix != NULL) {
4276 dstOutputs.add(desc->mIoHandle);
4277 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4278 }
4279 }
4280
Eric Laurente552edb2014-03-10 17:42:56 -07004281 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4282 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4283 strategy, srcOutputs[0], dstOutputs[0]);
4284 // mute strategy while moving tracks from one output to another
4285 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004286 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004287 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004288 setStrategyMute(strategy, true, desc);
4289 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004290 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004291 sp<AudioSourceDescriptor> source =
4292 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4293 if (source != 0){
4294 connectAudioSource(source);
4295 }
Eric Laurente552edb2014-03-10 17:42:56 -07004296 }
4297
4298 // Move effects associated to this strategy from previous output to new output
4299 if (strategy == STRATEGY_MEDIA) {
4300 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4301 SortedVector<audio_io_handle_t> moved;
4302 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004303 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4304 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4305 effectDesc->mIo != fxOutput) {
4306 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004307 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4308 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004309 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004310 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004311 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004312 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004313 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004314 }
4315 }
4316 }
4317 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004318 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004319 if (getStrategy((audio_stream_type_t)i) == strategy) {
4320 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004321 }
4322 }
4323 }
4324}
4325
Eric Laurente0720872014-03-11 09:30:41 -07004326void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004327{
François Gaffie2110e042015-03-24 08:41:51 +01004328 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004329 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004330 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004331 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004332 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004333 checkOutputForStrategy(STRATEGY_SONIFICATION);
4334 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004335 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004336 checkOutputForStrategy(STRATEGY_MEDIA);
4337 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004338 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004339}
4340
Eric Laurente0720872014-03-11 09:30:41 -07004341void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004342{
François Gaffie53615e22015-03-19 09:24:12 +01004343 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004344 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004345 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004346 return;
4347 }
4348
Eric Laurent3a4311c2014-03-17 12:00:47 -07004349 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004350 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4351 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4352 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004353
4354 // if suspended, restore A2DP output if:
4355 // ((SCO device is NOT connected) ||
4356 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4357 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004358 //
Eric Laurentf732e072016-08-03 19:30:28 -07004359 // if not suspended, suspend A2DP output if:
4360 // (SCO device is connected) &&
4361 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4362 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004363 //
4364 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004365 if (!isScoConnected ||
4366 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4367 AUDIO_POLICY_FORCE_BT_SCO) &&
4368 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4369 AUDIO_POLICY_FORCE_BT_SCO) &&
4370 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004371 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004372
4373 mpClientInterface->restoreOutput(a2dpOutput);
4374 mA2dpSuspended = false;
4375 }
4376 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004377 if (isScoConnected &&
4378 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4379 AUDIO_POLICY_FORCE_BT_SCO) ||
4380 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4381 AUDIO_POLICY_FORCE_BT_SCO) ||
4382 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004383 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004384
4385 mpClientInterface->suspendOutput(a2dpOutput);
4386 mA2dpSuspended = true;
4387 }
4388 }
4389}
4390
Eric Laurentc75307b2015-03-17 15:29:32 -07004391audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4392 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004393{
4394 audio_devices_t device = AUDIO_DEVICE_NONE;
4395
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004396 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004397 if (index >= 0) {
4398 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4399 if (patchDesc->mUid != mUidCached) {
4400 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004401 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004402 return outputDesc->device();
4403 }
4404 }
4405
Eric Laurente552edb2014-03-10 17:42:56 -07004406 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004407 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004408 // use device for strategy enforced audible
4409 // 2: we are in call or the strategy phone is active on the output:
4410 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004411 // 3: the strategy for enforced audible is active but not enforced on the output:
4412 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004413 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004414 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004415 // 5: the strategy accessibility is active on the output:
4416 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004417 // 6: the strategy "respectful" sonification is active on the output:
4418 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004419 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004420 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004421 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004422 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004423 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004424 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004425 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004426 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004427 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4428 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004429 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004430 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004431 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004432 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004433 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004434 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004435 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4436 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004437 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004438 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004439 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004440 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004441 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004442 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004443 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004444 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004445 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004446 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004447 }
4448
Eric Laurent1c333e22014-05-20 10:48:17 -07004449 ALOGV("getNewOutputDevice() selected device %x", device);
4450 return device;
4451}
4452
Eric Laurentfb66dd92016-01-28 18:32:03 -08004453audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004454{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004455 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004456
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004457 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004458 if (index >= 0) {
4459 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4460 if (patchDesc->mUid != mUidCached) {
4461 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004462 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004463 return inputDesc->mDevice;
4464 }
4465 }
4466
Eric Laurentfb66dd92016-01-28 18:32:03 -08004467 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4468 if (isInCall()) {
4469 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4470 } else if (source != AUDIO_SOURCE_DEFAULT) {
4471 device = getDeviceAndMixForInputSource(source);
4472 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004473
Eric Laurente552edb2014-03-10 17:42:56 -07004474 return device;
4475}
4476
Eric Laurent794fde22016-03-11 09:50:45 -08004477bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4478 audio_stream_type_t stream2) {
4479 return ((stream1 == stream2) ||
4480 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4481 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004482}
4483
Eric Laurente0720872014-03-11 09:30:41 -07004484uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004485 return (uint32_t)getStrategy(stream);
4486}
4487
Eric Laurente0720872014-03-11 09:30:41 -07004488audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004489 // By checking the range of stream before calling getStrategy, we avoid
4490 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4491 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004492 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004493 return AUDIO_DEVICE_NONE;
4494 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004495 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004496 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4497 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004498 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 }
Eric Laurent794fde22016-03-11 09:50:45 -08004500 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004501 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004502 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004503 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4504 for (size_t i = 0; i < outputs.size(); i++) {
4505 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004506 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004507 curDevices |= outputDesc->device();
4508 }
4509 }
4510 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004511 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004512
4513 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4514 and doesn't really need to.*/
4515 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4516 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4517 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4518 }
Eric Laurente552edb2014-03-10 17:42:56 -07004519 return devices;
4520}
4521
François Gaffie2110e042015-03-24 08:41:51 +01004522routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4523{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004524 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004525 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004526}
4527
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004528uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4529 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004530 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4531 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4532 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004533 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4534 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4535 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004536 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004537 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004538}
4539
Eric Laurente0720872014-03-11 09:30:41 -07004540void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004541 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004542 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004543 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4544 updateDevicesAndOutputs();
4545 break;
4546 default:
4547 break;
4548 }
4549}
4550
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004551uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004552
4553 // skip beacon mute management if a dedicated TTS output is available
4554 if (mTtsOutputAvailable) {
4555 return 0;
4556 }
4557
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004558 switch(event) {
4559 case STARTING_OUTPUT:
4560 mBeaconMuteRefCount++;
4561 break;
4562 case STOPPING_OUTPUT:
4563 if (mBeaconMuteRefCount > 0) {
4564 mBeaconMuteRefCount--;
4565 }
4566 break;
4567 case STARTING_BEACON:
4568 mBeaconPlayingRefCount++;
4569 break;
4570 case STOPPING_BEACON:
4571 if (mBeaconPlayingRefCount > 0) {
4572 mBeaconPlayingRefCount--;
4573 }
4574 break;
4575 }
4576
4577 if (mBeaconMuteRefCount > 0) {
4578 // any playback causes beacon to be muted
4579 return setBeaconMute(true);
4580 } else {
4581 // no other playback: unmute when beacon starts playing, mute when it stops
4582 return setBeaconMute(mBeaconPlayingRefCount == 0);
4583 }
4584}
4585
4586uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4587 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4588 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4589 // keep track of muted state to avoid repeating mute/unmute operations
4590 if (mBeaconMuted != mute) {
4591 // mute/unmute AUDIO_STREAM_TTS on all outputs
4592 ALOGV("\t muting %d", mute);
4593 uint32_t maxLatency = 0;
4594 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004596 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004597 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004598 0 /*delay*/, AUDIO_DEVICE_NONE);
4599 const uint32_t latency = desc->latency() * 2;
4600 if (latency > maxLatency) {
4601 maxLatency = latency;
4602 }
4603 }
4604 mBeaconMuted = mute;
4605 return maxLatency;
4606 }
4607 return 0;
4608}
4609
Eric Laurente0720872014-03-11 09:30:41 -07004610audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004611 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004612{
Paul McLeanaa981192015-03-21 09:55:15 -07004613 // Routing
4614 // see if we have an explicit route
4615 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4616 // (getStrategy(stream)).
4617 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4618 // and activity count is non-zero
4619 // the device = the device from the descriptor in the RouteMap, and exit.
4620 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4621 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004622 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4623 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004624 return route->mDeviceDescriptor->type();
4625 }
4626 }
4627
Eric Laurente552edb2014-03-10 17:42:56 -07004628 if (fromCache) {
4629 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4630 strategy, mDeviceForStrategy[strategy]);
4631 return mDeviceForStrategy[strategy];
4632 }
François Gaffie2110e042015-03-24 08:41:51 +01004633 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004634}
4635
Eric Laurente0720872014-03-11 09:30:41 -07004636void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004637{
4638 for (int i = 0; i < NUM_STRATEGIES; i++) {
4639 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4640 }
4641 mPreviousOutputs = mOutputs;
4642}
4643
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004644uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004645 audio_devices_t prevDevice,
4646 uint32_t delayMs)
4647{
4648 // mute/unmute strategies using an incompatible device combination
4649 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4650 // if unmuting, unmute only after the specified delay
4651 if (outputDesc->isDuplicated()) {
4652 return 0;
4653 }
4654
4655 uint32_t muteWaitMs = 0;
4656 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004657 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004658
4659 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4660 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004661 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004662 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4663 bool doMute = false;
4664
4665 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4666 doMute = true;
4667 outputDesc->mStrategyMutedByDevice[i] = true;
4668 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4669 doMute = true;
4670 outputDesc->mStrategyMutedByDevice[i] = false;
4671 }
Eric Laurent99401132014-05-07 19:48:15 -07004672 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004673 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004674 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004675 // skip output if it does not share any device with current output
4676 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4677 == AUDIO_DEVICE_NONE) {
4678 continue;
4679 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004680 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004681 mute ? "muting" : "unmuting", i, curDevice);
4682 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004683 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004684 if (mute) {
4685 // FIXME: should not need to double latency if volume could be applied
4686 // immediately by the audioflinger mixer. We must account for the delay
4687 // between now and the next time the audioflinger thread for this output
4688 // will process a buffer (which corresponds to one buffer size,
4689 // usually 1/2 or 1/4 of the latency).
4690 if (muteWaitMs < desc->latency() * 2) {
4691 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004692 }
4693 }
4694 }
4695 }
4696 }
4697 }
4698
Eric Laurent99401132014-05-07 19:48:15 -07004699 // temporary mute output if device selection changes to avoid volume bursts due to
4700 // different per device volumes
4701 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004702 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4703 // temporary mute duration is conservatively set to 4 times the reported latency
4704 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4705 if (muteWaitMs < tempMuteWaitMs) {
4706 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004707 }
Eric Laurentdc462862016-07-19 12:29:53 -07004708
Eric Laurent99401132014-05-07 19:48:15 -07004709 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004710 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004711 // make sure that we do not start the temporary mute period too early in case of
4712 // delayed device change
4713 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004714 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004715 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004716 }
4717 }
4718 }
4719
Eric Laurente552edb2014-03-10 17:42:56 -07004720 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4721 if (muteWaitMs > delayMs) {
4722 muteWaitMs -= delayMs;
4723 usleep(muteWaitMs * 1000);
4724 return muteWaitMs;
4725 }
4726 return 0;
4727}
4728
Eric Laurentc75307b2015-03-17 15:29:32 -07004729uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004730 audio_devices_t device,
4731 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004733 audio_patch_handle_t *patchHandle,
4734 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004735{
Eric Laurentc75307b2015-03-17 15:29:32 -07004736 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004737 AudioParameter param;
4738 uint32_t muteWaitMs;
4739
4740 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004741 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4742 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004743 return muteWaitMs;
4744 }
4745 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4746 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004747 if ((device != AUDIO_DEVICE_NONE) &&
4748 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004749 return 0;
4750 }
4751
4752 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004753 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004754
4755 audio_devices_t prevDevice = outputDesc->mDevice;
4756
Paul McLeanaa981192015-03-21 09:55:15 -07004757 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004758
4759 if (device != AUDIO_DEVICE_NONE) {
4760 outputDesc->mDevice = device;
4761 }
4762 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4763
4764 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004765 // the requested device is AUDIO_DEVICE_NONE
4766 // OR the requested device is the same as current device
4767 // AND force is not specified
4768 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004769 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004770 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4771 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004772 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004773 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004774 return muteWaitMs;
4775 }
4776
4777 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004778
Eric Laurente552edb2014-03-10 17:42:56 -07004779 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004780 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004781 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004782 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004783 DeviceVector deviceList;
4784 if ((address == NULL) || (strlen(address) == 0)) {
4785 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4786 } else {
4787 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4788 }
4789
Eric Laurent1c333e22014-05-20 10:48:17 -07004790 if (!deviceList.isEmpty()) {
4791 struct audio_patch patch;
4792 outputDesc->toAudioPortConfig(&patch.sources[0]);
4793 patch.num_sources = 1;
4794 patch.num_sinks = 0;
4795 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4796 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004797 patch.num_sinks++;
4798 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 ssize_t index;
4800 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4801 index = mAudioPatches.indexOfKey(*patchHandle);
4802 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004803 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 }
4805 sp< AudioPatch> patchDesc;
4806 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4807 if (index >= 0) {
4808 patchDesc = mAudioPatches.valueAt(index);
4809 afPatchHandle = patchDesc->mAfPatchHandle;
4810 }
4811
Eric Laurent1c333e22014-05-20 10:48:17 -07004812 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004813 &afPatchHandle,
4814 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004815 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4816 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004817 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004818 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004819 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004820 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004821 addAudioPatch(patchDesc->mHandle, patchDesc);
4822 } else {
4823 patchDesc->mPatch = patch;
4824 }
4825 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004826 if (patchHandle) {
4827 *patchHandle = patchDesc->mHandle;
4828 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004829 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004830 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004831 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004832 }
4833 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004834
4835 // inform all input as well
4836 for (size_t i = 0; i < mInputs.size(); i++) {
4837 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004838 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004839 AudioParameter inputCmd = AudioParameter();
4840 ALOGV("%s: inform input %d of device:%d", __func__,
4841 inputDescriptor->mIoHandle, device);
4842 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4843 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4844 inputCmd.toString(),
4845 delayMs);
4846 }
4847 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 }
Eric Laurente552edb2014-03-10 17:42:56 -07004849
4850 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004851 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004852
4853 return muteWaitMs;
4854}
4855
Eric Laurentc75307b2015-03-17 15:29:32 -07004856status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004857 int delayMs,
4858 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004859{
Eric Laurent6a94d692014-05-20 11:18:06 -07004860 ssize_t index;
4861 if (patchHandle) {
4862 index = mAudioPatches.indexOfKey(*patchHandle);
4863 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004864 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 }
4866 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004867 return INVALID_OPERATION;
4868 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004869 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4870 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004871 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004872 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 removeAudioPatch(patchDesc->mHandle);
4874 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004875 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004876 return status;
4877}
4878
4879status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4880 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 bool force,
4882 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004883{
4884 status_t status = NO_ERROR;
4885
Eric Laurent1f2f2232014-06-02 12:01:23 -07004886 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004887 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4888 inputDesc->mDevice = device;
4889
4890 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4891 if (!deviceList.isEmpty()) {
4892 struct audio_patch patch;
4893 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004894 // AUDIO_SOURCE_HOTWORD is for internal use only:
4895 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004896 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004897 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004898 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4899 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 patch.num_sinks = 1;
4901 //only one input device for now
4902 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004903 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004904 ssize_t index;
4905 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4906 index = mAudioPatches.indexOfKey(*patchHandle);
4907 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004908 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 }
4910 sp< AudioPatch> patchDesc;
4911 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4912 if (index >= 0) {
4913 patchDesc = mAudioPatches.valueAt(index);
4914 afPatchHandle = patchDesc->mAfPatchHandle;
4915 }
4916
Eric Laurent1c333e22014-05-20 10:48:17 -07004917 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004919 0);
4920 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004922 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004924 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 addAudioPatch(patchDesc->mHandle, patchDesc);
4926 } else {
4927 patchDesc->mPatch = patch;
4928 }
4929 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 if (patchHandle) {
4931 *patchHandle = patchDesc->mHandle;
4932 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004933 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004934 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004935 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004936 }
4937 }
4938 }
4939 return status;
4940}
4941
Eric Laurent6a94d692014-05-20 11:18:06 -07004942status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4943 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004944{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004945 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 ssize_t index;
4947 if (patchHandle) {
4948 index = mAudioPatches.indexOfKey(*patchHandle);
4949 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004950 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 }
4952 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004953 return INVALID_OPERATION;
4954 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004955 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4956 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004957 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004958 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 removeAudioPatch(patchDesc->mHandle);
4960 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004961 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004962 return status;
4963}
4964
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004965sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004966 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004967 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004968 audio_format_t& format,
4969 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004970 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004971{
4972 // Choose an input profile based on the requested capture parameters: select the first available
4973 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004974 //
4975 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4976 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004977
4978 for (size_t i = 0; i < mHwModules.size(); i++)
4979 {
4980 if (mHwModules[i]->mHandle == 0) {
4981 continue;
4982 }
4983 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4984 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004986 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004987 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004988 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004989 format,
4990 &format /*updatedFormat*/,
4991 channelMask,
4992 &channelMask /*updatedChannelMask*/,
4993 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004994
Eric Laurente552edb2014-03-10 17:42:56 -07004995 return profile;
4996 }
4997 }
4998 }
4999 return NULL;
5000}
5001
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005002
5003audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005004 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005005{
François Gaffie036e1e92015-03-19 10:16:24 +01005006 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5007 audio_devices_t selectedDeviceFromMix =
5008 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005009
François Gaffie036e1e92015-03-19 10:16:24 +01005010 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5011 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005012 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005013 return getDeviceForInputSource(inputSource);
5014}
5015
5016audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5017{
Paul McLean466dc8e2015-04-17 13:15:36 -06005018 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5019 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005020 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005021 return route->mDeviceDescriptor->type();
5022 }
5023 }
5024
5025 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005026}
5027
Eric Laurente0720872014-03-11 09:30:41 -07005028float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005029 int index,
5030 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005031{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005032 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005033
5034 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5035 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5036 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5037 // the ringtone volume
5038 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5039 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5040 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5041 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5042 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5043 }
5044
Eric Laurente552edb2014-03-10 17:42:56 -07005045 // if a headset is connected, apply the following rules to ring tones and notifications
5046 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005047 // - always attenuate notifications volume by 6dB
5048 // - attenuate ring tones volume by 6dB unless music is not playing and
5049 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005050 // - if music is playing, always limit the volume to current music volume,
5051 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005052 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005053 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5054 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5055 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5056 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5057 ((stream_strategy == STRATEGY_SONIFICATION)
5058 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005059 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005060 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005061 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005062 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005063 // when the phone is ringing we must consider that music could have been paused just before
5064 // by the music application and behave as if music was active if the last music track was
5065 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005066 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005067 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005068 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005069 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005070 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005071 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5072 musicDevice),
5073 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005074 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5075 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005076 if (volumeDB > minVolDB) {
5077 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005078 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005079 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005080 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5081 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5082 // on A2DP, also ensure notification volume is not too low compared to media when
5083 // intended to be played
5084 if ((volumeDB > -96.0f) &&
5085 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5086 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5087 stream, device,
5088 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5089 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5090 }
5091 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005092 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5093 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005094 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005095 }
5096 }
5097
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005098 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005099}
5100
Eric Laurente0720872014-03-11 09:30:41 -07005101status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005102 int index,
5103 const sp<AudioOutputDescriptor>& outputDesc,
5104 audio_devices_t device,
5105 int delayMs,
5106 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005107{
Eric Laurente552edb2014-03-10 17:42:56 -07005108 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005109 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005110 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005111 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005112 return NO_ERROR;
5113 }
François Gaffie2110e042015-03-24 08:41:51 +01005114 audio_policy_forced_cfg_t forceUseForComm =
5115 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005116 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005117 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5118 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005119 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005120 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005121 return INVALID_OPERATION;
5122 }
5123
Eric Laurentc75307b2015-03-17 15:29:32 -07005124 if (device == AUDIO_DEVICE_NONE) {
5125 device = outputDesc->device();
5126 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005127
Eric Laurentffbc80f2015-03-18 18:30:19 -07005128 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005129 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005130 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005131 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005132
Eric Laurentffbc80f2015-03-18 18:30:19 -07005133 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005134
Eric Laurent3b73df72014-03-11 09:06:29 -07005135 if (stream == AUDIO_STREAM_VOICE_CALL ||
5136 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005137 float voiceVolume;
5138 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005139 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005140 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005141 } else {
5142 voiceVolume = 1.0;
5143 }
5144
Eric Laurent18fba842016-03-31 14:41:26 -07005145 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005146 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5147 mLastVoiceVolume = voiceVolume;
5148 }
5149 }
5150
5151 return NO_ERROR;
5152}
5153
Eric Laurentc75307b2015-03-17 15:29:32 -07005154void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5155 audio_devices_t device,
5156 int delayMs,
5157 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005158{
Eric Laurentc75307b2015-03-17 15:29:32 -07005159 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005160
Eric Laurent794fde22016-03-11 09:50:45 -08005161 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005162 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005163 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005164 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005165 device,
5166 delayMs,
5167 force);
5168 }
5169}
5170
Eric Laurente0720872014-03-11 09:30:41 -07005171void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005172 bool on,
5173 const sp<AudioOutputDescriptor>& outputDesc,
5174 int delayMs,
5175 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005176{
Eric Laurent72249d52015-06-08 11:12:15 -07005177 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5178 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005179 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005180 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005181 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005182 }
5183 }
5184}
5185
Eric Laurente0720872014-03-11 09:30:41 -07005186void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005187 bool on,
5188 const sp<AudioOutputDescriptor>& outputDesc,
5189 int delayMs,
5190 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005191{
Eric Laurente552edb2014-03-10 17:42:56 -07005192 if (device == AUDIO_DEVICE_NONE) {
5193 device = outputDesc->device();
5194 }
5195
Eric Laurentc75307b2015-03-17 15:29:32 -07005196 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5197 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005198
5199 if (on) {
5200 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005201 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005202 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005203 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005204 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005205 }
5206 }
5207 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5208 outputDesc->mMuteCount[stream]++;
5209 } else {
5210 if (outputDesc->mMuteCount[stream] == 0) {
5211 ALOGV("setStreamMute() unmuting non muted stream!");
5212 return;
5213 }
5214 if (--outputDesc->mMuteCount[stream] == 0) {
5215 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005216 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005218 device,
5219 delayMs);
5220 }
5221 }
5222}
5223
Eric Laurente0720872014-03-11 09:30:41 -07005224void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005225 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005226{
Eric Laurent87ffa392015-05-22 10:32:38 -07005227 if(!hasPrimaryOutput()) {
5228 return;
5229 }
5230
Eric Laurente552edb2014-03-10 17:42:56 -07005231 // if the stream pertains to sonification strategy and we are in call we must
5232 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5233 // in the device used for phone strategy and play the tone if the selected device does not
5234 // interfere with the device used for phone strategy
5235 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5236 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005237 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005238 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5239 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005240 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005241 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5242 stream, starting, outputDesc->mDevice, stateChange);
5243 if (outputDesc->mRefCount[stream]) {
5244 int muteCount = 1;
5245 if (stateChange) {
5246 muteCount = outputDesc->mRefCount[stream];
5247 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005248 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005249 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5250 for (int i = 0; i < muteCount; i++) {
5251 setStreamMute(stream, starting, mPrimaryOutput);
5252 }
5253 } else {
5254 ALOGV("handleIncallSonification() high visibility");
5255 if (outputDesc->device() &
5256 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5257 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5258 for (int i = 0; i < muteCount; i++) {
5259 setStreamMute(stream, starting, mPrimaryOutput);
5260 }
5261 }
5262 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005263 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5264 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005265 } else {
5266 mpClientInterface->stopTone();
5267 }
5268 }
5269 }
5270 }
5271}
5272
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005273audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5274{
5275 // flags to stream type mapping
5276 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5277 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5278 }
5279 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5280 return AUDIO_STREAM_BLUETOOTH_SCO;
5281 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005282 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5283 return AUDIO_STREAM_TTS;
5284 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005285
5286 // usage to stream type mapping
5287 switch (attr->usage) {
5288 case AUDIO_USAGE_MEDIA:
5289 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005290 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5291 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005292 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5293 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005294 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5295 return AUDIO_STREAM_SYSTEM;
5296 case AUDIO_USAGE_VOICE_COMMUNICATION:
5297 return AUDIO_STREAM_VOICE_CALL;
5298
5299 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5300 return AUDIO_STREAM_DTMF;
5301
5302 case AUDIO_USAGE_ALARM:
5303 return AUDIO_STREAM_ALARM;
5304 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5305 return AUDIO_STREAM_RING;
5306
5307 case AUDIO_USAGE_NOTIFICATION:
5308 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5309 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5310 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5311 case AUDIO_USAGE_NOTIFICATION_EVENT:
5312 return AUDIO_STREAM_NOTIFICATION;
5313
5314 case AUDIO_USAGE_UNKNOWN:
5315 default:
5316 return AUDIO_STREAM_MUSIC;
5317 }
5318}
Eric Laurente83b55d2014-11-14 10:06:21 -08005319
François Gaffie53615e22015-03-19 09:24:12 +01005320bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5321{
Eric Laurente83b55d2014-11-14 10:06:21 -08005322 // has flags that map to a strategy?
5323 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5324 return true;
5325 }
5326
5327 // has known usage?
5328 switch (paa->usage) {
5329 case AUDIO_USAGE_UNKNOWN:
5330 case AUDIO_USAGE_MEDIA:
5331 case AUDIO_USAGE_VOICE_COMMUNICATION:
5332 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5333 case AUDIO_USAGE_ALARM:
5334 case AUDIO_USAGE_NOTIFICATION:
5335 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5336 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5337 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5338 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5339 case AUDIO_USAGE_NOTIFICATION_EVENT:
5340 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5341 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5342 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5343 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005344 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005345 break;
5346 default:
5347 return false;
5348 }
5349 return true;
5350}
5351
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005352bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005353 routing_strategy strategy, uint32_t inPastMs,
5354 nsecs_t sysTime) const
5355{
5356 if ((sysTime == 0) && (inPastMs != 0)) {
5357 sysTime = systemTime();
5358 }
Eric Laurent794fde22016-03-11 09:50:45 -08005359 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005360 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5361 (NUM_STRATEGIES == strategy)) &&
5362 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5363 return true;
5364 }
5365 }
5366 return false;
5367}
5368
François Gaffie2110e042015-03-24 08:41:51 +01005369audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5370{
5371 return mEngine->getForceUse(usage);
5372}
5373
5374bool AudioPolicyManager::isInCall()
5375{
5376 return isStateInCall(mEngine->getPhoneState());
5377}
5378
5379bool AudioPolicyManager::isStateInCall(int state)
5380{
5381 return is_state_in_call(state);
5382}
5383
Eric Laurentd60560a2015-04-10 11:31:20 -07005384void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5385{
5386 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5387 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5388 if (sourceDesc->mDevice->equals(deviceDesc)) {
5389 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5390 stopAudioSource(sourceDesc->getHandle());
5391 }
5392 }
5393
5394 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5395 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5396 bool release = false;
5397 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5398 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5399 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5400 source->ext.device.type == deviceDesc->type()) {
5401 release = true;
5402 }
5403 }
5404 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5405 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5406 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5407 sink->ext.device.type == deviceDesc->type()) {
5408 release = true;
5409 }
5410 }
5411 if (release) {
5412 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5413 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5414 }
5415 }
5416}
5417
Phil Burk09bc4612016-02-24 15:58:15 -08005418// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005419void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5420 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005421 // TODO Set this based on Config properties.
5422 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005423
5424 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5425 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005426 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005427
5428 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005429 bool supportsAC3 = false;
5430 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005431 bool supportsIEC61937 = false;
5432 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5433 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005434 switch (format) {
5435 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005436 supportsAC3 = true;
5437 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005438 case AUDIO_FORMAT_E_AC3:
5439 case AUDIO_FORMAT_DTS:
5440 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005441 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005442 break;
5443 case AUDIO_FORMAT_IEC61937:
5444 supportsIEC61937 = true;
5445 break;
5446 default:
5447 break;
5448 }
5449 }
Phil Burk09bc4612016-02-24 15:58:15 -08005450
5451 // Modify formats based on surround preferences.
5452 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005453 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5454 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5455 // Remove surround sound related formats.
5456 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5457 audio_format_t format = formats[formatIndex];
5458 switch(format) {
5459 case AUDIO_FORMAT_AC3:
5460 case AUDIO_FORMAT_E_AC3:
5461 case AUDIO_FORMAT_DTS:
5462 case AUDIO_FORMAT_DTS_HD:
5463 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005464 formats.removeAt(formatIndex);
5465 break;
5466 default:
5467 formatIndex++; // keep it
5468 break;
5469 }
Phil Burk09bc4612016-02-24 15:58:15 -08005470 }
Phil Burk07ac1142016-03-25 13:39:29 -07005471 supportsAC3 = false;
5472 supportsOtherSurround = false;
5473 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005474 }
Phil Burk07ac1142016-03-25 13:39:29 -07005475 } else { // AUTO or ALWAYS
5476 // Most TVs support AC3 even if they do not report it in the EDID.
5477 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5478 && !supportsAC3) {
5479 formats.add(AUDIO_FORMAT_AC3);
5480 supportsAC3 = true;
5481 }
5482
5483 // If ALWAYS, add support for raw surround formats if all are missing.
5484 // This assumes that if any of these formats are reported by the HAL
5485 // then the report is valid and should not be modified.
5486 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5487 && !supportsOtherSurround) {
5488 formats.add(AUDIO_FORMAT_E_AC3);
5489 formats.add(AUDIO_FORMAT_DTS);
5490 formats.add(AUDIO_FORMAT_DTS_HD);
5491 supportsOtherSurround = true;
5492 }
5493
5494 // Add support for IEC61937 if any raw surround supported.
5495 // The HAL could do this but add it here, just in case.
5496 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5497 formats.add(AUDIO_FORMAT_IEC61937);
5498 supportsIEC61937 = true;
5499 }
Phil Burk09bc4612016-02-24 15:58:15 -08005500 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005501}
5502
5503// Modify the list of channel masks supported.
5504void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5505 ChannelsVector &channelMasks = *channelMasksPtr;
5506 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5507 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5508
5509 // If NEVER, then remove support for channelMasks > stereo.
5510 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5511 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5512 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5513 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5514 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5515 channelMasks.removeAt(maskIndex);
5516 } else {
5517 maskIndex++;
5518 }
5519 }
5520 // If ALWAYS, then make sure we at least support 5.1
5521 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5522 bool supports5dot1 = false;
5523 // Are there any channel masks that can be considered "surround"?
5524 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5525 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5526 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5527 supports5dot1 = true;
5528 break;
5529 }
5530 }
5531 // If not then add 5.1 support.
5532 if (!supports5dot1) {
5533 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5534 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5535 }
Phil Burk09bc4612016-02-24 15:58:15 -08005536 }
5537}
5538
Phil Burk00eeb322016-03-31 12:41:00 -07005539void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5540 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005541 AudioProfileVector &profiles)
5542{
5543 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005544
François Gaffie112b0af2015-11-19 16:13:25 +01005545 // Format MUST be checked first to update the list of AudioProfile
5546 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005547 reply = mpClientInterface->getParameters(
5548 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005549 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005550 AudioParameter repliedParameters(reply);
5551 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005552 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005553 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5554 return;
5555 }
Phil Burk09bc4612016-02-24 15:58:15 -08005556 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005557 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005558 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005559 }
Phil Burk09bc4612016-02-24 15:58:15 -08005560 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005561 }
5562 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5563
Eric Laurent20eb3a42016-01-26 18:39:17 -08005564 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005565 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005566 ChannelsVector channelMasks;
5567 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005568 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005569 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005570
5571 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005572 reply = mpClientInterface->getParameters(
5573 ioHandle,
5574 requestedParameters.toString() + ";" +
5575 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005576 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005577 AudioParameter repliedParameters(reply);
5578 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005579 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005580 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005581 }
5582 }
5583 if (profiles.hasDynamicChannelsFor(format)) {
5584 reply = mpClientInterface->getParameters(ioHandle,
5585 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005586 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005587 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005588 AudioParameter repliedParameters(reply);
5589 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005590 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005591 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005592 if (device == AUDIO_DEVICE_OUT_HDMI) {
5593 filterSurroundChannelMasks(&channelMasks);
5594 }
François Gaffie112b0af2015-11-19 16:13:25 +01005595 }
5596 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005597 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005598 }
5599}
Eric Laurentd60560a2015-04-10 11:31:20 -07005600
Eric Laurente552edb2014-03-10 17:42:56 -07005601}; // namespace android