blob: fe8318e59cf9450802186c55c4d1ba988ec097b6 [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
Phil Burk09bc4612016-02-24 15:58:15 -080017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
36#include <hardware/audio.h>
37#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
53// AudioPolicyInterface implementation
54// ----------------------------------------------------------------------------
55
Eric Laurente0720872014-03-11 09:30:41 -070056status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080057 audio_policy_dev_state_t state,
58 const char *device_address,
59 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070060{
Paul McLeane743a472015-01-28 11:07:31 -080061 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080062}
63
64status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080065 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080066 const char *device_address,
67 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080068{
Paul McLeane743a472015-01-28 11:07:31 -080069 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
70- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070071
72 // connect/disconnect only 1 device at a time
73 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
74
François Gaffie53615e22015-03-19 09:24:12 +010075 sp<DeviceDescriptor> devDesc =
76 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080077
Eric Laurente552edb2014-03-10 17:42:56 -070078 // handle output devices
79 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070080 SortedVector <audio_io_handle_t> outputs;
81
Eric Laurent3a4311c2014-03-17 12:00:47 -070082 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
83
Eric Laurente552edb2014-03-10 17:42:56 -070084 // save a copy of the opened output descriptors before any output is opened or closed
85 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
86 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -070087 switch (state)
88 {
89 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -080090 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -070092 ALOGW("setDeviceConnectionState() device already connected: %x", device);
93 return INVALID_OPERATION;
94 }
95 ALOGV("setDeviceConnectionState() connecting device %x", device);
96
Eric Laurente552edb2014-03-10 17:42:56 -070097 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -070098 index = mAvailableOutputDevices.add(devDesc);
99 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100100 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700101 if (module == 0) {
102 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
103 device);
104 mAvailableOutputDevices.remove(devDesc);
105 return INVALID_OPERATION;
106 }
Paul McLeane743a472015-01-28 11:07:31 -0800107 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700108 } else {
109 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700110 }
111
Eric Laurenta1d525f2015-01-29 13:36:45 -0800112 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700113 mAvailableOutputDevices.remove(devDesc);
114 return INVALID_OPERATION;
115 }
François Gaffie2110e042015-03-24 08:41:51 +0100116 // Propagate device availability to Engine
117 mEngine->setDeviceConnectionState(devDesc, state);
118
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700119 // outputs should never be empty here
120 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
121 "checkOutputsForDevice() returned no outputs but status OK");
122 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
123 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800124
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800125 // Send connect to HALs
Eric Laurent3ae5f312015-02-03 17:12:08 -0800126 AudioParameter param = AudioParameter(devDesc->mAddress);
127 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
128 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
129
130 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700132 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700133 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700134 ALOGW("setDeviceConnectionState() device not connected: %x", device);
135 return INVALID_OPERATION;
136 }
137
Paul McLean5c477aa2014-08-20 16:47:57 -0700138 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
139
Paul McLeane743a472015-01-28 11:07:31 -0800140 // Send Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800141 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700142 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
143 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
144
Eric Laurente552edb2014-03-10 17:42:56 -0700145 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700147
Eric Laurenta1d525f2015-01-29 13:36:45 -0800148 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100149
150 // Propagate device availability to Engine
151 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700152 } break;
153
154 default:
155 ALOGE("setDeviceConnectionState() invalid state: %x", state);
156 return BAD_VALUE;
157 }
158
Eric Laurent3a4311c2014-03-17 12:00:47 -0700159 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
160 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700161 checkA2dpSuspend();
162 checkOutputForAllStrategies();
163 // outputs must be closed after checkOutputForAllStrategies() is executed
164 if (!outputs.isEmpty()) {
165 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700166 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700167 // close unused outputs after device disconnection or direct outputs that have been
168 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700169 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700170 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
171 (desc->mDirectOpenCount == 0))) {
172 closeOutput(outputs[i]);
173 }
174 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700175 // check again after closing A2DP output to reset mA2dpSuspended if needed
176 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700177 }
178
179 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700180 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700181 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
182 updateCallRouting(newDevice);
183 }
Eric Laurente552edb2014-03-10 17:42:56 -0700184 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700185 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
186 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
187 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700188 // do not force device change on duplicated output because if device is 0, it will
189 // also force a device 0 for the two outputs it is duplicated to which may override
190 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700191 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100192 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700193 // always force when disconnecting (a non-duplicated device)
194 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700195 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700196 }
Eric Laurente552edb2014-03-10 17:42:56 -0700197 }
198
Eric Laurentd60560a2015-04-10 11:31:20 -0700199 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
200 cleanUpForDevice(devDesc);
201 }
202
Eric Laurent72aa32f2014-05-30 18:51:48 -0700203 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700204 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700205 } // end if is output device
206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // handle input devices
208 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700209 SortedVector <audio_io_handle_t> inputs;
210
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700212 switch (state)
213 {
214 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700217 ALOGW("setDeviceConnectionState() device already connected: %d", device);
218 return INVALID_OPERATION;
219 }
François Gaffie53615e22015-03-19 09:24:12 +0100220 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700221 if (module == NULL) {
222 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
223 device);
224 return INVALID_OPERATION;
225 }
Paul McLean9080a4c2015-06-18 08:24:02 -0700226 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700227 return INVALID_OPERATION;
228 }
229
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 index = mAvailableInputDevices.add(devDesc);
231 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800232 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 } else {
234 return NO_MEMORY;
235 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236
237 // Set connect to HALs
238 AudioParameter param = AudioParameter(devDesc->mAddress);
239 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
240 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
241
François Gaffie2110e042015-03-24 08:41:51 +0100242 // Propagate device availability to Engine
243 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700244 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700245
246 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700247 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700249 ALOGW("setDeviceConnectionState() device not connected: %d", device);
250 return INVALID_OPERATION;
251 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700252
253 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
254
255 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800256 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700257 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
258 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
259
Paul McLean9080a4c2015-06-18 08:24:02 -0700260 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700262
François Gaffie2110e042015-03-24 08:41:51 +0100263 // Propagate device availability to Engine
264 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700265 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700266
267 default:
268 ALOGE("setDeviceConnectionState() invalid state: %x", state);
269 return BAD_VALUE;
270 }
271
Eric Laurentd4692962014-05-05 18:13:44 -0700272 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700273
Eric Laurent87ffa392015-05-22 10:32:38 -0700274 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700275 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
276 updateCallRouting(newDevice);
277 }
278
Eric Laurentd60560a2015-04-10 11:31:20 -0700279 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
280 cleanUpForDevice(devDesc);
281 }
282
Eric Laurentb52c1522014-05-20 11:27:36 -0700283 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700284 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 ALOGW("setDeviceConnectionState() invalid device: %x", device);
288 return BAD_VALUE;
289}
290
Eric Laurente0720872014-03-11 09:30:41 -0700291audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100292 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700293{
François Gaffie53615e22015-03-19 09:24:12 +0100294 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(device, device_address, "");
295
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 DeviceVector *deviceVector;
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700300 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700301 deviceVector = &mAvailableInputDevices;
302 } else {
303 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
304 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700305 }
François Gaffie53615e22015-03-19 09:24:12 +0100306 return deviceVector->getDeviceConnectionState(devDesc);
Eric Laurenta1d525f2015-01-29 13:36:45 -0800307}
308
Eric Laurentc2730ba2014-07-20 15:47:07 -0700309void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
310{
311 bool createTxPatch = false;
312 struct audio_patch patch;
313 patch.num_sources = 1;
314 patch.num_sinks = 1;
315 status_t status;
316 audio_patch_handle_t afPatchHandle;
317 DeviceVector deviceList;
318
Eric Laurent87ffa392015-05-22 10:32:38 -0700319 if(!hasPrimaryOutput()) {
320 return;
321 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800322 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700323 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
324
325 // release existing RX patch if any
326 if (mCallRxPatch != 0) {
327 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
328 mCallRxPatch.clear();
329 }
330 // release TX patch if any
331 if (mCallTxPatch != 0) {
332 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
333 mCallTxPatch.clear();
334 }
335
336 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
337 // via setOutputDevice() on primary output.
338 // Otherwise, create two audio patches for TX and RX path.
339 if (availablePrimaryOutputDevices() & rxDevice) {
340 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
341 // If the TX device is also on the primary HW module, setOutputDevice() will take care
342 // of it due to legacy implementation. If not, create a patch.
343 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
344 == AUDIO_DEVICE_NONE) {
345 createTxPatch = true;
346 }
347 } else {
348 // create RX path audio patch
349 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
350 ALOG_ASSERT(!deviceList.isEmpty(),
351 "updateCallRouting() selected device not in output device list");
352 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
353 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
354 ALOG_ASSERT(!deviceList.isEmpty(),
355 "updateCallRouting() no telephony RX device");
356 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
357
358 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
359 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
360
361 // request to reuse existing output stream if one is already opened to reach the RX device
362 SortedVector<audio_io_handle_t> outputs =
363 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700364 audio_io_handle_t output = selectOutput(outputs,
365 AUDIO_OUTPUT_FLAG_NONE,
366 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700367 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700368 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700369 ALOG_ASSERT(!outputDesc->isDuplicated(),
370 "updateCallRouting() RX device output is duplicated");
371 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700372 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700373 patch.num_sources = 2;
374 }
375
376 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
377 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
378 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
379 status);
380 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100381 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700382 mCallRxPatch->mAfPatchHandle = afPatchHandle;
383 mCallRxPatch->mUid = mUidCached;
384 }
385 createTxPatch = true;
386 }
387 if (createTxPatch) {
388
389 struct audio_patch patch;
390 patch.num_sources = 1;
391 patch.num_sinks = 1;
392 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
393 ALOG_ASSERT(!deviceList.isEmpty(),
394 "updateCallRouting() selected device not in input device list");
395 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
396 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
397 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
398 ALOG_ASSERT(!deviceList.isEmpty(),
399 "updateCallRouting() no telephony TX device");
400 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
401 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
402
403 SortedVector<audio_io_handle_t> outputs =
404 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700405 audio_io_handle_t output = selectOutput(outputs,
406 AUDIO_OUTPUT_FLAG_NONE,
407 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700408 // request to reuse existing output stream if one is already opened to reach the TX
409 // path output device
410 if (output != AUDIO_IO_HANDLE_NONE) {
411 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
412 ALOG_ASSERT(!outputDesc->isDuplicated(),
413 "updateCallRouting() RX device output is duplicated");
414 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700415 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700416 patch.num_sources = 2;
417 }
418
Eric Laurentc0a889f2015-10-14 14:36:34 -0700419 // terminate active capture if on the same HW module as the call TX source device
420 // FIXME: would be better to refine to only inputs whose profile connects to the
421 // call TX device but this information is not in the audio patch and logic here must be
422 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800423 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
424 for (size_t i = 0; i < activeInputs.size(); i++) {
425 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
426 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
427 AudioSessionCollection activeSessions =
428 activeDesc->getAudioSessions(true /*activeOnly*/);
429 for (size_t j = 0; j < activeSessions.size(); j++) {
430 audio_session_t activeSession = activeSessions.keyAt(j);
431 stopInput(activeDesc->mIoHandle, activeSession);
432 releaseInput(activeDesc->mIoHandle, activeSession);
433 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700434 }
435 }
436
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
438 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
439 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
440 status);
441 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100442 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700443 mCallTxPatch->mAfPatchHandle = afPatchHandle;
444 mCallTxPatch->mUid = mUidCached;
445 }
446 }
447}
448
Eric Laurente0720872014-03-11 09:30:41 -0700449void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700450{
451 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100452 // store previous phone state for management of sonification strategy below
453 int oldState = mEngine->getPhoneState();
454
455 if (mEngine->setPhoneState(state) != NO_ERROR) {
456 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700457 return;
458 }
François Gaffie2110e042015-03-24 08:41:51 +0100459 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700460 // if leaving call state, handle special case of active streams
461 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700462 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700463 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800464 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700465 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700466 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800467
Eric Laurent63dea1d2015-07-02 17:10:28 -0700468 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800469 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700470 }
471
François Gaffie2110e042015-03-24 08:41:51 +0100472 /**
473 * Switching to or from incall state or switching between telephony and VoIP lead to force
474 * routing command.
475 */
476 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
477 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700478
479 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700480 checkA2dpSuspend();
481 checkOutputForAllStrategies();
482 updateDevicesAndOutputs();
483
Eric Laurente552edb2014-03-10 17:42:56 -0700484 int delayMs = 0;
485 if (isStateInCall(state)) {
486 nsecs_t sysTime = systemTime();
487 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700488 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700489 // mute media and sonification strategies and delay device switch by the largest
490 // latency of any output where either strategy is active.
491 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100492 if ((isStrategyActive(desc, STRATEGY_MEDIA,
493 SONIFICATION_HEADSET_MUSIC_DELAY,
494 sysTime) ||
495 isStrategyActive(desc, STRATEGY_SONIFICATION,
496 SONIFICATION_HEADSET_MUSIC_DELAY,
497 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700498 (delayMs < (int)desc->latency()*2)) {
499 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700500 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700501 setStrategyMute(STRATEGY_MEDIA, true, desc);
502 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700503 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700504 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
505 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700506 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
507 }
508 }
509
Eric Laurent87ffa392015-05-22 10:32:38 -0700510 if (hasPrimaryOutput()) {
511 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
512 // the device returned is not necessarily reachable via this output
513 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
514 // force routing command to audio hardware when ending call
515 // even if no device change is needed
516 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
517 rxDevice = mPrimaryOutput->device();
518 }
Eric Laurente552edb2014-03-10 17:42:56 -0700519
Eric Laurent87ffa392015-05-22 10:32:38 -0700520 if (state == AUDIO_MODE_IN_CALL) {
521 updateCallRouting(rxDevice, delayMs);
522 } else if (oldState == AUDIO_MODE_IN_CALL) {
523 if (mCallRxPatch != 0) {
524 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
525 mCallRxPatch.clear();
526 }
527 if (mCallTxPatch != 0) {
528 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
529 mCallTxPatch.clear();
530 }
531 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
532 } else {
533 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700534 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700535 }
Eric Laurente552edb2014-03-10 17:42:56 -0700536 // if entering in call state, handle special case of active streams
537 // pertaining to sonification strategy see handleIncallSonification()
538 if (isStateInCall(state)) {
539 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800540 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700541 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700542 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700543
544 // force reevaluating accessibility routing when call starts
545 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700546 }
547
548 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700549 if (state == AUDIO_MODE_RINGTONE &&
550 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700551 mLimitRingtoneVolume = true;
552 } else {
553 mLimitRingtoneVolume = false;
554 }
555}
556
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700557audio_mode_t AudioPolicyManager::getPhoneState() {
558 return mEngine->getPhoneState();
559}
560
Eric Laurente0720872014-03-11 09:30:41 -0700561void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700562 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700563{
François Gaffie2110e042015-03-24 08:41:51 +0100564 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700565
François Gaffie2110e042015-03-24 08:41:51 +0100566 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
567 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
568 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700569 }
François Gaffie2110e042015-03-24 08:41:51 +0100570 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
571 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
572 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700573
574 // check for device and output changes triggered by new force usage
575 checkA2dpSuspend();
576 checkOutputForAllStrategies();
577 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800578
Eric Laurent87ffa392015-05-22 10:32:38 -0700579 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700580 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
581 updateCallRouting(newDevice);
582 }
Eric Laurente552edb2014-03-10 17:42:56 -0700583 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700584 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
585 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
586 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
587 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700588 }
Eric Laurente552edb2014-03-10 17:42:56 -0700589 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700590 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700591 }
592 }
593
Eric Laurentfb66dd92016-01-28 18:32:03 -0800594 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
595 for (size_t i = 0; i < activeInputs.size(); i++) {
596 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
597 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700598 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800599 if (activeDesc->mProfile->getSupportedDevices().types() &
600 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
601 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700602 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800603 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700604 }
Eric Laurente552edb2014-03-10 17:42:56 -0700605 }
Eric Laurente552edb2014-03-10 17:42:56 -0700606}
607
Eric Laurente0720872014-03-11 09:30:41 -0700608void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700609{
610 ALOGV("setSystemProperty() property %s, value %s", property, value);
611}
612
613// Find a direct output profile compatible with the parameters passed, even if the input flags do
614// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800615sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700616 audio_devices_t device,
617 uint32_t samplingRate,
618 audio_format_t format,
619 audio_channel_mask_t channelMask,
620 audio_output_flags_t flags)
621{
Eric Laurent861a6282015-05-18 15:40:16 -0700622 // only retain flags that will drive the direct output profile selection
623 // if explicitly requested
624 static const uint32_t kRelevantFlags =
625 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
626 flags =
627 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
628
629 sp<IOProfile> profile;
630
Eric Laurente552edb2014-03-10 17:42:56 -0700631 for (size_t i = 0; i < mHwModules.size(); i++) {
632 if (mHwModules[i]->mHandle == 0) {
633 continue;
634 }
635 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700636 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
637 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700638 samplingRate, NULL /*updatedSamplingRate*/,
639 format, NULL /*updatedFormat*/,
640 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700641 flags)) {
642 continue;
643 }
644 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100645 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700646 continue;
647 }
648 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100649 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700650 continue;
651 }
652 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100653 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700654 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700655 }
Eric Laurente552edb2014-03-10 17:42:56 -0700656 }
657 }
Eric Laurent861a6282015-05-18 15:40:16 -0700658 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700659}
660
Eric Laurente0720872014-03-11 09:30:41 -0700661audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100662 uint32_t samplingRate,
663 audio_format_t format,
664 audio_channel_mask_t channelMask,
665 audio_output_flags_t flags,
666 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700667{
Eric Laurent3b73df72014-03-11 09:06:29 -0700668 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700669 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
670 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
671 device, stream, samplingRate, format, channelMask, flags);
672
Eric Laurente83b55d2014-11-14 10:06:21 -0800673 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
674 stream, samplingRate,format, channelMask,
675 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700676}
677
Eric Laurente83b55d2014-11-14 10:06:21 -0800678status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
679 audio_io_handle_t *output,
680 audio_session_t session,
681 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700682 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800683 uint32_t samplingRate,
684 audio_format_t format,
685 audio_channel_mask_t channelMask,
686 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700687 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800688 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700689{
Eric Laurente83b55d2014-11-14 10:06:21 -0800690 audio_attributes_t attributes;
691 if (attr != NULL) {
692 if (!isValidAttributes(attr)) {
693 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
694 attr->usage, attr->content_type, attr->flags,
695 attr->tags);
696 return BAD_VALUE;
697 }
698 attributes = *attr;
699 } else {
700 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
701 ALOGE("getOutputForAttr(): invalid stream type");
702 return BAD_VALUE;
703 }
704 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700705 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700706 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800707 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100708 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800709 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100710 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800711 }
François Gaffie036e1e92015-03-19 10:16:24 +0100712 *stream = streamTypefromAttributesInt(&attributes);
713 *output = desc->mIoHandle;
714 ALOGV("getOutputForAttr() returns output %d", *output);
715 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800716 }
717 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
718 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
719 return BAD_VALUE;
720 }
721
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700722 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
723 " session %d selectedDeviceId %d",
724 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
725 session, selectedDeviceId);
726
727 *stream = streamTypefromAttributesInt(&attributes);
728
729 // Explicit routing?
730 sp<DeviceDescriptor> deviceDesc;
731 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
732 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
733 deviceDesc = mAvailableOutputDevices[i];
734 break;
735 }
736 }
737 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700738
Eric Laurente83b55d2014-11-14 10:06:21 -0800739 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700740 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700741
Eric Laurente83b55d2014-11-14 10:06:21 -0800742 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700743 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
744 }
745
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700746 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700747 device, samplingRate, format, channelMask, flags);
748
Eric Laurente83b55d2014-11-14 10:06:21 -0800749 *output = getOutputForDevice(device, session, *stream,
750 samplingRate, format, channelMask,
751 flags, offloadInfo);
752 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700753 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800754 return INVALID_OPERATION;
755 }
Paul McLeanaa981192015-03-21 09:55:15 -0700756
Eric Laurente83b55d2014-11-14 10:06:21 -0800757 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700758}
759
760audio_io_handle_t AudioPolicyManager::getOutputForDevice(
761 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800762 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700763 audio_stream_type_t stream,
764 uint32_t samplingRate,
765 audio_format_t format,
766 audio_channel_mask_t channelMask,
767 audio_output_flags_t flags,
768 const audio_offload_info_t *offloadInfo)
769{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700770 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700771 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700772 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700773
Eric Laurente552edb2014-03-10 17:42:56 -0700774#ifdef AUDIO_POLICY_TEST
775 if (mCurOutput != 0) {
776 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
777 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
778
779 if (mTestOutputs[mCurOutput] == 0) {
780 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700781 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
782 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700783 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700784 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700785 outputDesc->mFlags =
786 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700787 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700788 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
789 config.sample_rate = mTestSamplingRate;
790 config.channel_mask = mTestChannels;
791 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700792 if (offloadInfo != NULL) {
793 config.offload_info = *offloadInfo;
794 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700795 status = mpClientInterface->openOutput(0,
796 &mTestOutputs[mCurOutput],
797 &config,
798 &outputDesc->mDevice,
799 String8(""),
800 &outputDesc->mLatency,
801 outputDesc->mFlags);
802 if (status == NO_ERROR) {
803 outputDesc->mSamplingRate = config.sample_rate;
804 outputDesc->mFormat = config.format;
805 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700806 AudioParameter outputCmd = AudioParameter();
807 outputCmd.addInt(String8("set_id"),mCurOutput);
808 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
809 addOutput(mTestOutputs[mCurOutput], outputDesc);
810 }
811 }
812 return mTestOutputs[mCurOutput];
813 }
814#endif //AUDIO_POLICY_TEST
815
816 // open a direct output if required by specified parameters
817 //force direct flag if offload flag is set: offloading implies a direct output stream
818 // and all common behaviors are driven by checking only the direct flag
819 // this should normally be set appropriately in the policy configuration file
820 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700821 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700822 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700823 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
824 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
825 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800826 // only allow deep buffering for music stream type
827 if (stream != AUDIO_STREAM_MUSIC) {
828 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700829 } else if (/* stream == AUDIO_STREAM_MUSIC && */
830 flags == AUDIO_OUTPUT_FLAG_NONE &&
831 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
832 // use DEEP_BUFFER as default output for music stream type
833 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800834 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700835 if (stream == AUDIO_STREAM_TTS) {
836 flags = AUDIO_OUTPUT_FLAG_TTS;
837 }
Eric Laurente552edb2014-03-10 17:42:56 -0700838
Eric Laurentb732cf52014-09-24 19:08:21 -0700839 sp<IOProfile> profile;
840
841 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700842 // and not explicitly requested
843 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800844 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700845 audio_channel_count_from_out_mask(channelMask) <= 2) {
846 goto non_direct_output;
847 }
848
Andy Hung2ddee192015-12-18 17:34:44 -0800849 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
850 // This prevents creating an offloaded track and tearing it down immediately after start
851 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700852 // FIXME: We should check the audio session here but we do not have it in this context.
853 // This may prevent offloading in rare situations where effects are left active by apps
854 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700855
Eric Laurente552edb2014-03-10 17:42:56 -0700856 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800857 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700858 profile = getProfileForDirectOutput(device,
859 samplingRate,
860 format,
861 channelMask,
862 (audio_output_flags_t)flags);
863 }
864
Eric Laurent1c333e22014-05-20 10:48:17 -0700865 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700866 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700867
868 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700869 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700870 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
871 outputDesc = desc;
872 // reuse direct output if currently open and configured with same parameters
873 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800874 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700875 (channelMask == outputDesc->mChannelMask)) {
876 outputDesc->mDirectOpenCount++;
877 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
878 return mOutputs.keyAt(i);
879 }
880 }
881 }
882 // close direct output if currently open and configured with different parameters
883 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700884 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700885 }
Eric Laurent861a6282015-05-18 15:40:16 -0700886
887 // if the selected profile is offloaded and no offload info was specified,
888 // create a default one
889 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100890 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700891 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
892 defaultOffloadInfo.sample_rate = samplingRate;
893 defaultOffloadInfo.channel_mask = channelMask;
894 defaultOffloadInfo.format = format;
895 defaultOffloadInfo.stream_type = stream;
896 defaultOffloadInfo.bit_rate = 0;
897 defaultOffloadInfo.duration_us = -1;
898 defaultOffloadInfo.has_video = true; // conservative
899 defaultOffloadInfo.is_streaming = true; // likely
900 offloadInfo = &defaultOffloadInfo;
901 }
902
Eric Laurentc75307b2015-03-17 15:29:32 -0700903 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700904 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700905 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700906 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700907 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
908 config.sample_rate = samplingRate;
909 config.channel_mask = channelMask;
910 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700911 if (offloadInfo != NULL) {
912 config.offload_info = *offloadInfo;
913 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700914 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700915 &output,
916 &config,
917 &outputDesc->mDevice,
918 String8(""),
919 &outputDesc->mLatency,
920 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700921
922 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700923 if (status != NO_ERROR ||
924 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800925 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700926 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700927 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
928 "format %d %d, channelMask %04x %04x", output, samplingRate,
929 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
930 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700931 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700932 mpClientInterface->closeOutput(output);
933 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800934 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800935 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800936 goto non_direct_output;
937 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700938 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700939 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700940 outputDesc->mSamplingRate = config.sample_rate;
941 outputDesc->mChannelMask = config.channel_mask;
942 outputDesc->mFormat = config.format;
943 outputDesc->mRefCount[stream] = 0;
944 outputDesc->mStopTime[stream] = 0;
945 outputDesc->mDirectOpenCount = 1;
946
Eric Laurente552edb2014-03-10 17:42:56 -0700947 audio_io_handle_t srcOutput = getOutputForEffect();
948 addOutput(output, outputDesc);
949 audio_io_handle_t dstOutput = getOutputForEffect();
950 if (dstOutput == output) {
951 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
952 }
953 mPreviousOutputs = mOutputs;
954 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700955 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700956 return output;
957 }
958
Eric Laurentb732cf52014-09-24 19:08:21 -0700959non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700960
961 // A request for HW A/V sync cannot fallback to a mixed output because time
962 // stamps are embedded in audio data
963 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
964 return AUDIO_IO_HANDLE_NONE;
965 }
966
Eric Laurente552edb2014-03-10 17:42:56 -0700967 // ignoring channel mask due to downmix capability in mixer
968
969 // open a non direct output
970
971 // for non direct outputs, only PCM is supported
972 if (audio_is_linear_pcm(format)) {
973 // get which output is suitable for the specified stream. The actual
974 // routing change will happen when startOutput() will be called
975 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
976
Eric Laurent8838a382014-09-08 16:44:28 -0700977 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
978 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
979 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
981 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
982 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
983
Paul McLeanaa981192015-03-21 09:55:15 -0700984 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -0700985
986 return output;
987}
988
Eric Laurente0720872014-03-11 09:30:41 -0700989audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700990 audio_output_flags_t flags,
991 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700992{
993 // select one output among several that provide a path to a particular device or set of
994 // devices (the list was previously build by getOutputsForDevice()).
995 // The priority is as follows:
996 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -0800997 // 2: the output with the bit depth the closest to the requested one
998 // 3: the primary output
999 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001000
1001 if (outputs.size() == 0) {
1002 return 0;
1003 }
1004 if (outputs.size() == 1) {
1005 return outputs[0];
1006 }
1007
1008 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001009 audio_io_handle_t outputForFlags = 0;
1010 audio_io_handle_t outputForPrimary = 0;
1011 audio_io_handle_t outputForFormat = 0;
1012 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1013 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001014
1015 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001016 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001017 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001018 // if a valid format is specified, skip output if not compatible
1019 if (format != AUDIO_FORMAT_INVALID) {
1020 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001021 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001022 continue;
1023 }
1024 } else if (!audio_is_linear_pcm(format)) {
1025 continue;
1026 }
Eric Laurente6930022016-02-11 10:20:40 -08001027 if (AudioPort::isBetterFormatMatch(
1028 outputDesc->mFormat, bestFormat, format)) {
1029 outputForFormat = outputs[i];
1030 bestFormat = outputDesc->mFormat;
1031 }
Eric Laurent8838a382014-09-08 16:44:28 -07001032 }
1033
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001034 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001035 if (commonFlags >= maxCommonFlags) {
1036 if (commonFlags == maxCommonFlags) {
1037 if (AudioPort::isBetterFormatMatch(
1038 outputDesc->mFormat, bestFormatForFlags, format)) {
1039 outputForFlags = outputs[i];
1040 bestFormatForFlags = outputDesc->mFormat;
1041 }
1042 } else {
1043 outputForFlags = outputs[i];
1044 maxCommonFlags = commonFlags;
1045 bestFormatForFlags = outputDesc->mFormat;
1046 }
Eric Laurente552edb2014-03-10 17:42:56 -07001047 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1048 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001049 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001050 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001051 }
1052 }
1053 }
1054
Eric Laurente6930022016-02-11 10:20:40 -08001055 if (outputForFlags != 0) {
1056 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001057 }
Eric Laurente6930022016-02-11 10:20:40 -08001058 if (outputForFormat != 0) {
1059 return outputForFormat;
1060 }
1061 if (outputForPrimary != 0) {
1062 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001063 }
1064
1065 return outputs[0];
1066}
1067
Eric Laurente0720872014-03-11 09:30:41 -07001068status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001069 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001070 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001071{
Paul McLeanaa981192015-03-21 09:55:15 -07001072 ALOGV("startOutput() output %d, stream %d, session %d",
1073 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001074 ssize_t index = mOutputs.indexOfKey(output);
1075 if (index < 0) {
1076 ALOGW("startOutput() unknown output %d", output);
1077 return BAD_VALUE;
1078 }
1079
Eric Laurentc75307b2015-03-17 15:29:32 -07001080 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1081
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001082 // Routing?
1083 mOutputRoutes.incRouteActivity(session);
1084
Eric Laurentc75307b2015-03-17 15:29:32 -07001085 audio_devices_t newDevice;
1086 if (outputDesc->mPolicyMix != NULL) {
1087 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent493404d2015-04-21 15:07:36 -07001088 } else if (mOutputRoutes.hasRouteChanged(session)) {
1089 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001090 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001091 } else {
1092 newDevice = AUDIO_DEVICE_NONE;
1093 }
1094
1095 uint32_t delayMs = 0;
1096
Eric Laurentc75307b2015-03-17 15:29:32 -07001097 status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
1098
1099 if (status != NO_ERROR) {
1100 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001101 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001102 }
1103 // Automatically enable the remote submix input when output is started on a re routing mix
1104 // of type MIX_TYPE_RECORDERS
1105 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1106 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1107 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1108 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001109 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001110 "remote-submix");
1111 }
1112
1113 if (delayMs != 0) {
1114 usleep(delayMs * 1000);
1115 }
1116
1117 return status;
1118}
1119
1120status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1121 audio_stream_type_t stream,
1122 audio_devices_t device,
1123 uint32_t *delayMs)
1124{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001125 // cannot start playback of STREAM_TTS if any other output is being used
1126 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001127
1128 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001129 if (stream == AUDIO_STREAM_TTS) {
1130 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001131 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001132 return INVALID_OPERATION;
1133 } else {
1134 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1135 }
1136 } else {
1137 // some playback other than beacon starts
1138 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1139 }
1140
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001141 // check active before incrementing usage count
1142 bool force = !outputDesc->isActive();
1143
Eric Laurente552edb2014-03-10 17:42:56 -07001144 // increment usage count for this stream on the requested output:
1145 // NOTE that the usage count is the same for duplicated output and hardware output which is
1146 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1147 outputDesc->changeRefCount(stream, 1);
1148
Eric Laurent493404d2015-04-21 15:07:36 -07001149 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001150 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001151 if (device == AUDIO_DEVICE_NONE) {
1152 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001153 }
Eric Laurente552edb2014-03-10 17:42:56 -07001154 routing_strategy strategy = getStrategy(stream);
1155 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001156 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1157 (beaconMuteLatency > 0);
1158 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001159 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001160 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001161 if (desc != outputDesc) {
1162 // force a device change if any other output is managed by the same hw
1163 // module and has a current device selection that differs from selected device.
1164 // In this case, the audio HAL must receive the new device selection so that it can
1165 // change the device currently selected by the other active output.
1166 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001167 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001168 force = true;
1169 }
1170 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001171 // a notification so that audio focus effect can propagate, or that a mute/unmute
1172 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001173 uint32_t latency = desc->latency();
1174 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1175 waitMs = latency;
1176 }
1177 }
1178 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001179 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
Eric Laurente552edb2014-03-10 17:42:56 -07001180
1181 // handle special case for sonification while in call
1182 if (isInCall()) {
1183 handleIncallSonification(stream, true, false);
1184 }
1185
1186 // apply volume rules for current stream and device if necessary
1187 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001188 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001189 outputDesc,
1190 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001191
1192 // update the outputs if starting an output with a stream that can affect notification
1193 // routing
1194 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001195
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001196 // force reevaluating accessibility routing when ringtone or alarm starts
1197 if (strategy == STRATEGY_SONIFICATION) {
1198 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1199 }
Eric Laurente552edb2014-03-10 17:42:56 -07001200 }
1201 return NO_ERROR;
1202}
1203
1204
Eric Laurente0720872014-03-11 09:30:41 -07001205status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001206 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001207 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001208{
1209 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1210 ssize_t index = mOutputs.indexOfKey(output);
1211 if (index < 0) {
1212 ALOGW("stopOutput() unknown output %d", output);
1213 return BAD_VALUE;
1214 }
1215
Eric Laurentc75307b2015-03-17 15:29:32 -07001216 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001217
Eric Laurentc75307b2015-03-17 15:29:32 -07001218 if (outputDesc->mRefCount[stream] == 1) {
1219 // Automatically disable the remote submix input when output is stopped on a
1220 // re routing mix of type MIX_TYPE_RECORDERS
1221 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1222 outputDesc->mPolicyMix != NULL &&
1223 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1224 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1225 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001226 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001227 "remote-submix");
1228 }
1229 }
1230
1231 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001232 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001233 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001234 int activityCount = mOutputRoutes.decRouteActivity(session);
1235 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1236
1237 if (forceDeviceUpdate) {
1238 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1239 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001240 }
1241
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001242 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001243}
1244
1245status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001246 audio_stream_type_t stream,
1247 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001248{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001249 // always handle stream stop, check which stream type is stopping
1250 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1251
Eric Laurente552edb2014-03-10 17:42:56 -07001252 // handle special case for sonification while in call
1253 if (isInCall()) {
1254 handleIncallSonification(stream, false, false);
1255 }
1256
1257 if (outputDesc->mRefCount[stream] > 0) {
1258 // decrement usage count of this stream on the output
1259 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001260
Eric Laurente552edb2014-03-10 17:42:56 -07001261 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001262 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001263 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001264 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001265 // delay the device switch by twice the latency because stopOutput() is executed when
1266 // the track stop() command is received and at that time the audio track buffer can
1267 // still contain data that needs to be drained. The latency only covers the audio HAL
1268 // and kernel buffers. Also the latency does not always include additional delay in the
1269 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001270 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001271
1272 // force restoring the device selection on other active outputs if it differs from the
1273 // one being selected for this output
1274 for (size_t i = 0; i < mOutputs.size(); i++) {
1275 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001276 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001277 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001278 desc->isActive() &&
1279 outputDesc->sharesHwModuleWith(desc) &&
1280 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001281 setOutputDevice(desc,
1282 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001283 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001284 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001285 }
1286 }
1287 // update the outputs if stopping one with a stream that can affect notification routing
1288 handleNotificationRoutingForStream(stream);
1289 }
1290 return NO_ERROR;
1291 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001292 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001293 return INVALID_OPERATION;
1294 }
1295}
1296
Eric Laurente83b55d2014-11-14 10:06:21 -08001297void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001298 audio_stream_type_t stream __unused,
1299 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001300{
1301 ALOGV("releaseOutput() %d", output);
1302 ssize_t index = mOutputs.indexOfKey(output);
1303 if (index < 0) {
1304 ALOGW("releaseOutput() releasing unknown output %d", output);
1305 return;
1306 }
1307
1308#ifdef AUDIO_POLICY_TEST
1309 int testIndex = testOutputIndex(output);
1310 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001311 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001312 if (outputDesc->isActive()) {
1313 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001314 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001315 mTestOutputs[testIndex] = 0;
1316 }
1317 return;
1318 }
1319#endif //AUDIO_POLICY_TEST
1320
Paul McLeanaa981192015-03-21 09:55:15 -07001321 // Routing
1322 mOutputRoutes.removeRoute(session);
1323
Eric Laurentc75307b2015-03-17 15:29:32 -07001324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001325 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001326 if (desc->mDirectOpenCount <= 0) {
1327 ALOGW("releaseOutput() invalid open count %d for output %d",
1328 desc->mDirectOpenCount, output);
1329 return;
1330 }
1331 if (--desc->mDirectOpenCount == 0) {
1332 closeOutput(output);
1333 // If effects where present on the output, audioflinger moved them to the primary
1334 // output by default: move them back to the appropriate output.
1335 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001336 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001337 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1338 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001340 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001341 }
1342 }
1343}
1344
1345
Eric Laurentcaf7f482014-11-25 17:50:47 -08001346status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1347 audio_io_handle_t *input,
1348 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001349 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001350 uint32_t samplingRate,
1351 audio_format_t format,
1352 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001353 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001354 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001355 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001356{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001357 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1358 "session %d, flags %#x",
1359 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001360
Eric Laurentcaf7f482014-11-25 17:50:47 -08001361 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001362 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001363
Eric Laurent275e8e92014-11-30 15:14:47 -08001364 audio_devices_t device;
1365 // handle legacy remote submix case where the address was not always specified
1366 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001367 audio_source_t inputSource = attr->source;
1368 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001369 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001370
Eric Laurentc447ded2015-01-06 08:47:05 -08001371 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1372 inputSource = AUDIO_SOURCE_MIC;
1373 }
1374 halInputSource = inputSource;
1375
Paul McLean466dc8e2015-04-17 13:15:36 -06001376 // Explicit routing?
1377 sp<DeviceDescriptor> deviceDesc;
1378 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1379 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1380 deviceDesc = mAvailableInputDevices[i];
1381 break;
1382 }
1383 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001384 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001385
Eric Laurentc447ded2015-01-06 08:47:05 -08001386 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001387 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001388 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001389 if (ret != NO_ERROR) {
1390 return ret;
1391 }
1392 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001393 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1394 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001395 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001396 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001397 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001398 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001399 return BAD_VALUE;
1400 }
Eric Laurentc722f302014-12-10 11:21:49 -08001401 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001402 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001403 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1404 // there is an external policy, but this input is attached to a mix of recorders,
1405 // meaning it receives audio injected into the framework, so the recorder doesn't
1406 // know about it and is therefore considered "legacy"
1407 *inputType = API_INPUT_LEGACY;
1408 } else {
1409 // recording a mix of players defined by an external policy, we're rerouting for
1410 // an external policy
1411 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1412 }
Eric Laurentc722f302014-12-10 11:21:49 -08001413 } else if (audio_is_remote_submix_device(device)) {
1414 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001415 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001416 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1417 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001418 } else {
1419 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001420 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001421
Eric Laurent599c7582015-12-07 18:05:55 -08001422 }
1423
1424 *input = getInputForDevice(device, address, session, uid, inputSource,
1425 samplingRate, format, channelMask, flags,
1426 policyMix);
1427 if (*input == AUDIO_IO_HANDLE_NONE) {
1428 mInputRoutes.removeRoute(session);
1429 return INVALID_OPERATION;
1430 }
1431 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1432 return NO_ERROR;
1433}
1434
1435
1436audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1437 String8 address,
1438 audio_session_t session,
1439 uid_t uid,
1440 audio_source_t inputSource,
1441 uint32_t samplingRate,
1442 audio_format_t format,
1443 audio_channel_mask_t channelMask,
1444 audio_input_flags_t flags,
1445 AudioMix *policyMix)
1446{
1447 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1448 audio_source_t halInputSource = inputSource;
1449 bool isSoundTrigger = false;
1450
1451 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1452 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1453 if (index >= 0) {
1454 input = mSoundTriggerSessions.valueFor(session);
1455 isSoundTrigger = true;
1456 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1457 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1458 } else {
1459 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001460 }
1461 }
1462
Andy Hungf129b032015-04-07 13:45:50 -07001463 // find a compatible input profile (not necessarily identical in parameters)
1464 sp<IOProfile> profile;
1465 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001466 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001467 audio_format_t profileFormat = format;
1468 audio_channel_mask_t profileChannelMask = channelMask;
1469 audio_input_flags_t profileFlags = flags;
1470 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001471 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001472 profileSamplingRate, profileFormat, profileChannelMask,
1473 profileFlags);
1474 if (profile != 0) {
1475 break; // success
1476 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1477 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1478 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001479 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1480 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001481 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001482 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001483 }
Eric Laurente552edb2014-03-10 17:42:56 -07001484 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001485 // Pick input sampling rate if not specified by client
1486 if (samplingRate == 0) {
1487 samplingRate = profileSamplingRate;
1488 }
Eric Laurente552edb2014-03-10 17:42:56 -07001489
Eric Laurent322b4d22015-04-03 15:57:54 -07001490 if (profile->getModuleHandle() == 0) {
1491 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001492 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001493 }
1494
Eric Laurent599c7582015-12-07 18:05:55 -08001495 sp<AudioSession> audioSession = new AudioSession(session,
1496 inputSource,
1497 format,
1498 samplingRate,
1499 channelMask,
1500 flags,
1501 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001502 isSoundTrigger,
1503 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001504
Eric Laurentfb66dd92016-01-28 18:32:03 -08001505
Eric Laurent599c7582015-12-07 18:05:55 -08001506 // reuse an open input if possible
1507 for (size_t i = 0; i < mInputs.size(); i++) {
1508 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001509 // reuse input if:
1510 // - it shares the same profile
1511 // AND
1512 // - it is not a reroute submix input
1513 // AND
1514 // - it is: not used for sound trigger
1515 // OR
1516 // used for sound trigger and all clients use the same session ID
1517 //
1518 if ((profile == desc->mProfile) &&
1519 (isSoundTrigger == desc->isSoundTrigger()) &&
1520 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001521
1522 sp<AudioSession> as = desc->getAudioSession(session);
1523 if (as != 0) {
1524 // do not allow unmatching properties on same session
1525 if (as->matches(audioSession)) {
1526 as->changeOpenCount(1);
1527 } else {
1528 ALOGW("getInputForDevice() record with different attributes"
1529 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001530 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001531 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001532 } else if (isSoundTrigger) {
1533 break;
1534 }
1535 // force close input if current source is now the highest priority request on this input
1536 // and current input properties are not exactly as requested.
1537 if ((desc->mSamplingRate != samplingRate ||
1538 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001539 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001540 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1541 source_priority(inputSource))) {
1542 ALOGV("%s: ", __FUNCTION__);
1543 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1544 for (size_t j = 0; j < sessions.size(); j++) {
1545 audio_session_t currentSession = sessions.keyAt(j);
1546 stopInput(desc->mIoHandle, currentSession);
1547 releaseInput(desc->mIoHandle, currentSession);
1548 }
1549 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001550 } else {
1551 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001552 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1553 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001554 }
Eric Laurent599c7582015-12-07 18:05:55 -08001555 }
1556 }
Eric Laurent599c7582015-12-07 18:05:55 -08001557
Eric Laurentcf2c0212014-07-25 16:20:43 -07001558 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001559 config.sample_rate = profileSamplingRate;
1560 config.channel_mask = profileChannelMask;
1561 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001562
Eric Laurent322b4d22015-04-03 15:57:54 -07001563 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001564 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001565 &config,
1566 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001567 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001568 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001569 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001570
1571 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001572 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001573 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001574 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001575 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001576 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1577 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001578 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001579 if (input != AUDIO_IO_HANDLE_NONE) {
1580 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001581 }
Eric Laurent599c7582015-12-07 18:05:55 -08001582 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001583 }
1584
Eric Laurent1f2f2232014-06-02 12:01:23 -07001585 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001586 inputDesc->mSamplingRate = profileSamplingRate;
1587 inputDesc->mFormat = profileFormat;
1588 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001589 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001590 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001591 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001592
Eric Laurent599c7582015-12-07 18:05:55 -08001593 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001594 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001595
Eric Laurent599c7582015-12-07 18:05:55 -08001596 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001597}
1598
Eric Laurentfb66dd92016-01-28 18:32:03 -08001599bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1600 const sp<AudioSession>& audioSession)
1601{
1602 // Do not allow capture if an active voice call is using a software patch and
1603 // the call TX source device is on the same HW module.
1604 // FIXME: would be better to refine to only inputs whose profile connects to the
1605 // call TX device but this information is not in the audio patch
1606 if (mCallTxPatch != 0 &&
1607 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1608 return false;
1609 }
1610
1611 // starting concurrent capture is enabled if:
1612 // 1) capturing for re-routing
1613 // 2) capturing for HOTWORD source
1614 // 3) capturing for FM TUNER source
1615 // 3) All other active captures are either for re-routing or HOTWORD
1616
1617 if (is_virtual_input_device(inputDesc->mDevice) ||
1618 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1619 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1620 return true;
1621 }
1622
1623 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1624 for (size_t i = 0; i < activeInputs.size(); i++) {
1625 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1626 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1627 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1628 !is_virtual_input_device(activeInput->mDevice)) {
1629 return false;
1630 }
1631 }
1632
1633 return true;
1634}
1635
1636
Eric Laurent4dc68062014-07-28 17:26:49 -07001637status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001638 audio_session_t session,
1639 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001640{
1641 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001642 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001643 ssize_t index = mInputs.indexOfKey(input);
1644 if (index < 0) {
1645 ALOGW("startInput() unknown input %d", input);
1646 return BAD_VALUE;
1647 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001648 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001649
Eric Laurent599c7582015-12-07 18:05:55 -08001650 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1651 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001652 ALOGW("startInput() unknown session %d on input %d", session, input);
1653 return BAD_VALUE;
1654 }
1655
Eric Laurentfb66dd92016-01-28 18:32:03 -08001656 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1657 ALOGW("startInput(%d) failed: other input already started", input);
1658 return INVALID_OPERATION;
1659 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001660
Eric Laurentfb66dd92016-01-28 18:32:03 -08001661 if (isInCall()) {
1662 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1663 }
1664 if (mInputs.activeInputsCount() != 0) {
1665 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001666 }
1667
Eric Laurent313d1e72016-01-29 09:56:57 -08001668 // increment activity count before calling getNewInputDevice() below as only active sessions
1669 // are considered for device selection
1670 audioSession->changeActiveCount(1);
1671
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001672 // Routing?
1673 mInputRoutes.incRouteActivity(session);
1674
Eric Laurent232f26f2016-02-17 18:06:27 -08001675 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
1676 // if input maps to a dynamic policy with an activity listener, notify of state change
1677 if ((inputDesc->mPolicyMix != NULL)
1678 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001679 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001680 MIX_STATE_MIXING);
1681 }
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001682
Eric Laurent232f26f2016-02-17 18:06:27 -08001683 if (mInputs.activeInputsCount() == 0) {
1684 SoundTrigger::setCaptureState(true);
1685 }
1686 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001687
Eric Laurent232f26f2016-02-17 18:06:27 -08001688 // automatically enable the remote submix output when input is started if not
1689 // used by a policy mix of type MIX_TYPE_RECORDERS
1690 // For remote submix (a virtual device), we open only one input per capture request.
1691 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1692 String8 address = String8("");
1693 if (inputDesc->mPolicyMix == NULL) {
1694 address = String8("0");
1695 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001696 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurentc722f302014-12-10 11:21:49 -08001697 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001698 if (address != "") {
1699 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1700 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1701 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001702 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001703 }
Eric Laurente552edb2014-03-10 17:42:56 -07001704 }
1705
Eric Laurent599c7582015-12-07 18:05:55 -08001706 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001707
Eric Laurente552edb2014-03-10 17:42:56 -07001708 return NO_ERROR;
1709}
1710
Eric Laurent4dc68062014-07-28 17:26:49 -07001711status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1712 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001713{
1714 ALOGV("stopInput() input %d", input);
1715 ssize_t index = mInputs.indexOfKey(input);
1716 if (index < 0) {
1717 ALOGW("stopInput() unknown input %d", input);
1718 return BAD_VALUE;
1719 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001720 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001721
Eric Laurent599c7582015-12-07 18:05:55 -08001722 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001723 if (index < 0) {
1724 ALOGW("stopInput() unknown session %d on input %d", session, input);
1725 return BAD_VALUE;
1726 }
1727
Eric Laurent599c7582015-12-07 18:05:55 -08001728 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001729 ALOGW("stopInput() input %d already stopped", input);
1730 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001731 }
1732
Eric Laurent599c7582015-12-07 18:05:55 -08001733 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001734
1735 // Routing?
1736 mInputRoutes.decRouteActivity(session);
1737
Eric Laurent232f26f2016-02-17 18:06:27 -08001738 if (!inputDesc->isActive()) {
1739 // if input maps to a dynamic policy with an activity listener, notify of state change
1740 if ((inputDesc->mPolicyMix != NULL)
1741 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001742 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001743 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001744 }
Eric Laurent4b2fcd82016-01-15 18:00:39 -08001745
Eric Laurent232f26f2016-02-17 18:06:27 -08001746 // automatically disable the remote submix output when input is stopped if not
1747 // used by a policy mix of type MIX_TYPE_RECORDERS
1748 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1749 String8 address = String8("");
1750 if (inputDesc->mPolicyMix == NULL) {
1751 address = String8("0");
1752 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001753 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurent4b2fcd82016-01-15 18:00:39 -08001754 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001755 if (address != "") {
1756 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1757 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1758 address, "remote-submix");
Eric Laurent84332aa2016-01-28 22:19:18 +00001759 }
1760
1761 resetInputDevice(input);
1762
1763 if (mInputs.activeInputsCount() == 0) {
1764 SoundTrigger::setCaptureState(false);
1765 }
1766 inputDesc->clearPreemptedSessions();
1767 }
Eric Laurente552edb2014-03-10 17:42:56 -07001768 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001769 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001770}
1771
Eric Laurent4dc68062014-07-28 17:26:49 -07001772void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1773 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001774{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001775
Eric Laurente552edb2014-03-10 17:42:56 -07001776 ALOGV("releaseInput() %d", input);
1777 ssize_t index = mInputs.indexOfKey(input);
1778 if (index < 0) {
1779 ALOGW("releaseInput() releasing unknown input %d", input);
1780 return;
1781 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001782
1783 // Routing
1784 mInputRoutes.removeRoute(session);
1785
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001786 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1787 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001788
Eric Laurent599c7582015-12-07 18:05:55 -08001789 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001790 if (index < 0) {
1791 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1792 return;
1793 }
Eric Laurent599c7582015-12-07 18:05:55 -08001794
1795 if (audioSession->openCount() == 0) {
1796 ALOGW("releaseInput() invalid open count %d on session %d",
1797 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001798 return;
1799 }
Eric Laurent599c7582015-12-07 18:05:55 -08001800
1801 if (audioSession->changeOpenCount(-1) == 0) {
1802 inputDesc->removeAudioSession(session);
1803 }
1804
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001805 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001806 ALOGV("releaseInput() exit > 0");
1807 return;
1808 }
1809
Eric Laurent05b90f82014-08-27 15:32:29 -07001810 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001811 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001812 ALOGV("releaseInput() exit");
1813}
1814
Eric Laurentd4692962014-05-05 18:13:44 -07001815void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001816 bool patchRemoved = false;
1817
Eric Laurentd4692962014-05-05 18:13:44 -07001818 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001819 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001820 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001821 if (patch_index >= 0) {
1822 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1823 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1824 mAudioPatches.removeItemsAt(patch_index);
1825 patchRemoved = true;
1826 }
Eric Laurentd4692962014-05-05 18:13:44 -07001827 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1828 }
1829 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001830 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001831 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001832
1833 if (patchRemoved) {
1834 mpClientInterface->onAudioPatchListUpdate();
1835 }
Eric Laurentd4692962014-05-05 18:13:44 -07001836}
1837
Eric Laurente0720872014-03-11 09:30:41 -07001838void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001839 int indexMin,
1840 int indexMax)
1841{
1842 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001843 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001844
1845 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001846 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1847 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001848 continue;
1849 }
1850 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001851 }
Eric Laurente552edb2014-03-10 17:42:56 -07001852}
1853
Eric Laurente0720872014-03-11 09:30:41 -07001854status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001855 int index,
1856 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001857{
1858
François Gaffied1ab2bd2015-12-02 18:20:06 +01001859 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1860 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001861 return BAD_VALUE;
1862 }
1863 if (!audio_is_output_device(device)) {
1864 return BAD_VALUE;
1865 }
1866
1867 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001868 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001869
1870 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1871 stream, device, index);
1872
1873 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1874 // clear all device specific values
1875 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01001876 mVolumeCurves->clearCurrentVolumeIndex(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001877 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001878
1879 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001880 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1881 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001882 continue;
1883 }
1884 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1885 }
Eric Laurente552edb2014-03-10 17:42:56 -07001886
Eric Laurent31551f82014-10-10 18:21:56 -07001887 // update volume on all outputs whose current device is also selected by the same
1888 // strategy as the device specified by the caller
Eric Laurente552edb2014-03-10 17:42:56 -07001889 status_t status = NO_ERROR;
1890 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001891 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1892 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001893 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1894 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001895 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001896 }
Eric Laurent794fde22016-03-11 09:50:45 -08001897 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08001898 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, true /*fromCache*/);
1899 // it is possible that the requested device is not selected by the strategy
1900 // (e.g an explicit audio patch is active causing getDevicesForStream()
1901 // to return this device. We must make sure that the device passed is part of the
1902 // devices considered when applying volume below.
1903 curStreamDevice |= device;
1904
1905 if (((device == AUDIO_DEVICE_OUT_DEFAULT) ||
1906 ((curDevice & curStreamDevice) != 0))) {
1907 status_t volStatus =
1908 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice);
1909 if (volStatus != NO_ERROR) {
1910 status = volStatus;
1911 }
1912 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001913 }
Eric Laurente552edb2014-03-10 17:42:56 -07001914 }
1915 return status;
1916}
1917
Eric Laurente0720872014-03-11 09:30:41 -07001918status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001919 int *index,
1920 audio_devices_t device)
1921{
1922 if (index == NULL) {
1923 return BAD_VALUE;
1924 }
1925 if (!audio_is_output_device(device)) {
1926 return BAD_VALUE;
1927 }
1928 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1929 // the strategy the stream belongs to.
1930 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1931 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1932 }
François Gaffiedfd74092015-03-19 12:10:59 +01001933 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001934
François Gaffied1ab2bd2015-12-02 18:20:06 +01001935 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07001936 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1937 return NO_ERROR;
1938}
1939
Eric Laurente0720872014-03-11 09:30:41 -07001940audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001941 const SortedVector<audio_io_handle_t>& outputs)
1942{
1943 // select one output among several suitable for global effects.
1944 // The priority is as follows:
1945 // 1: An offloaded output. If the effect ends up not being offloadable,
1946 // AudioFlinger will invalidate the track and the offloaded output
1947 // will be closed causing the effect to be moved to a PCM output.
1948 // 2: A deep buffer output
1949 // 3: the first output in the list
1950
1951 if (outputs.size() == 0) {
1952 return 0;
1953 }
1954
1955 audio_io_handle_t outputOffloaded = 0;
1956 audio_io_handle_t outputDeepBuffer = 0;
1957
1958 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001959 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001960 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001961 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1962 outputOffloaded = outputs[i];
1963 }
1964 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1965 outputDeepBuffer = outputs[i];
1966 }
1967 }
1968
1969 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1970 outputOffloaded, outputDeepBuffer);
1971 if (outputOffloaded != 0) {
1972 return outputOffloaded;
1973 }
1974 if (outputDeepBuffer != 0) {
1975 return outputDeepBuffer;
1976 }
1977
1978 return outputs[0];
1979}
1980
Eric Laurente0720872014-03-11 09:30:41 -07001981audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001982{
1983 // apply simple rule where global effects are attached to the same output as MUSIC streams
1984
Eric Laurent3b73df72014-03-11 09:06:29 -07001985 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001986 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1987 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1988
1989 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1990 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1991 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1992
1993 return output;
1994}
1995
Eric Laurente0720872014-03-11 09:30:41 -07001996status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001997 audio_io_handle_t io,
1998 uint32_t strategy,
1999 int session,
2000 int id)
2001{
2002 ssize_t index = mOutputs.indexOfKey(io);
2003 if (index < 0) {
2004 index = mInputs.indexOfKey(io);
2005 if (index < 0) {
2006 ALOGW("registerEffect() unknown io %d", io);
2007 return INVALID_OPERATION;
2008 }
2009 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002010 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002011}
2012
Eric Laurentc75307b2015-03-17 15:29:32 -07002013bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2014{
Eric Laurent28d09f02016-03-08 10:43:05 -08002015 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002016 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2017 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002018 continue;
2019 }
2020 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2021 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002022 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002023}
2024
2025bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2026{
2027 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2028}
2029
Eric Laurente0720872014-03-11 09:30:41 -07002030bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002031{
2032 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002033 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002034 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002035 return true;
2036 }
2037 }
2038 return false;
2039}
2040
Eric Laurent275e8e92014-11-30 15:14:47 -08002041// Register a list of custom mixes with their attributes and format.
2042// When a mix is registered, corresponding input and output profiles are
2043// added to the remote submix hw module. The profile contains only the
2044// parameters (sampling rate, format...) specified by the mix.
2045// The corresponding input remote submix device is also connected.
2046//
2047// When a remote submix device is connected, the address is checked to select the
2048// appropriate profile and the corresponding input or output stream is opened.
2049//
2050// When capture starts, getInputForAttr() will:
2051// - 1 look for a mix matching the address passed in attribtutes tags if any
2052// - 2 if none found, getDeviceForInputSource() will:
2053// - 2.1 look for a mix matching the attributes source
2054// - 2.2 if none found, default to device selection by policy rules
2055// At this time, the corresponding output remote submix device is also connected
2056// and active playback use cases can be transferred to this mix if needed when reconnecting
2057// after AudioTracks are invalidated
2058//
2059// When playback starts, getOutputForAttr() will:
2060// - 1 look for a mix matching the address passed in attribtutes tags if any
2061// - 2 if none found, look for a mix matching the attributes usage
2062// - 3 if none found, default to device and output selection by policy rules.
2063
2064status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2065{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002066 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2067 status_t res = NO_ERROR;
2068
2069 sp<HwModule> rSubmixModule;
2070 // examine each mix's route type
2071 for (size_t i = 0; i < mixes.size(); i++) {
2072 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2073 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2074 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002075 break;
2076 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002077 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2078 // Loop back through "remote submix"
2079 if (rSubmixModule == 0) {
2080 for (size_t j = 0; i < mHwModules.size(); j++) {
2081 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2082 && mHwModules[j]->mHandle != 0) {
2083 rSubmixModule = mHwModules[j];
2084 break;
2085 }
2086 }
2087 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002088
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002089 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002090
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002091 if (rSubmixModule == 0) {
2092 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2093 res = INVALID_OPERATION;
2094 break;
2095 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002096
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002097 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002098
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002099 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
2100 ALOGE(" Error regisering mix %zu for address %s", i, address.string());
2101 res = INVALID_OPERATION;
2102 break;
2103 }
2104 audio_config_t outputConfig = mixes[i].mFormat;
2105 audio_config_t inputConfig = mixes[i].mFormat;
2106 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2107 // stereo and let audio flinger do the channel conversion if needed.
2108 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2109 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2110 rSubmixModule->addOutputProfile(address, &outputConfig,
2111 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2112 rSubmixModule->addInputProfile(address, &inputConfig,
2113 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002114
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002115 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2116 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2117 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2118 address.string(), "remote-submix");
2119 } else {
2120 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2121 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2122 address.string(), "remote-submix");
2123 }
2124 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2125 ALOGV("registerPolicyMixes() mix %zu of %zu is RENDER", i, mixes.size());
2126 String8 address = mixes[i].mDeviceAddress;
2127
2128 audio_devices_t device = mixes[i].mDeviceType;
2129
2130 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2131 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2132 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2133 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2134 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2135 && (patch->mPatch.sinks[0].ext.device.type == device)
2136 && (patch->mPatch.sinks[0].ext.device.address == address)) {
2137
2138 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2139 res = INVALID_OPERATION;
2140 }
2141 break;
2142 }
2143 }
2144
2145 if (res != NO_ERROR) {
2146 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
2147 i,device, address.string());
2148 res = INVALID_OPERATION;
2149 break;
2150 }
Eric Laurentc722f302014-12-10 11:21:49 -08002151 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002152 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002153 if (res != NO_ERROR) {
2154 unregisterPolicyMixes(mixes);
2155 }
2156 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002157}
2158
2159status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2160{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002161 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002162 status_t res = NO_ERROR;
2163 sp<HwModule> rSubmixModule;
2164 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002165 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002166 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002167
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002168 if (rSubmixModule == 0) {
2169 for (size_t j = 0; i < mHwModules.size(); j++) {
2170 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2171 && mHwModules[j]->mHandle != 0) {
2172 rSubmixModule = mHwModules[j];
2173 break;
2174 }
2175 }
2176 }
2177 if (rSubmixModule == 0) {
2178 res = INVALID_OPERATION;
2179 continue;
2180 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002181
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002182 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002183
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002184 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2185 res = INVALID_OPERATION;
2186 continue;
2187 }
2188
2189 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2190 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2191 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2192 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2193 address.string(), "remote-submix");
2194 }
2195 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2196 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2197 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2198 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2199 address.string(), "remote-submix");
2200 }
2201 rSubmixModule->removeOutputProfile(address);
2202 rSubmixModule->removeInputProfile(address);
2203
2204 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2205 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2206 res = INVALID_OPERATION;
2207 continue;
2208 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002209 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002210 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002211 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002212}
2213
Eric Laurente552edb2014-03-10 17:42:56 -07002214
Eric Laurente0720872014-03-11 09:30:41 -07002215status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002216{
2217 const size_t SIZE = 256;
2218 char buffer[SIZE];
2219 String8 result;
2220
2221 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2222 result.append(buffer);
2223
Eric Laurent87ffa392015-05-22 10:32:38 -07002224 snprintf(buffer, SIZE, " Primary Output: %d\n",
2225 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002226 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002227 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002228 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002229 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002230 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002231 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002232 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002233 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002234 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002235 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002236 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002237 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002238 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002239 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002240 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002241 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002242 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002243 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2244 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2245 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002246 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2247 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002248 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2249 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002250
François Gaffie2110e042015-03-24 08:41:51 +01002251 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002252
François Gaffie112b0af2015-11-19 16:13:25 +01002253 mAvailableOutputDevices.dump(fd, String8("Available output"));
2254 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002255 mHwModules.dump(fd);
2256 mOutputs.dump(fd);
2257 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002258 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002259 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002260 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002261
2262 return NO_ERROR;
2263}
2264
2265// This function checks for the parameters which can be offloaded.
2266// This can be enhanced depending on the capability of the DSP and policy
2267// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002268bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002269{
2270 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002271 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002272 offloadInfo.sample_rate, offloadInfo.channel_mask,
2273 offloadInfo.format,
2274 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2275 offloadInfo.has_video);
2276
Andy Hung2ddee192015-12-18 17:34:44 -08002277 if (mMasterMono) {
2278 return false; // no offloading if mono is set.
2279 }
2280
Eric Laurente552edb2014-03-10 17:42:56 -07002281 // Check if offload has been disabled
2282 char propValue[PROPERTY_VALUE_MAX];
2283 if (property_get("audio.offload.disable", propValue, "0")) {
2284 if (atoi(propValue) != 0) {
2285 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2286 return false;
2287 }
2288 }
2289
2290 // Check if stream type is music, then only allow offload as of now.
2291 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2292 {
2293 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2294 return false;
2295 }
2296
2297 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002298 const bool allowOffloadWithVideo =
2299 property_get_bool("audio.offload.video", false /* default_value */);
2300 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002301 ALOGV("isOffloadSupported: has_video == true, returning false");
2302 return false;
2303 }
2304
2305 //If duration is less than minimum value defined in property, return false
2306 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2307 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2308 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2309 return false;
2310 }
2311 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2312 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2313 return false;
2314 }
2315
2316 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2317 // creating an offloaded track and tearing it down immediately after start when audioflinger
2318 // detects there is an active non offloadable effect.
2319 // FIXME: We should check the audio session here but we do not have it in this context.
2320 // This may prevent offloading in rare situations where effects are left active by apps
2321 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002322 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002323 return false;
2324 }
2325
2326 // See if there is a profile to support this.
2327 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002328 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002329 offloadInfo.sample_rate,
2330 offloadInfo.format,
2331 offloadInfo.channel_mask,
2332 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002333 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2334 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002335}
2336
Eric Laurent6a94d692014-05-20 11:18:06 -07002337status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2338 audio_port_type_t type,
2339 unsigned int *num_ports,
2340 struct audio_port *ports,
2341 unsigned int *generation)
2342{
2343 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2344 generation == NULL) {
2345 return BAD_VALUE;
2346 }
2347 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2348 if (ports == NULL) {
2349 *num_ports = 0;
2350 }
2351
2352 size_t portsWritten = 0;
2353 size_t portsMax = *num_ports;
2354 *num_ports = 0;
2355 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2356 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2357 for (size_t i = 0;
2358 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2359 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2360 }
2361 *num_ports += mAvailableOutputDevices.size();
2362 }
2363 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2364 for (size_t i = 0;
2365 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2366 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2367 }
2368 *num_ports += mAvailableInputDevices.size();
2369 }
2370 }
2371 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2372 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2373 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2374 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2375 }
2376 *num_ports += mInputs.size();
2377 }
2378 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002379 size_t numOutputs = 0;
2380 for (size_t i = 0; i < mOutputs.size(); i++) {
2381 if (!mOutputs[i]->isDuplicated()) {
2382 numOutputs++;
2383 if (portsWritten < portsMax) {
2384 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2385 }
2386 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002387 }
Eric Laurent84c70242014-06-23 08:46:27 -07002388 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002389 }
2390 }
2391 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002392 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002393 return NO_ERROR;
2394}
2395
2396status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2397{
2398 return NO_ERROR;
2399}
2400
Eric Laurent6a94d692014-05-20 11:18:06 -07002401status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2402 audio_patch_handle_t *handle,
2403 uid_t uid)
2404{
2405 ALOGV("createAudioPatch()");
2406
2407 if (handle == NULL || patch == NULL) {
2408 return BAD_VALUE;
2409 }
2410 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2411
Eric Laurent874c42872014-08-08 15:13:39 -07002412 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2413 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2414 return BAD_VALUE;
2415 }
2416 // only one source per audio patch supported for now
2417 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002418 return INVALID_OPERATION;
2419 }
Eric Laurent874c42872014-08-08 15:13:39 -07002420
2421 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002422 return INVALID_OPERATION;
2423 }
Eric Laurent874c42872014-08-08 15:13:39 -07002424 for (size_t i = 0; i < patch->num_sinks; i++) {
2425 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2426 return INVALID_OPERATION;
2427 }
2428 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002429
2430 sp<AudioPatch> patchDesc;
2431 ssize_t index = mAudioPatches.indexOfKey(*handle);
2432
Eric Laurent6a94d692014-05-20 11:18:06 -07002433 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2434 patch->sources[0].role,
2435 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002436#if LOG_NDEBUG == 0
2437 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002438 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002439 patch->sinks[i].role,
2440 patch->sinks[i].type);
2441 }
2442#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002443
2444 if (index >= 0) {
2445 patchDesc = mAudioPatches.valueAt(index);
2446 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2447 mUidCached, patchDesc->mUid, uid);
2448 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2449 return INVALID_OPERATION;
2450 }
2451 } else {
2452 *handle = 0;
2453 }
2454
2455 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002456 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002457 if (outputDesc == NULL) {
2458 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2459 return BAD_VALUE;
2460 }
Eric Laurent84c70242014-06-23 08:46:27 -07002461 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2462 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002463 if (patchDesc != 0) {
2464 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2465 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2466 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2467 return BAD_VALUE;
2468 }
2469 }
Eric Laurent874c42872014-08-08 15:13:39 -07002470 DeviceVector devices;
2471 for (size_t i = 0; i < patch->num_sinks; i++) {
2472 // Only support mix to devices connection
2473 // TODO add support for mix to mix connection
2474 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2475 ALOGV("createAudioPatch() source mix but sink is not a device");
2476 return INVALID_OPERATION;
2477 }
2478 sp<DeviceDescriptor> devDesc =
2479 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2480 if (devDesc == 0) {
2481 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2482 return BAD_VALUE;
2483 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002484
François Gaffie53615e22015-03-19 09:24:12 +01002485 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002486 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002487 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002488 NULL, // updatedSamplingRate
2489 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002490 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002491 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002492 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002493 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002494 ALOGV("createAudioPatch() profile not supported for device %08x",
2495 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002496 return INVALID_OPERATION;
2497 }
2498 devices.add(devDesc);
2499 }
2500 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002501 return INVALID_OPERATION;
2502 }
Eric Laurent874c42872014-08-08 15:13:39 -07002503
Eric Laurent6a94d692014-05-20 11:18:06 -07002504 // TODO: reconfigure output format and channels here
2505 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002506 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002507 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002508 index = mAudioPatches.indexOfKey(*handle);
2509 if (index >= 0) {
2510 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2511 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2512 }
2513 patchDesc = mAudioPatches.valueAt(index);
2514 patchDesc->mUid = uid;
2515 ALOGV("createAudioPatch() success");
2516 } else {
2517 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2518 return INVALID_OPERATION;
2519 }
2520 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2521 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2522 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002523 // only one sink supported when connecting an input device to a mix
2524 if (patch->num_sinks > 1) {
2525 return INVALID_OPERATION;
2526 }
François Gaffie53615e22015-03-19 09:24:12 +01002527 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002528 if (inputDesc == NULL) {
2529 return BAD_VALUE;
2530 }
2531 if (patchDesc != 0) {
2532 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2533 return BAD_VALUE;
2534 }
2535 }
2536 sp<DeviceDescriptor> devDesc =
2537 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2538 if (devDesc == 0) {
2539 return BAD_VALUE;
2540 }
2541
François Gaffie53615e22015-03-19 09:24:12 +01002542 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002543 devDesc->mAddress,
2544 patch->sinks[0].sample_rate,
2545 NULL, /*updatedSampleRate*/
2546 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002547 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002548 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002549 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002550 // FIXME for the parameter type,
2551 // and the NONE
2552 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002553 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002554 return INVALID_OPERATION;
2555 }
2556 // TODO: reconfigure output format and channels here
2557 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002558 devDesc->type(), inputDesc->mIoHandle);
2559 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002560 index = mAudioPatches.indexOfKey(*handle);
2561 if (index >= 0) {
2562 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2563 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2564 }
2565 patchDesc = mAudioPatches.valueAt(index);
2566 patchDesc->mUid = uid;
2567 ALOGV("createAudioPatch() success");
2568 } else {
2569 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2570 return INVALID_OPERATION;
2571 }
2572 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2573 // device to device connection
2574 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002575 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002576 return BAD_VALUE;
2577 }
2578 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002579 sp<DeviceDescriptor> srcDeviceDesc =
2580 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002581 if (srcDeviceDesc == 0) {
2582 return BAD_VALUE;
2583 }
Eric Laurent874c42872014-08-08 15:13:39 -07002584
Eric Laurent6a94d692014-05-20 11:18:06 -07002585 //update source and sink with our own data as the data passed in the patch may
2586 // be incomplete.
2587 struct audio_patch newPatch = *patch;
2588 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002589
Eric Laurent874c42872014-08-08 15:13:39 -07002590 for (size_t i = 0; i < patch->num_sinks; i++) {
2591 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2592 ALOGV("createAudioPatch() source device but one sink is not a device");
2593 return INVALID_OPERATION;
2594 }
2595
2596 sp<DeviceDescriptor> sinkDeviceDesc =
2597 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2598 if (sinkDeviceDesc == 0) {
2599 return BAD_VALUE;
2600 }
2601 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2602
Eric Laurent3bcf8592015-04-03 12:13:24 -07002603 // create a software bridge in PatchPanel if:
2604 // - source and sink devices are on differnt HW modules OR
2605 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002606 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002607 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002608 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002609 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002610 return INVALID_OPERATION;
2611 }
Eric Laurent874c42872014-08-08 15:13:39 -07002612 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002613 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002614 // if the sink device is reachable via an opened output stream, request to go via
2615 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002616 audio_io_handle_t output = selectOutput(outputs,
2617 AUDIO_OUTPUT_FLAG_NONE,
2618 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002619 if (output != AUDIO_IO_HANDLE_NONE) {
2620 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2621 if (outputDesc->isDuplicated()) {
2622 return INVALID_OPERATION;
2623 }
2624 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002625 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002626 newPatch.num_sources = 2;
2627 }
Eric Laurent83b88082014-06-20 18:31:16 -07002628 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002629 }
2630 // TODO: check from routing capabilities in config file and other conflicting patches
2631
2632 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2633 if (index >= 0) {
2634 afPatchHandle = patchDesc->mAfPatchHandle;
2635 }
2636
2637 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2638 &afPatchHandle,
2639 0);
2640 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2641 status, afPatchHandle);
2642 if (status == NO_ERROR) {
2643 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002644 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002645 addAudioPatch(patchDesc->mHandle, patchDesc);
2646 } else {
2647 patchDesc->mPatch = newPatch;
2648 }
2649 patchDesc->mAfPatchHandle = afPatchHandle;
2650 *handle = patchDesc->mHandle;
2651 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002652 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002653 } else {
2654 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2655 status);
2656 return INVALID_OPERATION;
2657 }
2658 } else {
2659 return BAD_VALUE;
2660 }
2661 } else {
2662 return BAD_VALUE;
2663 }
2664 return NO_ERROR;
2665}
2666
2667status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2668 uid_t uid)
2669{
2670 ALOGV("releaseAudioPatch() patch %d", handle);
2671
2672 ssize_t index = mAudioPatches.indexOfKey(handle);
2673
2674 if (index < 0) {
2675 return BAD_VALUE;
2676 }
2677 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2678 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2679 mUidCached, patchDesc->mUid, uid);
2680 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2681 return INVALID_OPERATION;
2682 }
2683
2684 struct audio_patch *patch = &patchDesc->mPatch;
2685 patchDesc->mUid = mUidCached;
2686 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002688 if (outputDesc == NULL) {
2689 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2690 return BAD_VALUE;
2691 }
2692
Eric Laurentc75307b2015-03-17 15:29:32 -07002693 setOutputDevice(outputDesc,
2694 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002695 true,
2696 0,
2697 NULL);
2698 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2699 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002700 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002701 if (inputDesc == NULL) {
2702 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2703 return BAD_VALUE;
2704 }
2705 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002706 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002707 true,
2708 NULL);
2709 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2710 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2711 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2712 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2713 status, patchDesc->mAfPatchHandle);
2714 removeAudioPatch(patchDesc->mHandle);
2715 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002716 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002717 } else {
2718 return BAD_VALUE;
2719 }
2720 } else {
2721 return BAD_VALUE;
2722 }
2723 return NO_ERROR;
2724}
2725
2726status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2727 struct audio_patch *patches,
2728 unsigned int *generation)
2729{
François Gaffie53615e22015-03-19 09:24:12 +01002730 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002731 return BAD_VALUE;
2732 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002733 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002734 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002735}
2736
Eric Laurente1715a42014-05-20 11:30:42 -07002737status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002738{
Eric Laurente1715a42014-05-20 11:30:42 -07002739 ALOGV("setAudioPortConfig()");
2740
2741 if (config == NULL) {
2742 return BAD_VALUE;
2743 }
2744 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2745 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002746 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2747 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002748 }
2749
Eric Laurenta121f902014-06-03 13:32:54 -07002750 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002751 if (config->type == AUDIO_PORT_TYPE_MIX) {
2752 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002753 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002754 if (outputDesc == NULL) {
2755 return BAD_VALUE;
2756 }
Eric Laurent84c70242014-06-23 08:46:27 -07002757 ALOG_ASSERT(!outputDesc->isDuplicated(),
2758 "setAudioPortConfig() called on duplicated output %d",
2759 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002760 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002761 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002762 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002763 if (inputDesc == NULL) {
2764 return BAD_VALUE;
2765 }
Eric Laurenta121f902014-06-03 13:32:54 -07002766 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002767 } else {
2768 return BAD_VALUE;
2769 }
2770 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2771 sp<DeviceDescriptor> deviceDesc;
2772 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2773 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2774 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2775 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2776 } else {
2777 return BAD_VALUE;
2778 }
2779 if (deviceDesc == NULL) {
2780 return BAD_VALUE;
2781 }
Eric Laurenta121f902014-06-03 13:32:54 -07002782 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002783 } else {
2784 return BAD_VALUE;
2785 }
2786
Eric Laurenta121f902014-06-03 13:32:54 -07002787 struct audio_port_config backupConfig;
2788 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2789 if (status == NO_ERROR) {
2790 struct audio_port_config newConfig;
2791 audioPortConfig->toAudioPortConfig(&newConfig, config);
2792 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002793 }
Eric Laurenta121f902014-06-03 13:32:54 -07002794 if (status != NO_ERROR) {
2795 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002796 }
Eric Laurente1715a42014-05-20 11:30:42 -07002797
2798 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002799}
2800
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002801void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2802{
Eric Laurentd60560a2015-04-10 11:31:20 -07002803 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002804 clearAudioPatches(uid);
2805 clearSessionRoutes(uid);
2806}
2807
Eric Laurent6a94d692014-05-20 11:18:06 -07002808void AudioPolicyManager::clearAudioPatches(uid_t uid)
2809{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002810 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002811 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2812 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002813 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002814 }
2815 }
2816}
2817
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002818void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2819 audio_io_handle_t ouptutToSkip)
2820{
2821 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2822 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2823 for (size_t j = 0; j < mOutputs.size(); j++) {
2824 if (mOutputs.keyAt(j) == ouptutToSkip) {
2825 continue;
2826 }
2827 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2828 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2829 continue;
2830 }
2831 // If the default device for this strategy is on another output mix,
2832 // invalidate all tracks in this strategy to force re connection.
2833 // Otherwise select new device on the output mix.
2834 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002835 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002836 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2837 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2838 }
2839 }
2840 } else {
2841 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2842 setOutputDevice(outputDesc, newDevice, false);
2843 }
2844 }
2845}
2846
2847void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2848{
2849 // remove output routes associated with this uid
2850 SortedVector<routing_strategy> affectedStrategies;
2851 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2852 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2853 if (route->mUid == uid) {
2854 mOutputRoutes.removeItemsAt(i);
2855 if (route->mDeviceDescriptor != 0) {
2856 affectedStrategies.add(getStrategy(route->mStreamType));
2857 }
2858 }
2859 }
2860 // reroute outputs if necessary
2861 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2862 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2863 }
2864
2865 // remove input routes associated with this uid
2866 SortedVector<audio_source_t> affectedSources;
2867 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2868 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2869 if (route->mUid == uid) {
2870 mInputRoutes.removeItemsAt(i);
2871 if (route->mDeviceDescriptor != 0) {
2872 affectedSources.add(route->mSource);
2873 }
2874 }
2875 }
2876 // reroute inputs if necessary
2877 SortedVector<audio_io_handle_t> inputsToClose;
2878 for (size_t i = 0; i < mInputs.size(); i++) {
2879 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002880 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002881 inputsToClose.add(inputDesc->mIoHandle);
2882 }
2883 }
2884 for (size_t i = 0; i < inputsToClose.size(); i++) {
2885 closeInput(inputsToClose[i]);
2886 }
2887}
2888
Eric Laurentd60560a2015-04-10 11:31:20 -07002889void AudioPolicyManager::clearAudioSources(uid_t uid)
2890{
2891 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2892 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2893 if (sourceDesc->mUid == uid) {
2894 stopAudioSource(mAudioSources.keyAt(i));
2895 }
2896 }
2897}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002898
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002899status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2900 audio_io_handle_t *ioHandle,
2901 audio_devices_t *device)
2902{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08002903 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2904 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002905 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002906
François Gaffiedf372692015-03-19 10:43:27 +01002907 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002908}
2909
Eric Laurentd60560a2015-04-10 11:31:20 -07002910status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2911 const audio_attributes_t *attributes,
2912 audio_io_handle_t *handle,
2913 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002914{
Eric Laurentd60560a2015-04-10 11:31:20 -07002915 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2916 if (source == NULL || attributes == NULL || handle == NULL) {
2917 return BAD_VALUE;
2918 }
2919
2920 *handle = AUDIO_IO_HANDLE_NONE;
2921
2922 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2923 source->type != AUDIO_PORT_TYPE_DEVICE) {
2924 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2925 return INVALID_OPERATION;
2926 }
2927
2928 sp<DeviceDescriptor> srcDeviceDesc =
2929 mAvailableInputDevices.getDevice(source->ext.device.type,
2930 String8(source->ext.device.address));
2931 if (srcDeviceDesc == 0) {
2932 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2933 return BAD_VALUE;
2934 }
2935 sp<AudioSourceDescriptor> sourceDesc =
2936 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2937
2938 struct audio_patch dummyPatch;
2939 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2940 sourceDesc->mPatchDesc = patchDesc;
2941
2942 status_t status = connectAudioSource(sourceDesc);
2943 if (status == NO_ERROR) {
2944 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2945 *handle = sourceDesc->getHandle();
2946 }
2947 return status;
2948}
2949
2950status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2951{
2952 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2953
2954 // make sure we only have one patch per source.
2955 disconnectAudioSource(sourceDesc);
2956
2957 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08002958 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07002959 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2960
2961 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2962 sp<DeviceDescriptor> sinkDeviceDesc =
2963 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2964
2965 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2966 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2967
2968 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2969 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002970 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002971 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2972 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2973 // create patch between src device and output device
2974 // create Hwoutput and add to mHwOutputs
2975 } else {
2976 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2977 audio_io_handle_t output =
2978 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2979 if (output == AUDIO_IO_HANDLE_NONE) {
2980 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2981 return INVALID_OPERATION;
2982 }
2983 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2984 if (outputDesc->isDuplicated()) {
2985 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2986 return INVALID_OPERATION;
2987 }
2988 // create a special patch with no sink and two sources:
2989 // - the second source indicates to PatchPanel through which output mix this patch should
2990 // be connected as well as the stream type for volume control
2991 // - the sink is defined by whatever output device is currently selected for the output
2992 // though which this patch is routed.
2993 patch->num_sinks = 0;
2994 patch->num_sources = 2;
2995 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2996 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2997 patch->sources[1].ext.mix.usecase.stream = stream;
2998 status_t status = mpClientInterface->createAudioPatch(patch,
2999 &afPatchHandle,
3000 0);
3001 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3002 status, afPatchHandle);
3003 if (status != NO_ERROR) {
3004 ALOGW("%s patch panel could not connect device patch, error %d",
3005 __FUNCTION__, status);
3006 return INVALID_OPERATION;
3007 }
3008 uint32_t delayMs = 0;
3009 status = startSource(outputDesc, stream, sinkDevice, &delayMs);
3010
3011 if (status != NO_ERROR) {
3012 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3013 return status;
3014 }
3015 sourceDesc->mSwOutput = outputDesc;
3016 if (delayMs != 0) {
3017 usleep(delayMs * 1000);
3018 }
3019 }
3020
3021 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3022 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3023
3024 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003025}
3026
Eric Laurent493404d2015-04-21 15:07:36 -07003027status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003028{
Eric Laurentd60560a2015-04-10 11:31:20 -07003029 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3030 ALOGV("%s handle %d", __FUNCTION__, handle);
3031 if (sourceDesc == 0) {
3032 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3033 return BAD_VALUE;
3034 }
3035 status_t status = disconnectAudioSource(sourceDesc);
3036
3037 mAudioSources.removeItem(handle);
3038 return status;
3039}
3040
Andy Hung2ddee192015-12-18 17:34:44 -08003041status_t AudioPolicyManager::setMasterMono(bool mono)
3042{
3043 if (mMasterMono == mono) {
3044 return NO_ERROR;
3045 }
3046 mMasterMono = mono;
3047 // if enabling mono we close all offloaded devices, which will invalidate the
3048 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3049 // for recreating the new AudioTrack as non-offloaded PCM.
3050 //
3051 // If disabling mono, we leave all tracks as is: we don't know which clients
3052 // and tracks are able to be recreated as offloaded. The next "song" should
3053 // play back offloaded.
3054 if (mMasterMono) {
3055 Vector<audio_io_handle_t> offloaded;
3056 for (size_t i = 0; i < mOutputs.size(); ++i) {
3057 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3058 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3059 offloaded.push(desc->mIoHandle);
3060 }
3061 }
3062 for (size_t i = 0; i < offloaded.size(); ++i) {
3063 closeOutput(offloaded[i]);
3064 }
3065 }
3066 // update master mono for all remaining outputs
3067 for (size_t i = 0; i < mOutputs.size(); ++i) {
3068 updateMono(mOutputs.keyAt(i));
3069 }
3070 return NO_ERROR;
3071}
3072
3073status_t AudioPolicyManager::getMasterMono(bool *mono)
3074{
3075 *mono = mMasterMono;
3076 return NO_ERROR;
3077}
3078
Eric Laurentd60560a2015-04-10 11:31:20 -07003079status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3080{
3081 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3082
3083 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3084 if (patchDesc == 0) {
3085 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3086 sourceDesc->mPatchDesc->mHandle);
3087 return BAD_VALUE;
3088 }
3089 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3090
Eric Laurent28d09f02016-03-08 10:43:05 -08003091 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003092 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3093 if (swOutputDesc != 0) {
3094 stopSource(swOutputDesc, stream, false);
3095 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3096 } else {
3097 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3098 if (hwOutputDesc != 0) {
3099 // release patch between src device and output device
3100 // close Hwoutput and remove from mHwOutputs
3101 } else {
3102 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3103 }
3104 }
3105 return NO_ERROR;
3106}
3107
3108sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3109 audio_io_handle_t output, routing_strategy strategy)
3110{
3111 sp<AudioSourceDescriptor> source;
3112 for (size_t i = 0; i < mAudioSources.size(); i++) {
3113 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3114 routing_strategy sourceStrategy =
3115 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3116 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3117 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3118 source = sourceDesc;
3119 break;
3120 }
3121 }
3122 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003123}
3124
Eric Laurente552edb2014-03-10 17:42:56 -07003125// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003126// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003127// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003128uint32_t AudioPolicyManager::nextAudioPortGeneration()
3129{
3130 return android_atomic_inc(&mAudioPortGeneration);
3131}
3132
Eric Laurente0720872014-03-11 09:30:41 -07003133AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003134 :
3135#ifdef AUDIO_POLICY_TEST
3136 Thread(false),
3137#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003138 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003139 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003140 mAudioPortGeneration(1),
3141 mBeaconMuteRefCount(0),
3142 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003143 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003144 mTtsOutputAvailable(false),
3145 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003146{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003147 mUidCached = getuid();
3148 mpClientInterface = clientInterface;
3149
3150 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3151 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3152 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3153 bool speakerDrcEnabled = false;
3154
3155#ifdef USE_XML_AUDIO_POLICY_CONF
3156 mVolumeCurves = new VolumeCurvesCollection();
3157 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3158 mDefaultOutputDevice, speakerDrcEnabled,
3159 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3160 PolicySerializer serializer;
3161 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3162#else
3163 mVolumeCurves = new StreamDescriptorCollection();
3164 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3165 mDefaultOutputDevice, speakerDrcEnabled);
3166 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3167 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3168#endif
3169 ALOGE("could not load audio policy configuration file, setting defaults");
3170 config.setDefault();
3171 }
3172 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3173 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3174
3175 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003176 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3177 if (!engineInstance) {
3178 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3179 return;
3180 }
3181 // Retrieve the Policy Manager Interface
3182 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3183 if (mEngine == NULL) {
3184 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3185 return;
3186 }
3187 mEngine->setObserver(this);
3188 status_t status = mEngine->initCheck();
3189 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3190
Eric Laurent3a4311c2014-03-17 12:00:47 -07003191 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003192 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003193 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3194 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003195 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003196 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003197 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003198 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003199 continue;
3200 }
3201 // open all output streams needed to access attached devices
3202 // except for direct output streams that are only opened when they are actually
3203 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003204 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003205 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3206 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003207 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003208
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003209 if (!outProfile->hasSupportedDevices()) {
3210 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003211 continue;
3212 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003213 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003214 mTtsOutputAvailable = true;
3215 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003216
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003217 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003218 continue;
3219 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003220 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003221 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3222 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003223 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003224 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003225 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003226 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003227 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003228 if ((profileType & outputDeviceTypes) == 0) {
3229 continue;
3230 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003231 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3232 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003233
3234 outputDesc->mDevice = profileType;
3235 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3236 config.sample_rate = outputDesc->mSamplingRate;
3237 config.channel_mask = outputDesc->mChannelMask;
3238 config.format = outputDesc->mFormat;
3239 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003240 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003241 &output,
3242 &config,
3243 &outputDesc->mDevice,
3244 String8(""),
3245 &outputDesc->mLatency,
3246 outputDesc->mFlags);
3247
3248 if (status != NO_ERROR) {
3249 ALOGW("Cannot open output stream for device %08x on hw module %s",
3250 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003251 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003252 } else {
3253 outputDesc->mSamplingRate = config.sample_rate;
3254 outputDesc->mChannelMask = config.channel_mask;
3255 outputDesc->mFormat = config.format;
3256
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003257 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3258 for (size_t k = 0; k < supportedDevices.size(); k++) {
3259 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003260 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003261 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3262 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003263 }
3264 }
3265 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003266 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003267 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003268 }
3269 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003270 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003271 outputDesc->mDevice,
3272 true);
3273 }
Eric Laurente552edb2014-03-10 17:42:56 -07003274 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003275 // open input streams needed to access attached devices to validate
3276 // mAvailableInputDevices list
3277 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3278 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003279 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003280
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003281 if (!inProfile->hasSupportedDevices()) {
3282 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003283 continue;
3284 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003285 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003286 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003287 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3288
Eric Laurentd78f1532014-09-16 16:38:20 -07003289 if ((profileType & inputDeviceTypes) == 0) {
3290 continue;
3291 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003292 sp<AudioInputDescriptor> inputDesc =
3293 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003294
Eric Laurentd78f1532014-09-16 16:38:20 -07003295 inputDesc->mDevice = profileType;
3296
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003297 // find the address
3298 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3299 // the inputs vector must be of size 1, but we don't want to crash here
3300 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3301 : String8("");
3302 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3303 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3304
Eric Laurentd78f1532014-09-16 16:38:20 -07003305 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3306 config.sample_rate = inputDesc->mSamplingRate;
3307 config.channel_mask = inputDesc->mChannelMask;
3308 config.format = inputDesc->mFormat;
3309 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003310 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003311 &input,
3312 &config,
3313 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003314 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003315 AUDIO_SOURCE_MIC,
3316 AUDIO_INPUT_FLAG_NONE);
3317
3318 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003319 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3320 for (size_t k = 0; k < supportedDevices.size(); k++) {
3321 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003322 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003323 if (index >= 0) {
3324 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3325 if (!devDesc->isAttached()) {
3326 devDesc->attach(mHwModules[i]);
3327 devDesc->importAudioPort(inProfile);
3328 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003329 }
3330 }
3331 mpClientInterface->closeInput(input);
3332 } else {
3333 ALOGW("Cannot open input stream for device %08x on hw module %s",
3334 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003335 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003336 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003337 }
3338 }
3339 // make sure all attached devices have been allocated a unique ID
3340 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003341 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003342 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003343 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3344 continue;
3345 }
François Gaffie2110e042015-03-24 08:41:51 +01003346 // The device is now validated and can be appended to the available devices of the engine
3347 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3348 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003349 i++;
3350 }
3351 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003352 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003353 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003354 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3355 continue;
3356 }
François Gaffie2110e042015-03-24 08:41:51 +01003357 // The device is now validated and can be appended to the available devices of the engine
3358 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3359 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003360 i++;
3361 }
3362 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003363 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003364 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003365 }
Eric Laurente552edb2014-03-10 17:42:56 -07003366
3367 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3368
3369 updateDevicesAndOutputs();
3370
3371#ifdef AUDIO_POLICY_TEST
3372 if (mPrimaryOutput != 0) {
3373 AudioParameter outputCmd = AudioParameter();
3374 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003375 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003376
3377 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3378 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003379 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3380 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003381 mTestLatencyMs = 0;
3382 mCurOutput = 0;
3383 mDirectOutput = false;
3384 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3385 mTestOutputs[i] = 0;
3386 }
3387
3388 const size_t SIZE = 256;
3389 char buffer[SIZE];
3390 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3391 run(buffer, ANDROID_PRIORITY_AUDIO);
3392 }
3393#endif //AUDIO_POLICY_TEST
3394}
3395
Eric Laurente0720872014-03-11 09:30:41 -07003396AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003397{
3398#ifdef AUDIO_POLICY_TEST
3399 exit();
3400#endif //AUDIO_POLICY_TEST
3401 for (size_t i = 0; i < mOutputs.size(); i++) {
3402 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003403 }
3404 for (size_t i = 0; i < mInputs.size(); i++) {
3405 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003406 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003407 mAvailableOutputDevices.clear();
3408 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003409 mOutputs.clear();
3410 mInputs.clear();
3411 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003412}
3413
Eric Laurente0720872014-03-11 09:30:41 -07003414status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003415{
Eric Laurent87ffa392015-05-22 10:32:38 -07003416 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003417}
3418
3419#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003420bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003421{
3422 ALOGV("entering threadLoop()");
3423 while (!exitPending())
3424 {
3425 String8 command;
3426 int valueInt;
3427 String8 value;
3428
3429 Mutex::Autolock _l(mLock);
3430 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3431
3432 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3433 AudioParameter param = AudioParameter(command);
3434
3435 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3436 valueInt != 0) {
3437 ALOGV("Test command %s received", command.string());
3438 String8 target;
3439 if (param.get(String8("target"), target) != NO_ERROR) {
3440 target = "Manager";
3441 }
3442 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3443 param.remove(String8("test_cmd_policy_output"));
3444 mCurOutput = valueInt;
3445 }
3446 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3447 param.remove(String8("test_cmd_policy_direct"));
3448 if (value == "false") {
3449 mDirectOutput = false;
3450 } else if (value == "true") {
3451 mDirectOutput = true;
3452 }
3453 }
3454 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3455 param.remove(String8("test_cmd_policy_input"));
3456 mTestInput = valueInt;
3457 }
3458
3459 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3460 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003461 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003462 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003463 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003464 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003465 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003466 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003467 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003468 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003469 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003470 if (target == "Manager") {
3471 mTestFormat = format;
3472 } else if (mTestOutputs[mCurOutput] != 0) {
3473 AudioParameter outputParam = AudioParameter();
3474 outputParam.addInt(String8("format"), format);
3475 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3476 }
3477 }
3478 }
3479 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3480 param.remove(String8("test_cmd_policy_channels"));
3481 int channels = 0;
3482
3483 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003484 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003485 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003486 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003487 }
3488 if (channels != 0) {
3489 if (target == "Manager") {
3490 mTestChannels = channels;
3491 } else if (mTestOutputs[mCurOutput] != 0) {
3492 AudioParameter outputParam = AudioParameter();
3493 outputParam.addInt(String8("channels"), channels);
3494 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3495 }
3496 }
3497 }
3498 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3499 param.remove(String8("test_cmd_policy_sampleRate"));
3500 if (valueInt >= 0 && valueInt <= 96000) {
3501 int samplingRate = valueInt;
3502 if (target == "Manager") {
3503 mTestSamplingRate = samplingRate;
3504 } else if (mTestOutputs[mCurOutput] != 0) {
3505 AudioParameter outputParam = AudioParameter();
3506 outputParam.addInt(String8("sampling_rate"), samplingRate);
3507 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3508 }
3509 }
3510 }
3511
3512 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3513 param.remove(String8("test_cmd_policy_reopen"));
3514
Eric Laurentc75307b2015-03-17 15:29:32 -07003515 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003516
Eric Laurentc75307b2015-03-17 15:29:32 -07003517 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003518
Eric Laurentc75307b2015-03-17 15:29:32 -07003519 removeOutput(mPrimaryOutput->mIoHandle);
3520 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3521 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003522 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003523 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3524 config.sample_rate = outputDesc->mSamplingRate;
3525 config.channel_mask = outputDesc->mChannelMask;
3526 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003527 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003528 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003529 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003530 &config,
3531 &outputDesc->mDevice,
3532 String8(""),
3533 &outputDesc->mLatency,
3534 outputDesc->mFlags);
3535 if (status != NO_ERROR) {
3536 ALOGE("Failed to reopen hardware output stream, "
3537 "samplingRate: %d, format %d, channels %d",
3538 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003539 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003540 outputDesc->mSamplingRate = config.sample_rate;
3541 outputDesc->mChannelMask = config.channel_mask;
3542 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003543 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003544 AudioParameter outputCmd = AudioParameter();
3545 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003546 mpClientInterface->setParameters(handle, outputCmd.toString());
3547 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003548 }
3549 }
3550
3551
3552 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3553 }
3554 }
3555 return false;
3556}
3557
Eric Laurente0720872014-03-11 09:30:41 -07003558void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003559{
3560 {
3561 AutoMutex _l(mLock);
3562 requestExit();
3563 mWaitWorkCV.signal();
3564 }
3565 requestExitAndWait();
3566}
3567
Eric Laurente0720872014-03-11 09:30:41 -07003568int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003569{
3570 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3571 if (output == mTestOutputs[i]) return i;
3572 }
3573 return 0;
3574}
3575#endif //AUDIO_POLICY_TEST
3576
3577// ---
3578
Eric Laurentc75307b2015-03-17 15:29:32 -07003579void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003580{
François Gaffie98cc1912015-03-18 17:52:40 +01003581 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003582 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003583 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003584 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003585}
3586
François Gaffie53615e22015-03-19 09:24:12 +01003587void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3588{
3589 mOutputs.removeItem(output);
3590}
3591
Eric Laurent1f2f2232014-06-02 12:01:23 -07003592void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003593{
François Gaffie98cc1912015-03-18 17:52:40 +01003594 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003595 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003596 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003597}
Eric Laurente552edb2014-03-10 17:42:56 -07003598
Eric Laurentc75307b2015-03-17 15:29:32 -07003599void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003600 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003601 const String8 address /*in*/,
3602 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003603 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003604 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003605 if (devDesc != 0) {
3606 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3607 desc->mIoHandle, address.string());
3608 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003609 }
3610}
3611
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003612status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003613 audio_policy_dev_state_t state,
3614 SortedVector<audio_io_handle_t>& outputs,
3615 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003616{
François Gaffie53615e22015-03-19 09:24:12 +01003617 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003618 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003619
3620 if (audio_device_is_digital(device)) {
3621 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003622 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003623 }
Eric Laurente552edb2014-03-10 17:42:56 -07003624
Eric Laurent3b73df72014-03-11 09:06:29 -07003625 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003626 // first list already open outputs that can be routed to this device
3627 for (size_t i = 0; i < mOutputs.size(); i++) {
3628 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003629 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003630 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003631 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3632 outputs.add(mOutputs.keyAt(i));
3633 } else {
3634 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003635 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003636 }
Eric Laurente552edb2014-03-10 17:42:56 -07003637 }
3638 }
3639 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003640 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003641 for (size_t i = 0; i < mHwModules.size(); i++)
3642 {
3643 if (mHwModules[i]->mHandle == 0) {
3644 continue;
3645 }
3646 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3647 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003648 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003649 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003650 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003651 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003652 profiles.add(profile);
3653 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3654 }
Eric Laurente552edb2014-03-10 17:42:56 -07003655 }
3656 }
3657 }
3658
Eric Laurent7b279bb2015-12-14 10:18:23 -08003659 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003660
Eric Laurente552edb2014-03-10 17:42:56 -07003661 if (profiles.isEmpty() && outputs.isEmpty()) {
3662 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3663 return BAD_VALUE;
3664 }
3665
3666 // open outputs for matching profiles if needed. Direct outputs are also opened to
3667 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3668 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003669 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003670
3671 // nothing to do if one output is already opened for this profile
3672 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003673 for (j = 0; j < outputs.size(); j++) {
3674 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003675 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003676 // matching profile: save the sample rates, format and channel masks supported
3677 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003678 if (audio_device_is_digital(device)) {
3679 devDesc->importAudioPort(profile);
3680 }
Eric Laurente552edb2014-03-10 17:42:56 -07003681 break;
3682 }
3683 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003684 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003685 continue;
3686 }
3687
Eric Laurent83b88082014-06-20 18:31:16 -07003688 ALOGV("opening output for device %08x with params %s profile %p",
3689 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003690 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003691 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003692 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3693 config.sample_rate = desc->mSamplingRate;
3694 config.channel_mask = desc->mChannelMask;
3695 config.format = desc->mFormat;
3696 config.offload_info.sample_rate = desc->mSamplingRate;
3697 config.offload_info.channel_mask = desc->mChannelMask;
3698 config.offload_info.format = desc->mFormat;
3699 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003700 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003701 &output,
3702 &config,
3703 &desc->mDevice,
3704 address,
3705 &desc->mLatency,
3706 desc->mFlags);
3707 if (status == NO_ERROR) {
3708 desc->mSamplingRate = config.sample_rate;
3709 desc->mChannelMask = config.channel_mask;
3710 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003711
Eric Laurentd4692962014-05-05 18:13:44 -07003712 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003713 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003714 char *param = audio_device_address_to_parameter(device, address);
3715 mpClientInterface->setParameters(output, String8(param));
3716 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003717 }
François Gaffie112b0af2015-11-19 16:13:25 +01003718 updateAudioProfiles(output, profile->getAudioProfiles());
3719 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003720 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003721 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003722 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003723 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003724 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003725 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003726 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003727 config.offload_info.sample_rate = config.sample_rate;
3728 config.offload_info.channel_mask = config.channel_mask;
3729 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003730 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003731 &output,
3732 &config,
3733 &desc->mDevice,
3734 address,
3735 &desc->mLatency,
3736 desc->mFlags);
3737 if (status == NO_ERROR) {
3738 desc->mSamplingRate = config.sample_rate;
3739 desc->mChannelMask = config.channel_mask;
3740 desc->mFormat = config.format;
3741 } else {
3742 output = AUDIO_IO_HANDLE_NONE;
3743 }
Eric Laurentd4692962014-05-05 18:13:44 -07003744 }
3745
Eric Laurentcf2c0212014-07-25 16:20:43 -07003746 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003747 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003748 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003749 sp<AudioPolicyMix> policyMix;
3750 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003751 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3752 address.string());
3753 }
François Gaffie036e1e92015-03-19 10:16:24 +01003754 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003755 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003756
Eric Laurent87ffa392015-05-22 10:32:38 -07003757 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3758 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003759 // no duplicated output for direct outputs and
3760 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003761 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003762
Eric Laurentd4692962014-05-05 18:13:44 -07003763 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003764 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003765
Eric Laurentd4692962014-05-05 18:13:44 -07003766 //TODO: configure audio effect output stage here
3767
3768 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003769 duplicatedOutput =
3770 mpClientInterface->openDuplicateOutput(output,
3771 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003772 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003773 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003774 sp<SwAudioOutputDescriptor> dupOutputDesc =
3775 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3776 dupOutputDesc->mOutput1 = mPrimaryOutput;
3777 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003778 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3779 dupOutputDesc->mFormat = desc->mFormat;
3780 dupOutputDesc->mChannelMask = desc->mChannelMask;
3781 dupOutputDesc->mLatency = desc->mLatency;
3782 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003783 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003784 } else {
3785 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003786 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003787 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003788 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003789 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003790 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003791 }
Eric Laurente552edb2014-03-10 17:42:56 -07003792 }
3793 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003794 } else {
3795 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003796 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003797 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003798 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003799 profiles.removeAt(profile_index);
3800 profile_index--;
3801 } else {
3802 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003803 // Load digital format info only for digital devices
3804 if (audio_device_is_digital(device)) {
3805 devDesc->importAudioPort(profile);
3806 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003807
François Gaffie53615e22015-03-19 09:24:12 +01003808 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003809 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3810 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003811 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003812 NULL/*patch handle*/, address.string());
3813 }
Eric Laurente552edb2014-03-10 17:42:56 -07003814 ALOGV("checkOutputsForDevice(): adding output %d", output);
3815 }
3816 }
3817
3818 if (profiles.isEmpty()) {
3819 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3820 return BAD_VALUE;
3821 }
Eric Laurentd4692962014-05-05 18:13:44 -07003822 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003823 // check if one opened output is not needed any more after disconnecting one device
3824 for (size_t i = 0; i < mOutputs.size(); i++) {
3825 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003826 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003827 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003828 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003829 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003830 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003831 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003832 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3833 mOutputs.keyAt(i));
3834 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003835 }
Eric Laurente552edb2014-03-10 17:42:56 -07003836 }
3837 }
Eric Laurentd4692962014-05-05 18:13:44 -07003838 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003839 for (size_t i = 0; i < mHwModules.size(); i++)
3840 {
3841 if (mHwModules[i]->mHandle == 0) {
3842 continue;
3843 }
3844 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3845 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003846 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003847 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003848 ALOGV("checkOutputsForDevice(): "
3849 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003850 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003851 }
3852 }
3853 }
3854 }
3855 return NO_ERROR;
3856}
3857
Paul McLean9080a4c2015-06-18 08:24:02 -07003858status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003859 audio_policy_dev_state_t state,
3860 SortedVector<audio_io_handle_t>& inputs,
3861 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003862{
Paul McLean9080a4c2015-06-18 08:24:02 -07003863 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003864 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003865
3866 if (audio_device_is_digital(device)) {
3867 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003868 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003869 }
3870
Eric Laurentd4692962014-05-05 18:13:44 -07003871 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3872 // first list already open inputs that can be routed to this device
3873 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3874 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003875 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003876 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3877 inputs.add(mInputs.keyAt(input_index));
3878 }
3879 }
3880
3881 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003882 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003883 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3884 {
3885 if (mHwModules[module_idx]->mHandle == 0) {
3886 continue;
3887 }
3888 for (size_t profile_index = 0;
3889 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3890 profile_index++)
3891 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003892 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3893
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003894 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003895 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003896 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003897 profiles.add(profile);
3898 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3899 profile_index, module_idx);
3900 }
Eric Laurentd4692962014-05-05 18:13:44 -07003901 }
3902 }
3903 }
3904
3905 if (profiles.isEmpty() && inputs.isEmpty()) {
3906 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3907 return BAD_VALUE;
3908 }
3909
3910 // open inputs for matching profiles if needed. Direct inputs are also opened to
3911 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3912 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3913
Eric Laurent1c333e22014-05-20 10:48:17 -07003914 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003915 // nothing to do if one input is already opened for this profile
3916 size_t input_index;
3917 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3918 desc = mInputs.valueAt(input_index);
3919 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003920 if (audio_device_is_digital(device)) {
3921 devDesc->importAudioPort(profile);
3922 }
Eric Laurentd4692962014-05-05 18:13:44 -07003923 break;
3924 }
3925 }
3926 if (input_index != mInputs.size()) {
3927 continue;
3928 }
3929
3930 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3931 desc = new AudioInputDescriptor(profile);
3932 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003933 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3934 config.sample_rate = desc->mSamplingRate;
3935 config.channel_mask = desc->mChannelMask;
3936 config.format = desc->mFormat;
3937 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003938 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003939 &input,
3940 &config,
3941 &desc->mDevice,
3942 address,
3943 AUDIO_SOURCE_MIC,
3944 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003945
Eric Laurentcf2c0212014-07-25 16:20:43 -07003946 if (status == NO_ERROR) {
3947 desc->mSamplingRate = config.sample_rate;
3948 desc->mChannelMask = config.channel_mask;
3949 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003950
Eric Laurentd4692962014-05-05 18:13:44 -07003951 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003952 char *param = audio_device_address_to_parameter(device, address);
3953 mpClientInterface->setParameters(input, String8(param));
3954 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003955 }
François Gaffie112b0af2015-11-19 16:13:25 +01003956 updateAudioProfiles(input, profile->getAudioProfiles());
3957 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003958 ALOGW("checkInputsForDevice() direct input missing param");
3959 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003960 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003961 }
3962
3963 if (input != 0) {
3964 addInput(input, desc);
3965 }
3966 } // endif input != 0
3967
Eric Laurentcf2c0212014-07-25 16:20:43 -07003968 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003969 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003970 profiles.removeAt(profile_index);
3971 profile_index--;
3972 } else {
3973 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003974 if (audio_device_is_digital(device)) {
3975 devDesc->importAudioPort(profile);
3976 }
Eric Laurentd4692962014-05-05 18:13:44 -07003977 ALOGV("checkInputsForDevice(): adding input %d", input);
3978 }
3979 } // end scan profiles
3980
3981 if (profiles.isEmpty()) {
3982 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3983 return BAD_VALUE;
3984 }
3985 } else {
3986 // Disconnect
3987 // check if one opened input is not needed any more after disconnecting one device
3988 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3989 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003991 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3992 mInputs.keyAt(input_index));
3993 inputs.add(mInputs.keyAt(input_index));
3994 }
3995 }
3996 // Clear any profiles associated with the disconnected device.
3997 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3998 if (mHwModules[module_index]->mHandle == 0) {
3999 continue;
4000 }
4001 for (size_t profile_index = 0;
4002 profile_index < mHwModules[module_index]->mInputProfiles.size();
4003 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004004 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004005 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004006 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004007 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004008 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004009 }
4010 }
4011 }
4012 } // end disconnect
4013
4014 return NO_ERROR;
4015}
4016
4017
Eric Laurente0720872014-03-11 09:30:41 -07004018void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004019{
4020 ALOGV("closeOutput(%d)", output);
4021
Eric Laurentc75307b2015-03-17 15:29:32 -07004022 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004023 if (outputDesc == NULL) {
4024 ALOGW("closeOutput() unknown output %d", output);
4025 return;
4026 }
François Gaffie036e1e92015-03-19 10:16:24 +01004027 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004028
Eric Laurente552edb2014-03-10 17:42:56 -07004029 // look for duplicated outputs connected to the output being removed.
4030 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004031 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004032 if (dupOutputDesc->isDuplicated() &&
4033 (dupOutputDesc->mOutput1 == outputDesc ||
4034 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004035 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004036 if (dupOutputDesc->mOutput1 == outputDesc) {
4037 outputDesc2 = dupOutputDesc->mOutput2;
4038 } else {
4039 outputDesc2 = dupOutputDesc->mOutput1;
4040 }
4041 // As all active tracks on duplicated output will be deleted,
4042 // and as they were also referenced on the other output, the reference
4043 // count for their stream type must be adjusted accordingly on
4044 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004045 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004046 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004047 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004048 }
4049 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4050 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4051
4052 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004053 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004054 }
4055 }
4056
Eric Laurent05b90f82014-08-27 15:32:29 -07004057 nextAudioPortGeneration();
4058
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004059 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004060 if (index >= 0) {
4061 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4062 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4063 mAudioPatches.removeItemsAt(index);
4064 mpClientInterface->onAudioPatchListUpdate();
4065 }
4066
Eric Laurente552edb2014-03-10 17:42:56 -07004067 AudioParameter param;
4068 param.add(String8("closing"), String8("true"));
4069 mpClientInterface->setParameters(output, param.toString());
4070
4071 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004072 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004073 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004074}
4075
4076void AudioPolicyManager::closeInput(audio_io_handle_t input)
4077{
4078 ALOGV("closeInput(%d)", input);
4079
4080 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4081 if (inputDesc == NULL) {
4082 ALOGW("closeInput() unknown input %d", input);
4083 return;
4084 }
4085
Eric Laurent6a94d692014-05-20 11:18:06 -07004086 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004087
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004088 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004089 if (index >= 0) {
4090 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4091 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4092 mAudioPatches.removeItemsAt(index);
4093 mpClientInterface->onAudioPatchListUpdate();
4094 }
4095
4096 mpClientInterface->closeInput(input);
4097 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004098}
4099
Eric Laurentc75307b2015-03-17 15:29:32 -07004100SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4101 audio_devices_t device,
4102 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004103{
4104 SortedVector<audio_io_handle_t> outputs;
4105
4106 ALOGVV("getOutputsForDevice() device %04x", device);
4107 for (size_t i = 0; i < openOutputs.size(); i++) {
4108 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004109 i, openOutputs.valueAt(i)->isDuplicated(),
4110 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004111 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4112 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4113 outputs.add(openOutputs.keyAt(i));
4114 }
4115 }
4116 return outputs;
4117}
4118
Eric Laurente0720872014-03-11 09:30:41 -07004119bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004120 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004121{
4122 if (outputs1.size() != outputs2.size()) {
4123 return false;
4124 }
4125 for (size_t i = 0; i < outputs1.size(); i++) {
4126 if (outputs1[i] != outputs2[i]) {
4127 return false;
4128 }
4129 }
4130 return true;
4131}
4132
Eric Laurente0720872014-03-11 09:30:41 -07004133void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004134{
4135 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4136 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4137 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4138 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4139
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004140 // also take into account external policy-related changes: add all outputs which are
4141 // associated with policies in the "before" and "after" output vectors
4142 ALOGVV("checkOutputForStrategy(): policy related outputs");
4143 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004144 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004145 if (desc != 0 && desc->mPolicyMix != NULL) {
4146 srcOutputs.add(desc->mIoHandle);
4147 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4148 }
4149 }
4150 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004151 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004152 if (desc != 0 && desc->mPolicyMix != NULL) {
4153 dstOutputs.add(desc->mIoHandle);
4154 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4155 }
4156 }
4157
Eric Laurente552edb2014-03-10 17:42:56 -07004158 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4159 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4160 strategy, srcOutputs[0], dstOutputs[0]);
4161 // mute strategy while moving tracks from one output to another
4162 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004163 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004164 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004165 setStrategyMute(strategy, true, desc);
4166 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004167 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004168 sp<AudioSourceDescriptor> source =
4169 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4170 if (source != 0){
4171 connectAudioSource(source);
4172 }
Eric Laurente552edb2014-03-10 17:42:56 -07004173 }
4174
4175 // Move effects associated to this strategy from previous output to new output
4176 if (strategy == STRATEGY_MEDIA) {
4177 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4178 SortedVector<audio_io_handle_t> moved;
4179 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004180 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4181 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4182 effectDesc->mIo != fxOutput) {
4183 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004184 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4185 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004186 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004187 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004188 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004189 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004190 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004191 }
4192 }
4193 }
4194 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004195 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004196 if (getStrategy((audio_stream_type_t)i) == strategy) {
4197 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004198 }
4199 }
4200 }
4201}
4202
Eric Laurente0720872014-03-11 09:30:41 -07004203void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004204{
François Gaffie2110e042015-03-24 08:41:51 +01004205 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004206 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004207 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004208 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004209 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004210 checkOutputForStrategy(STRATEGY_SONIFICATION);
4211 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004212 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004213 checkOutputForStrategy(STRATEGY_MEDIA);
4214 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004215 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004216}
4217
Eric Laurente0720872014-03-11 09:30:41 -07004218void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004219{
François Gaffie53615e22015-03-19 09:24:12 +01004220 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004221 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004222 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004223 return;
4224 }
4225
Eric Laurent3a4311c2014-03-17 12:00:47 -07004226 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004227 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4228 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4229 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004230 // suspend A2DP output if:
4231 // (NOT already suspended) &&
4232 // ((SCO device is connected &&
4233 // (forced usage for communication || for record is SCO))) ||
4234 // (phone state is ringing || in call)
4235 //
4236 // restore A2DP output if:
4237 // (Already suspended) &&
4238 // ((SCO device is NOT connected ||
4239 // (forced usage NOT for communication && NOT for record is SCO))) &&
4240 // (phone state is NOT ringing && NOT in call)
4241 //
4242 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004243 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004244 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4245 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4246 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4247 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004248
4249 mpClientInterface->restoreOutput(a2dpOutput);
4250 mA2dpSuspended = false;
4251 }
4252 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004253 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004254 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4255 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4256 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4257 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004258
4259 mpClientInterface->suspendOutput(a2dpOutput);
4260 mA2dpSuspended = true;
4261 }
4262 }
4263}
4264
Eric Laurentc75307b2015-03-17 15:29:32 -07004265audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4266 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004267{
4268 audio_devices_t device = AUDIO_DEVICE_NONE;
4269
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004270 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004271 if (index >= 0) {
4272 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4273 if (patchDesc->mUid != mUidCached) {
4274 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004275 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004276 return outputDesc->device();
4277 }
4278 }
4279
Eric Laurente552edb2014-03-10 17:42:56 -07004280 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004281 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004282 // use device for strategy enforced audible
4283 // 2: we are in call or the strategy phone is active on the output:
4284 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004285 // 3: the strategy for enforced audible is active but not enforced on the output:
4286 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004287 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004288 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004289 // 5: the strategy accessibility is active on the output:
4290 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004291 // 6: the strategy "respectful" sonification is active on the output:
4292 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004293 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004294 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004295 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004296 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004297 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004298 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004299 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004300 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004301 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4302 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004303 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004304 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004305 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004306 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004307 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004308 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004309 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4310 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004311 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004312 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004313 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004314 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004315 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004316 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004317 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004318 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004319 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004320 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004321 }
4322
Eric Laurent1c333e22014-05-20 10:48:17 -07004323 ALOGV("getNewOutputDevice() selected device %x", device);
4324 return device;
4325}
4326
Eric Laurentfb66dd92016-01-28 18:32:03 -08004327audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004328{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004329 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004330
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004331 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004332 if (index >= 0) {
4333 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4334 if (patchDesc->mUid != mUidCached) {
4335 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004336 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004337 return inputDesc->mDevice;
4338 }
4339 }
4340
Eric Laurentfb66dd92016-01-28 18:32:03 -08004341 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4342 if (isInCall()) {
4343 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4344 } else if (source != AUDIO_SOURCE_DEFAULT) {
4345 device = getDeviceAndMixForInputSource(source);
4346 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004347
Eric Laurente552edb2014-03-10 17:42:56 -07004348 return device;
4349}
4350
Eric Laurent794fde22016-03-11 09:50:45 -08004351bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4352 audio_stream_type_t stream2) {
4353 return ((stream1 == stream2) ||
4354 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4355 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004356}
4357
Eric Laurente0720872014-03-11 09:30:41 -07004358uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004359 return (uint32_t)getStrategy(stream);
4360}
4361
Eric Laurente0720872014-03-11 09:30:41 -07004362audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004363 // By checking the range of stream before calling getStrategy, we avoid
4364 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4365 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004366 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004367 return AUDIO_DEVICE_NONE;
4368 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004369 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004370 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4371 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004372 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004373 }
Eric Laurent794fde22016-03-11 09:50:45 -08004374 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004375 audio_devices_t curDevices =
4376 getDeviceForStrategy((routing_strategy)curStrategy, true /*fromCache*/);
4377 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4378 for (size_t i = 0; i < outputs.size(); i++) {
4379 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004380 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004381 curDevices |= outputDesc->device();
4382 }
4383 }
4384 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004385 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004386
4387 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4388 and doesn't really need to.*/
4389 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4390 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4391 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4392 }
Eric Laurente552edb2014-03-10 17:42:56 -07004393 return devices;
4394}
4395
François Gaffie2110e042015-03-24 08:41:51 +01004396routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4397{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004398 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004399 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004400}
4401
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004402uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4403 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004404 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4405 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4406 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004407 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4408 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4409 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004410 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004411 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004412}
4413
Eric Laurente0720872014-03-11 09:30:41 -07004414void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004415 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004416 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004417 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4418 updateDevicesAndOutputs();
4419 break;
4420 default:
4421 break;
4422 }
4423}
4424
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004425uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004426
4427 // skip beacon mute management if a dedicated TTS output is available
4428 if (mTtsOutputAvailable) {
4429 return 0;
4430 }
4431
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004432 switch(event) {
4433 case STARTING_OUTPUT:
4434 mBeaconMuteRefCount++;
4435 break;
4436 case STOPPING_OUTPUT:
4437 if (mBeaconMuteRefCount > 0) {
4438 mBeaconMuteRefCount--;
4439 }
4440 break;
4441 case STARTING_BEACON:
4442 mBeaconPlayingRefCount++;
4443 break;
4444 case STOPPING_BEACON:
4445 if (mBeaconPlayingRefCount > 0) {
4446 mBeaconPlayingRefCount--;
4447 }
4448 break;
4449 }
4450
4451 if (mBeaconMuteRefCount > 0) {
4452 // any playback causes beacon to be muted
4453 return setBeaconMute(true);
4454 } else {
4455 // no other playback: unmute when beacon starts playing, mute when it stops
4456 return setBeaconMute(mBeaconPlayingRefCount == 0);
4457 }
4458}
4459
4460uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4461 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4462 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4463 // keep track of muted state to avoid repeating mute/unmute operations
4464 if (mBeaconMuted != mute) {
4465 // mute/unmute AUDIO_STREAM_TTS on all outputs
4466 ALOGV("\t muting %d", mute);
4467 uint32_t maxLatency = 0;
4468 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004469 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004470 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004471 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004472 0 /*delay*/, AUDIO_DEVICE_NONE);
4473 const uint32_t latency = desc->latency() * 2;
4474 if (latency > maxLatency) {
4475 maxLatency = latency;
4476 }
4477 }
4478 mBeaconMuted = mute;
4479 return maxLatency;
4480 }
4481 return 0;
4482}
4483
Eric Laurente0720872014-03-11 09:30:41 -07004484audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004485 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004486{
Paul McLeanaa981192015-03-21 09:55:15 -07004487 // Routing
4488 // see if we have an explicit route
4489 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4490 // (getStrategy(stream)).
4491 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4492 // and activity count is non-zero
4493 // the device = the device from the descriptor in the RouteMap, and exit.
4494 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4495 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004496 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4497 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004498 return route->mDeviceDescriptor->type();
4499 }
4500 }
4501
Eric Laurente552edb2014-03-10 17:42:56 -07004502 if (fromCache) {
4503 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4504 strategy, mDeviceForStrategy[strategy]);
4505 return mDeviceForStrategy[strategy];
4506 }
François Gaffie2110e042015-03-24 08:41:51 +01004507 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004508}
4509
Eric Laurente0720872014-03-11 09:30:41 -07004510void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004511{
4512 for (int i = 0; i < NUM_STRATEGIES; i++) {
4513 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4514 }
4515 mPreviousOutputs = mOutputs;
4516}
4517
Eric Laurent1f2f2232014-06-02 12:01:23 -07004518uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004519 audio_devices_t prevDevice,
4520 uint32_t delayMs)
4521{
4522 // mute/unmute strategies using an incompatible device combination
4523 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4524 // if unmuting, unmute only after the specified delay
4525 if (outputDesc->isDuplicated()) {
4526 return 0;
4527 }
4528
4529 uint32_t muteWaitMs = 0;
4530 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004531 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004532
4533 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4534 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004535 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004536 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4537 bool doMute = false;
4538
4539 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4540 doMute = true;
4541 outputDesc->mStrategyMutedByDevice[i] = true;
4542 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4543 doMute = true;
4544 outputDesc->mStrategyMutedByDevice[i] = false;
4545 }
Eric Laurent99401132014-05-07 19:48:15 -07004546 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004547 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004548 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004549 // skip output if it does not share any device with current output
4550 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4551 == AUDIO_DEVICE_NONE) {
4552 continue;
4553 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004554 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4555 mute ? "muting" : "unmuting", i, curDevice);
4556 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004557 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004558 if (mute) {
4559 // FIXME: should not need to double latency if volume could be applied
4560 // immediately by the audioflinger mixer. We must account for the delay
4561 // between now and the next time the audioflinger thread for this output
4562 // will process a buffer (which corresponds to one buffer size,
4563 // usually 1/2 or 1/4 of the latency).
4564 if (muteWaitMs < desc->latency() * 2) {
4565 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004566 }
4567 }
4568 }
4569 }
4570 }
4571 }
4572
Eric Laurent99401132014-05-07 19:48:15 -07004573 // temporary mute output if device selection changes to avoid volume bursts due to
4574 // different per device volumes
4575 if (outputDesc->isActive() && (device != prevDevice)) {
4576 if (muteWaitMs < outputDesc->latency() * 2) {
4577 muteWaitMs = outputDesc->latency() * 2;
4578 }
4579 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004580 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004581 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004582 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004583 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004584 muteWaitMs *2, device);
4585 }
4586 }
4587 }
4588
Eric Laurente552edb2014-03-10 17:42:56 -07004589 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4590 if (muteWaitMs > delayMs) {
4591 muteWaitMs -= delayMs;
4592 usleep(muteWaitMs * 1000);
4593 return muteWaitMs;
4594 }
4595 return 0;
4596}
4597
Eric Laurentc75307b2015-03-17 15:29:32 -07004598uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004599 audio_devices_t device,
4600 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004601 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004602 audio_patch_handle_t *patchHandle,
4603 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004604{
Eric Laurentc75307b2015-03-17 15:29:32 -07004605 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004606 AudioParameter param;
4607 uint32_t muteWaitMs;
4608
4609 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004610 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4611 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004612 return muteWaitMs;
4613 }
4614 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4615 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004616 if ((device != AUDIO_DEVICE_NONE) &&
4617 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004618 return 0;
4619 }
4620
4621 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004622 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004623
4624 audio_devices_t prevDevice = outputDesc->mDevice;
4625
Paul McLeanaa981192015-03-21 09:55:15 -07004626 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004627
4628 if (device != AUDIO_DEVICE_NONE) {
4629 outputDesc->mDevice = device;
4630 }
4631 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4632
4633 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004634 // the requested device is AUDIO_DEVICE_NONE
4635 // OR the requested device is the same as current device
4636 // AND force is not specified
4637 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004638 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004639 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4640 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004641 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004642 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004643 return muteWaitMs;
4644 }
4645
4646 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004647
Eric Laurente552edb2014-03-10 17:42:56 -07004648 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004649 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004650 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004651 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004652 DeviceVector deviceList = (address == NULL) ?
4653 mAvailableOutputDevices.getDevicesFromType(device)
4654 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004655 if (!deviceList.isEmpty()) {
4656 struct audio_patch patch;
4657 outputDesc->toAudioPortConfig(&patch.sources[0]);
4658 patch.num_sources = 1;
4659 patch.num_sinks = 0;
4660 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4661 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004662 patch.num_sinks++;
4663 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004664 ssize_t index;
4665 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4666 index = mAudioPatches.indexOfKey(*patchHandle);
4667 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004668 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 }
4670 sp< AudioPatch> patchDesc;
4671 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4672 if (index >= 0) {
4673 patchDesc = mAudioPatches.valueAt(index);
4674 afPatchHandle = patchDesc->mAfPatchHandle;
4675 }
4676
Eric Laurent1c333e22014-05-20 10:48:17 -07004677 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004678 &afPatchHandle,
4679 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004680 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4681 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004682 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004683 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004685 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 addAudioPatch(patchDesc->mHandle, patchDesc);
4687 } else {
4688 patchDesc->mPatch = patch;
4689 }
4690 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004691 if (patchHandle) {
4692 *patchHandle = patchDesc->mHandle;
4693 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004694 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004696 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004697 }
4698 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004699
4700 // inform all input as well
4701 for (size_t i = 0; i < mInputs.size(); i++) {
4702 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004703 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004704 AudioParameter inputCmd = AudioParameter();
4705 ALOGV("%s: inform input %d of device:%d", __func__,
4706 inputDescriptor->mIoHandle, device);
4707 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4708 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4709 inputCmd.toString(),
4710 delayMs);
4711 }
4712 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004713 }
Eric Laurente552edb2014-03-10 17:42:56 -07004714
4715 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004716 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004717
4718 return muteWaitMs;
4719}
4720
Eric Laurentc75307b2015-03-17 15:29:32 -07004721status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004722 int delayMs,
4723 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004724{
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 ssize_t index;
4726 if (patchHandle) {
4727 index = mAudioPatches.indexOfKey(*patchHandle);
4728 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004729 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 }
4731 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004732 return INVALID_OPERATION;
4733 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4735 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004736 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004737 outputDesc->setPatchHandle(0);
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 removeAudioPatch(patchDesc->mHandle);
4739 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004740 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004741 return status;
4742}
4743
4744status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4745 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 bool force,
4747 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004748{
4749 status_t status = NO_ERROR;
4750
Eric Laurent1f2f2232014-06-02 12:01:23 -07004751 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004752 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4753 inputDesc->mDevice = device;
4754
4755 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4756 if (!deviceList.isEmpty()) {
4757 struct audio_patch patch;
4758 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004759 // AUDIO_SOURCE_HOTWORD is for internal use only:
4760 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004761 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004762 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004763 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4764 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004765 patch.num_sinks = 1;
4766 //only one input device for now
4767 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004768 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 ssize_t index;
4770 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4771 index = mAudioPatches.indexOfKey(*patchHandle);
4772 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004773 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004774 }
4775 sp< AudioPatch> patchDesc;
4776 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4777 if (index >= 0) {
4778 patchDesc = mAudioPatches.valueAt(index);
4779 afPatchHandle = patchDesc->mAfPatchHandle;
4780 }
4781
Eric Laurent1c333e22014-05-20 10:48:17 -07004782 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004783 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004784 0);
4785 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004786 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004787 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004789 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 addAudioPatch(patchDesc->mHandle, patchDesc);
4791 } else {
4792 patchDesc->mPatch = patch;
4793 }
4794 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004795 if (patchHandle) {
4796 *patchHandle = patchDesc->mHandle;
4797 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004798 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004800 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004801 }
4802 }
4803 }
4804 return status;
4805}
4806
Eric Laurent6a94d692014-05-20 11:18:06 -07004807status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4808 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004809{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004810 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 ssize_t index;
4812 if (patchHandle) {
4813 index = mAudioPatches.indexOfKey(*patchHandle);
4814 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004815 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 }
4817 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004818 return INVALID_OPERATION;
4819 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4821 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004822 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004823 inputDesc->setPatchHandle(0);
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 removeAudioPatch(patchDesc->mHandle);
4825 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004826 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004827 return status;
4828}
4829
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004830sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004831 String8 address,
4832 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004833 audio_format_t& format,
4834 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004835 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004836{
4837 // Choose an input profile based on the requested capture parameters: select the first available
4838 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004839 //
4840 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4841 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004842
4843 for (size_t i = 0; i < mHwModules.size(); i++)
4844 {
4845 if (mHwModules[i]->mHandle == 0) {
4846 continue;
4847 }
4848 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4849 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004850 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004851 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004852 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004853 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004854 format,
4855 &format /*updatedFormat*/,
4856 channelMask,
4857 &channelMask /*updatedChannelMask*/,
4858 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004859
Eric Laurente552edb2014-03-10 17:42:56 -07004860 return profile;
4861 }
4862 }
4863 }
4864 return NULL;
4865}
4866
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004867
4868audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004869 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004870{
François Gaffie036e1e92015-03-19 10:16:24 +01004871 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4872 audio_devices_t selectedDeviceFromMix =
4873 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004874
François Gaffie036e1e92015-03-19 10:16:24 +01004875 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4876 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004877 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004878 return getDeviceForInputSource(inputSource);
4879}
4880
4881audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4882{
Paul McLean466dc8e2015-04-17 13:15:36 -06004883 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4884 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004885 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004886 return route->mDeviceDescriptor->type();
4887 }
4888 }
4889
4890 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004891}
4892
Eric Laurente0720872014-03-11 09:30:41 -07004893float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004894 int index,
4895 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004896{
François Gaffied1ab2bd2015-12-02 18:20:06 +01004897 float volumeDb = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Eric Laurente552edb2014-03-10 17:42:56 -07004898 // if a headset is connected, apply the following rules to ring tones and notifications
4899 // to avoid sound level bursts in user's ears:
4900 // - always attenuate ring tones and notifications volume by 6dB
4901 // - if music is playing, always limit the volume to current music volume,
4902 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004903 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004904 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4905 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4906 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4907 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4908 ((stream_strategy == STRATEGY_SONIFICATION)
4909 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004910 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004911 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004912 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01004913 mVolumeCurves->canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004914 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004915 // when the phone is ringing we must consider that music could have been paused just before
4916 // by the music application and behave as if music was active if the last music track was
4917 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004918 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004919 mLimitRingtoneVolume) {
4920 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004921 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004922 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
4923 musicDevice),
4924 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004925 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4926 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4927 if (volumeDb > minVolDB) {
4928 volumeDb = minVolDB;
4929 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004930 }
4931 }
4932 }
4933
Eric Laurentffbc80f2015-03-18 18:30:19 -07004934 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004935}
4936
Eric Laurente0720872014-03-11 09:30:41 -07004937status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004938 int index,
4939 const sp<AudioOutputDescriptor>& outputDesc,
4940 audio_devices_t device,
4941 int delayMs,
4942 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004943{
Eric Laurente552edb2014-03-10 17:42:56 -07004944 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004945 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004946 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004947 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004948 return NO_ERROR;
4949 }
François Gaffie2110e042015-03-24 08:41:51 +01004950 audio_policy_forced_cfg_t forceUseForComm =
4951 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004952 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004953 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4954 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004955 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004956 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004957 return INVALID_OPERATION;
4958 }
4959
Eric Laurentc75307b2015-03-17 15:29:32 -07004960 if (device == AUDIO_DEVICE_NONE) {
4961 device = outputDesc->device();
4962 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004963
Eric Laurentffbc80f2015-03-18 18:30:19 -07004964 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004965 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004966 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004967 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004968
Eric Laurentffbc80f2015-03-18 18:30:19 -07004969 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004970
Eric Laurent3b73df72014-03-11 09:06:29 -07004971 if (stream == AUDIO_STREAM_VOICE_CALL ||
4972 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004973 float voiceVolume;
4974 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004975 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004976 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004977 } else {
4978 voiceVolume = 1.0;
4979 }
4980
Eric Laurentc75307b2015-03-17 15:29:32 -07004981 if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
Eric Laurente552edb2014-03-10 17:42:56 -07004982 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4983 mLastVoiceVolume = voiceVolume;
4984 }
4985 }
4986
4987 return NO_ERROR;
4988}
4989
Eric Laurentc75307b2015-03-17 15:29:32 -07004990void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4991 audio_devices_t device,
4992 int delayMs,
4993 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004994{
Eric Laurentc75307b2015-03-17 15:29:32 -07004995 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004996
Eric Laurent794fde22016-03-11 09:50:45 -08004997 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004998 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004999 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005000 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005001 device,
5002 delayMs,
5003 force);
5004 }
5005}
5006
Eric Laurente0720872014-03-11 09:30:41 -07005007void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005008 bool on,
5009 const sp<AudioOutputDescriptor>& outputDesc,
5010 int delayMs,
5011 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005012{
Eric Laurent72249d52015-06-08 11:12:15 -07005013 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5014 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005015 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005016 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005017 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005018 }
5019 }
5020}
5021
Eric Laurente0720872014-03-11 09:30:41 -07005022void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005023 bool on,
5024 const sp<AudioOutputDescriptor>& outputDesc,
5025 int delayMs,
5026 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005027{
Eric Laurente552edb2014-03-10 17:42:56 -07005028 if (device == AUDIO_DEVICE_NONE) {
5029 device = outputDesc->device();
5030 }
5031
Eric Laurentc75307b2015-03-17 15:29:32 -07005032 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5033 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005034
5035 if (on) {
5036 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005037 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005038 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005039 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005040 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005041 }
5042 }
5043 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5044 outputDesc->mMuteCount[stream]++;
5045 } else {
5046 if (outputDesc->mMuteCount[stream] == 0) {
5047 ALOGV("setStreamMute() unmuting non muted stream!");
5048 return;
5049 }
5050 if (--outputDesc->mMuteCount[stream] == 0) {
5051 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005052 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005053 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005054 device,
5055 delayMs);
5056 }
5057 }
5058}
5059
Eric Laurente0720872014-03-11 09:30:41 -07005060void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005061 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005062{
Eric Laurent87ffa392015-05-22 10:32:38 -07005063 if(!hasPrimaryOutput()) {
5064 return;
5065 }
5066
Eric Laurente552edb2014-03-10 17:42:56 -07005067 // if the stream pertains to sonification strategy and we are in call we must
5068 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5069 // in the device used for phone strategy and play the tone if the selected device does not
5070 // interfere with the device used for phone strategy
5071 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5072 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005073 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005074 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5075 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005076 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005077 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5078 stream, starting, outputDesc->mDevice, stateChange);
5079 if (outputDesc->mRefCount[stream]) {
5080 int muteCount = 1;
5081 if (stateChange) {
5082 muteCount = outputDesc->mRefCount[stream];
5083 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005084 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005085 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5086 for (int i = 0; i < muteCount; i++) {
5087 setStreamMute(stream, starting, mPrimaryOutput);
5088 }
5089 } else {
5090 ALOGV("handleIncallSonification() high visibility");
5091 if (outputDesc->device() &
5092 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5093 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5094 for (int i = 0; i < muteCount; i++) {
5095 setStreamMute(stream, starting, mPrimaryOutput);
5096 }
5097 }
5098 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005099 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5100 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005101 } else {
5102 mpClientInterface->stopTone();
5103 }
5104 }
5105 }
5106 }
5107}
5108
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005109audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5110{
5111 // flags to stream type mapping
5112 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5113 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5114 }
5115 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5116 return AUDIO_STREAM_BLUETOOTH_SCO;
5117 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005118 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5119 return AUDIO_STREAM_TTS;
5120 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005121
5122 // usage to stream type mapping
5123 switch (attr->usage) {
5124 case AUDIO_USAGE_MEDIA:
5125 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005126 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5127 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005128 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5129 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005130 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5131 return AUDIO_STREAM_SYSTEM;
5132 case AUDIO_USAGE_VOICE_COMMUNICATION:
5133 return AUDIO_STREAM_VOICE_CALL;
5134
5135 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5136 return AUDIO_STREAM_DTMF;
5137
5138 case AUDIO_USAGE_ALARM:
5139 return AUDIO_STREAM_ALARM;
5140 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5141 return AUDIO_STREAM_RING;
5142
5143 case AUDIO_USAGE_NOTIFICATION:
5144 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5145 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5146 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5147 case AUDIO_USAGE_NOTIFICATION_EVENT:
5148 return AUDIO_STREAM_NOTIFICATION;
5149
5150 case AUDIO_USAGE_UNKNOWN:
5151 default:
5152 return AUDIO_STREAM_MUSIC;
5153 }
5154}
Eric Laurente83b55d2014-11-14 10:06:21 -08005155
François Gaffie53615e22015-03-19 09:24:12 +01005156bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5157{
Eric Laurente83b55d2014-11-14 10:06:21 -08005158 // has flags that map to a strategy?
5159 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5160 return true;
5161 }
5162
5163 // has known usage?
5164 switch (paa->usage) {
5165 case AUDIO_USAGE_UNKNOWN:
5166 case AUDIO_USAGE_MEDIA:
5167 case AUDIO_USAGE_VOICE_COMMUNICATION:
5168 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5169 case AUDIO_USAGE_ALARM:
5170 case AUDIO_USAGE_NOTIFICATION:
5171 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5172 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5173 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5174 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5175 case AUDIO_USAGE_NOTIFICATION_EVENT:
5176 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5177 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5178 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5179 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005180 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005181 break;
5182 default:
5183 return false;
5184 }
5185 return true;
5186}
5187
François Gaffiead3183e2015-03-18 16:55:35 +01005188bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5189 routing_strategy strategy, uint32_t inPastMs,
5190 nsecs_t sysTime) const
5191{
5192 if ((sysTime == 0) && (inPastMs != 0)) {
5193 sysTime = systemTime();
5194 }
Eric Laurent794fde22016-03-11 09:50:45 -08005195 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005196 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5197 (NUM_STRATEGIES == strategy)) &&
5198 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5199 return true;
5200 }
5201 }
5202 return false;
5203}
5204
François Gaffie2110e042015-03-24 08:41:51 +01005205audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5206{
5207 return mEngine->getForceUse(usage);
5208}
5209
5210bool AudioPolicyManager::isInCall()
5211{
5212 return isStateInCall(mEngine->getPhoneState());
5213}
5214
5215bool AudioPolicyManager::isStateInCall(int state)
5216{
5217 return is_state_in_call(state);
5218}
5219
Eric Laurentd60560a2015-04-10 11:31:20 -07005220void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5221{
5222 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5223 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5224 if (sourceDesc->mDevice->equals(deviceDesc)) {
5225 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5226 stopAudioSource(sourceDesc->getHandle());
5227 }
5228 }
5229
5230 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5231 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5232 bool release = false;
5233 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5234 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5235 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5236 source->ext.device.type == deviceDesc->type()) {
5237 release = true;
5238 }
5239 }
5240 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5241 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5242 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5243 sink->ext.device.type == deviceDesc->type()) {
5244 release = true;
5245 }
5246 }
5247 if (release) {
5248 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5249 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5250 }
5251 }
5252}
5253
Phil Burk09bc4612016-02-24 15:58:15 -08005254// Modify the list of surround sound formats supported.
5255void AudioPolicyManager::filterSurroundFormats(FormatVector &formats) {
5256
5257 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5258 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5259 ALOGI("%s: forced use = %d", __FUNCTION__, forceUse);
5260
5261 // Analyze original support for various formats.
5262 bool supportsRawSurround = false;
5263 bool supportsIEC61937 = false;
5264 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5265 audio_format_t format = formats[formatIndex];
5266 ALOGI("%s: original formats: #%x", __FUNCTION__, format);
5267 switch (format) {
5268 case AUDIO_FORMAT_AC3:
5269 case AUDIO_FORMAT_E_AC3:
5270 case AUDIO_FORMAT_DTS:
5271 case AUDIO_FORMAT_DTS_HD:
5272 supportsRawSurround = true;
5273 break;
5274 case AUDIO_FORMAT_IEC61937:
5275 supportsIEC61937 = true;
5276 break;
5277 default:
5278 break;
5279 }
5280 }
5281 ALOGI("%s: supportsRawSurround = %d, supportsIEC61937 = %d",
5282 __FUNCTION__, supportsRawSurround, supportsIEC61937);
5283
5284 // Modify formats based on surround preferences.
5285 // If NEVER, remove support for surround formats.
5286 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER)
5287 && (supportsRawSurround || supportsIEC61937)) {
5288 // Remove surround sound related formats.
5289 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5290 audio_format_t format = formats[formatIndex];
5291 switch(format) {
5292 case AUDIO_FORMAT_AC3:
5293 case AUDIO_FORMAT_E_AC3:
5294 case AUDIO_FORMAT_DTS:
5295 case AUDIO_FORMAT_DTS_HD:
5296 case AUDIO_FORMAT_IEC61937:
5297 ALOGI("%s: remove #%x", __FUNCTION__, format);
5298 formats.removeAt(formatIndex);
5299 break;
5300 default:
5301 formatIndex++; // keep it
5302 break;
5303 }
5304 }
5305 supportsRawSurround = false;
5306 supportsIEC61937 = false;
5307 }
5308 // If ALWAYS, add support for raw surround formats if all are missing.
5309 // This assumes that if any of these formats are reported by the HAL
5310 // then the report is valid and should not be modified.
5311 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5312 && !supportsRawSurround) {
5313 formats.add(AUDIO_FORMAT_AC3);
5314 formats.add(AUDIO_FORMAT_E_AC3);
5315 formats.add(AUDIO_FORMAT_DTS);
5316 formats.add(AUDIO_FORMAT_DTS_HD);
5317 supportsRawSurround = true;
5318 }
5319 // Add support for IEC61937 if raw surround supported.
5320 // The HAL could do this but add it here, just in case.
5321 if (supportsRawSurround && !supportsIEC61937) {
5322 formats.add(AUDIO_FORMAT_IEC61937);
5323 // supportsIEC61937 = true;
5324 }
5325 // Just for debugging.
5326 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5327 audio_format_t format = formats[formatIndex];
5328 ALOGI("%s: final formats: #%x", __FUNCTION__, format);
5329 }
5330}
5331
François Gaffie112b0af2015-11-19 16:13:25 +01005332void AudioPolicyManager::updateAudioProfiles(audio_io_handle_t ioHandle,
5333 AudioProfileVector &profiles)
5334{
5335 String8 reply;
5336 char *value;
5337 // Format MUST be checked first to update the list of AudioProfile
5338 if (profiles.hasDynamicFormat()) {
5339 reply = mpClientInterface->getParameters(ioHandle,
5340 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk09bc4612016-02-24 15:58:15 -08005341 ALOGI("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005342 AudioParameter repliedParameters(reply);
5343 if (repliedParameters.get(
5344 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005345 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5346 return;
5347 }
Phil Burk09bc4612016-02-24 15:58:15 -08005348 FormatVector formats = formatsFromString(reply.string());
5349 filterSurroundFormats(formats);
5350 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005351 }
5352 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5353
Eric Laurent20eb3a42016-01-26 18:39:17 -08005354 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005355 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005356 ChannelsVector channelMasks;
5357 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005358 AudioParameter requestedParameters;
5359 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5360
5361 if (profiles.hasDynamicRateFor(format)) {
5362 reply = mpClientInterface->getParameters(ioHandle,
5363 requestedParameters.toString() + ";" +
5364 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5365 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005366 AudioParameter repliedParameters(reply);
5367 if (repliedParameters.get(
5368 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5369 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005370 }
5371 }
5372 if (profiles.hasDynamicChannelsFor(format)) {
5373 reply = mpClientInterface->getParameters(ioHandle,
5374 requestedParameters.toString() + ";" +
5375 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5376 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005377 AudioParameter repliedParameters(reply);
5378 if (repliedParameters.get(
5379 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5380 channelMasks = channelMasksFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005381 }
5382 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005383 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005384 }
5385}
Eric Laurentd60560a2015-04-10 11:31:20 -07005386
Eric Laurente552edb2014-03-10 17:42:56 -07005387}; // namespace android