blob: 2aed7b1bb05a8adec34f2f1486cbac66c46f5904 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -080017#define LOG_TAG "APM::AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
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 Gaffief4ad6e52015-11-19 16:59:57 +010042#ifdef USE_XML_AUDIO_POLICY_CONF
43#include <Serializer.h>
44#else
François Gaffie53615e22015-03-19 09:24:12 +010045#include <ConfigParsingUtils.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010046#endif
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()
423 audio_io_handle_t activeInput = mInputs.getActiveInput();
424 if (activeInput != 0) {
425 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
426 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
Eric Laurent599c7582015-12-07 18:05:55 -0800427 //FIXME: consider all active sessions
428 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
429 audio_session_t activeSession = activeSessions.keyAt(0);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700430 stopInput(activeInput, activeSession);
431 releaseInput(activeInput, activeSession);
432 }
433 }
434
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
436 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
437 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
438 status);
439 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100440 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441 mCallTxPatch->mAfPatchHandle = afPatchHandle;
442 mCallTxPatch->mUid = mUidCached;
443 }
444 }
445}
446
Eric Laurente0720872014-03-11 09:30:41 -0700447void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700448{
449 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100450 // store previous phone state for management of sonification strategy below
451 int oldState = mEngine->getPhoneState();
452
453 if (mEngine->setPhoneState(state) != NO_ERROR) {
454 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700455 return;
456 }
François Gaffie2110e042015-03-24 08:41:51 +0100457 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700458 // if leaving call state, handle special case of active streams
459 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700460 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700461 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700462 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800463 if (stream == AUDIO_STREAM_PATCH) {
464 continue;
465 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700466 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700467 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800468
Eric Laurent63dea1d2015-07-02 17:10:28 -0700469 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800470 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700471 }
472
François Gaffie2110e042015-03-24 08:41:51 +0100473 /**
474 * Switching to or from incall state or switching between telephony and VoIP lead to force
475 * routing command.
476 */
477 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
478 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700479
480 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700481 checkA2dpSuspend();
482 checkOutputForAllStrategies();
483 updateDevicesAndOutputs();
484
Eric Laurente552edb2014-03-10 17:42:56 -0700485 int delayMs = 0;
486 if (isStateInCall(state)) {
487 nsecs_t sysTime = systemTime();
488 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700489 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700490 // mute media and sonification strategies and delay device switch by the largest
491 // latency of any output where either strategy is active.
492 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100493 if ((isStrategyActive(desc, STRATEGY_MEDIA,
494 SONIFICATION_HEADSET_MUSIC_DELAY,
495 sysTime) ||
496 isStrategyActive(desc, STRATEGY_SONIFICATION,
497 SONIFICATION_HEADSET_MUSIC_DELAY,
498 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700499 (delayMs < (int)desc->latency()*2)) {
500 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700501 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700502 setStrategyMute(STRATEGY_MEDIA, true, desc);
503 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700504 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700505 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
506 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700507 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
508 }
509 }
510
Eric Laurent87ffa392015-05-22 10:32:38 -0700511 if (hasPrimaryOutput()) {
512 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
513 // the device returned is not necessarily reachable via this output
514 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
515 // force routing command to audio hardware when ending call
516 // even if no device change is needed
517 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
518 rxDevice = mPrimaryOutput->device();
519 }
Eric Laurente552edb2014-03-10 17:42:56 -0700520
Eric Laurent87ffa392015-05-22 10:32:38 -0700521 if (state == AUDIO_MODE_IN_CALL) {
522 updateCallRouting(rxDevice, delayMs);
523 } else if (oldState == AUDIO_MODE_IN_CALL) {
524 if (mCallRxPatch != 0) {
525 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
526 mCallRxPatch.clear();
527 }
528 if (mCallTxPatch != 0) {
529 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
530 mCallTxPatch.clear();
531 }
532 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
533 } else {
534 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700535 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700536 }
Eric Laurente552edb2014-03-10 17:42:56 -0700537 // if entering in call state, handle special case of active streams
538 // pertaining to sonification strategy see handleIncallSonification()
539 if (isStateInCall(state)) {
540 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700541 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800542 if (stream == AUDIO_STREAM_PATCH) {
543 continue;
544 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700545 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700546 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700547
548 // force reevaluating accessibility routing when call starts
549 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700550 }
551
552 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700553 if (state == AUDIO_MODE_RINGTONE &&
554 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700555 mLimitRingtoneVolume = true;
556 } else {
557 mLimitRingtoneVolume = false;
558 }
559}
560
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700561audio_mode_t AudioPolicyManager::getPhoneState() {
562 return mEngine->getPhoneState();
563}
564
Eric Laurente0720872014-03-11 09:30:41 -0700565void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700566 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700567{
François Gaffie2110e042015-03-24 08:41:51 +0100568 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700569
François Gaffie2110e042015-03-24 08:41:51 +0100570 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
571 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
572 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700573 }
François Gaffie2110e042015-03-24 08:41:51 +0100574 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
575 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
576 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700577
578 // check for device and output changes triggered by new force usage
579 checkA2dpSuspend();
580 checkOutputForAllStrategies();
581 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700582 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700583 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
584 updateCallRouting(newDevice);
585 }
Eric Laurente552edb2014-03-10 17:42:56 -0700586 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700587 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
588 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
589 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
590 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700591 }
Eric Laurente552edb2014-03-10 17:42:56 -0700592 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700593 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700594 }
595 }
596
François Gaffie53615e22015-03-19 09:24:12 +0100597 audio_io_handle_t activeInput = mInputs.getActiveInput();
Eric Laurente552edb2014-03-10 17:42:56 -0700598 if (activeInput != 0) {
Eric Laurentc171c7c2015-09-25 12:21:06 -0700599 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
600 audio_devices_t newDevice = getNewInputDevice(activeInput);
601 // Force new input selection if the new device can not be reached via current input
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100602 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentc171c7c2015-09-25 12:21:06 -0700603 setInputDevice(activeInput, newDevice);
604 } else {
605 closeInput(activeInput);
606 }
Eric Laurente552edb2014-03-10 17:42:56 -0700607 }
Eric Laurente552edb2014-03-10 17:42:56 -0700608}
609
Eric Laurente0720872014-03-11 09:30:41 -0700610void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700611{
612 ALOGV("setSystemProperty() property %s, value %s", property, value);
613}
614
615// Find a direct output profile compatible with the parameters passed, even if the input flags do
616// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800617sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700618 audio_devices_t device,
619 uint32_t samplingRate,
620 audio_format_t format,
621 audio_channel_mask_t channelMask,
622 audio_output_flags_t flags)
623{
Eric Laurent861a6282015-05-18 15:40:16 -0700624 // only retain flags that will drive the direct output profile selection
625 // if explicitly requested
626 static const uint32_t kRelevantFlags =
627 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
628 flags =
629 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
630
631 sp<IOProfile> profile;
632
Eric Laurente552edb2014-03-10 17:42:56 -0700633 for (size_t i = 0; i < mHwModules.size(); i++) {
634 if (mHwModules[i]->mHandle == 0) {
635 continue;
636 }
637 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700638 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
639 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700640 samplingRate, NULL /*updatedSamplingRate*/,
641 format, NULL /*updatedFormat*/,
642 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700643 flags)) {
644 continue;
645 }
646 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100647 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700648 continue;
649 }
650 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100651 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700652 continue;
653 }
654 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100655 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700656 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700657 }
Eric Laurente552edb2014-03-10 17:42:56 -0700658 }
659 }
Eric Laurent861a6282015-05-18 15:40:16 -0700660 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700661}
662
Eric Laurente0720872014-03-11 09:30:41 -0700663audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100664 uint32_t samplingRate,
665 audio_format_t format,
666 audio_channel_mask_t channelMask,
667 audio_output_flags_t flags,
668 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700669{
Eric Laurent3b73df72014-03-11 09:06:29 -0700670 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700671 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
672 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
673 device, stream, samplingRate, format, channelMask, flags);
674
Eric Laurente83b55d2014-11-14 10:06:21 -0800675 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
676 stream, samplingRate,format, channelMask,
677 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700678}
679
Eric Laurente83b55d2014-11-14 10:06:21 -0800680status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
681 audio_io_handle_t *output,
682 audio_session_t session,
683 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700684 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800685 uint32_t samplingRate,
686 audio_format_t format,
687 audio_channel_mask_t channelMask,
688 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700689 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800690 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700691{
Eric Laurente83b55d2014-11-14 10:06:21 -0800692 audio_attributes_t attributes;
693 if (attr != NULL) {
694 if (!isValidAttributes(attr)) {
695 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
696 attr->usage, attr->content_type, attr->flags,
697 attr->tags);
698 return BAD_VALUE;
699 }
700 attributes = *attr;
701 } else {
702 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
703 ALOGE("getOutputForAttr(): invalid stream type");
704 return BAD_VALUE;
705 }
706 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700707 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700708 sp<SwAudioOutputDescriptor> desc;
François Gaffie036e1e92015-03-19 10:16:24 +0100709 if (mPolicyMixes.getOutputForAttr(attributes, desc) == NO_ERROR) {
710 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
711 if (!audio_is_linear_pcm(format)) {
712 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800713 }
François Gaffie036e1e92015-03-19 10:16:24 +0100714 *stream = streamTypefromAttributesInt(&attributes);
715 *output = desc->mIoHandle;
716 ALOGV("getOutputForAttr() returns output %d", *output);
717 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800718 }
719 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
720 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
721 return BAD_VALUE;
722 }
723
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700724 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
725 " session %d selectedDeviceId %d",
726 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
727 session, selectedDeviceId);
728
729 *stream = streamTypefromAttributesInt(&attributes);
730
731 // Explicit routing?
732 sp<DeviceDescriptor> deviceDesc;
733 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
734 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
735 deviceDesc = mAvailableOutputDevices[i];
736 break;
737 }
738 }
739 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700740
Eric Laurente83b55d2014-11-14 10:06:21 -0800741 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700742 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700743
Eric Laurente83b55d2014-11-14 10:06:21 -0800744 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700745 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
746 }
747
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700748 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700749 device, samplingRate, format, channelMask, flags);
750
Eric Laurente83b55d2014-11-14 10:06:21 -0800751 *output = getOutputForDevice(device, session, *stream,
752 samplingRate, format, channelMask,
753 flags, offloadInfo);
754 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700755 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800756 return INVALID_OPERATION;
757 }
Paul McLeanaa981192015-03-21 09:55:15 -0700758
Eric Laurente83b55d2014-11-14 10:06:21 -0800759 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700760}
761
762audio_io_handle_t AudioPolicyManager::getOutputForDevice(
763 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800764 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700765 audio_stream_type_t stream,
766 uint32_t samplingRate,
767 audio_format_t format,
768 audio_channel_mask_t channelMask,
769 audio_output_flags_t flags,
770 const audio_offload_info_t *offloadInfo)
771{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700772 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700773 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700774 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775
Eric Laurente552edb2014-03-10 17:42:56 -0700776#ifdef AUDIO_POLICY_TEST
777 if (mCurOutput != 0) {
778 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
779 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
780
781 if (mTestOutputs[mCurOutput] == 0) {
782 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700783 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
784 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700785 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700786 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700787 outputDesc->mFlags =
788 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700789 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700790 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
791 config.sample_rate = mTestSamplingRate;
792 config.channel_mask = mTestChannels;
793 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700794 if (offloadInfo != NULL) {
795 config.offload_info = *offloadInfo;
796 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700797 status = mpClientInterface->openOutput(0,
798 &mTestOutputs[mCurOutput],
799 &config,
800 &outputDesc->mDevice,
801 String8(""),
802 &outputDesc->mLatency,
803 outputDesc->mFlags);
804 if (status == NO_ERROR) {
805 outputDesc->mSamplingRate = config.sample_rate;
806 outputDesc->mFormat = config.format;
807 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700808 AudioParameter outputCmd = AudioParameter();
809 outputCmd.addInt(String8("set_id"),mCurOutput);
810 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
811 addOutput(mTestOutputs[mCurOutput], outputDesc);
812 }
813 }
814 return mTestOutputs[mCurOutput];
815 }
816#endif //AUDIO_POLICY_TEST
817
818 // open a direct output if required by specified parameters
819 //force direct flag if offload flag is set: offloading implies a direct output stream
820 // and all common behaviors are driven by checking only the direct flag
821 // this should normally be set appropriately in the policy configuration file
822 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700823 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700825 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
826 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
827 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800828 // only allow deep buffering for music stream type
829 if (stream != AUDIO_STREAM_MUSIC) {
830 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700831 } else if (/* stream == AUDIO_STREAM_MUSIC && */
832 flags == AUDIO_OUTPUT_FLAG_NONE &&
833 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
834 // use DEEP_BUFFER as default output for music stream type
835 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800836 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700837 if (stream == AUDIO_STREAM_TTS) {
838 flags = AUDIO_OUTPUT_FLAG_TTS;
839 }
Eric Laurente552edb2014-03-10 17:42:56 -0700840
Eric Laurentb732cf52014-09-24 19:08:21 -0700841 sp<IOProfile> profile;
842
843 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700844 // and not explicitly requested
845 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
846 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700847 audio_channel_count_from_out_mask(channelMask) <= 2) {
848 goto non_direct_output;
849 }
850
Andy Hung2ddee192015-12-18 17:34:44 -0800851 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
852 // This prevents creating an offloaded track and tearing it down immediately after start
853 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700854 // FIXME: We should check the audio session here but we do not have it in this context.
855 // This may prevent offloading in rare situations where effects are left active by apps
856 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700857
Eric Laurente552edb2014-03-10 17:42:56 -0700858 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800859 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700860 profile = getProfileForDirectOutput(device,
861 samplingRate,
862 format,
863 channelMask,
864 (audio_output_flags_t)flags);
865 }
866
Eric Laurent1c333e22014-05-20 10:48:17 -0700867 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700868 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700869
870 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700871 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700872 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
873 outputDesc = desc;
874 // reuse direct output if currently open and configured with same parameters
875 if ((samplingRate == outputDesc->mSamplingRate) &&
876 (format == outputDesc->mFormat) &&
877 (channelMask == outputDesc->mChannelMask)) {
878 outputDesc->mDirectOpenCount++;
879 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
880 return mOutputs.keyAt(i);
881 }
882 }
883 }
884 // close direct output if currently open and configured with different parameters
885 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700886 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700887 }
Eric Laurent861a6282015-05-18 15:40:16 -0700888
889 // if the selected profile is offloaded and no offload info was specified,
890 // create a default one
891 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100892 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700893 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
894 defaultOffloadInfo.sample_rate = samplingRate;
895 defaultOffloadInfo.channel_mask = channelMask;
896 defaultOffloadInfo.format = format;
897 defaultOffloadInfo.stream_type = stream;
898 defaultOffloadInfo.bit_rate = 0;
899 defaultOffloadInfo.duration_us = -1;
900 defaultOffloadInfo.has_video = true; // conservative
901 defaultOffloadInfo.is_streaming = true; // likely
902 offloadInfo = &defaultOffloadInfo;
903 }
904
Eric Laurentc75307b2015-03-17 15:29:32 -0700905 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700906 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700907 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700908 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700909 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
910 config.sample_rate = samplingRate;
911 config.channel_mask = channelMask;
912 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700913 if (offloadInfo != NULL) {
914 config.offload_info = *offloadInfo;
915 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700916 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700917 &output,
918 &config,
919 &outputDesc->mDevice,
920 String8(""),
921 &outputDesc->mLatency,
922 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700923
924 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700925 if (status != NO_ERROR ||
926 (samplingRate != 0 && samplingRate != config.sample_rate) ||
927 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
928 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700929 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
930 "format %d %d, channelMask %04x %04x", output, samplingRate,
931 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
932 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700933 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700934 mpClientInterface->closeOutput(output);
935 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800936 // fall back to mixer output if possible when the direct output could not be open
937 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
938 goto non_direct_output;
939 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700940 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700942 outputDesc->mSamplingRate = config.sample_rate;
943 outputDesc->mChannelMask = config.channel_mask;
944 outputDesc->mFormat = config.format;
945 outputDesc->mRefCount[stream] = 0;
946 outputDesc->mStopTime[stream] = 0;
947 outputDesc->mDirectOpenCount = 1;
948
Eric Laurente552edb2014-03-10 17:42:56 -0700949 audio_io_handle_t srcOutput = getOutputForEffect();
950 addOutput(output, outputDesc);
951 audio_io_handle_t dstOutput = getOutputForEffect();
952 if (dstOutput == output) {
953 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
954 }
955 mPreviousOutputs = mOutputs;
956 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700957 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700958 return output;
959 }
960
Eric Laurentb732cf52014-09-24 19:08:21 -0700961non_direct_output:
Eric Laurente552edb2014-03-10 17:42:56 -0700962 // ignoring channel mask due to downmix capability in mixer
963
964 // open a non direct output
965
966 // for non direct outputs, only PCM is supported
967 if (audio_is_linear_pcm(format)) {
968 // get which output is suitable for the specified stream. The actual
969 // routing change will happen when startOutput() will be called
970 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
971
Eric Laurent8838a382014-09-08 16:44:28 -0700972 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
973 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
974 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -0700975 }
976 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
977 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
978
Paul McLeanaa981192015-03-21 09:55:15 -0700979 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -0700980
981 return output;
982}
983
Eric Laurente0720872014-03-11 09:30:41 -0700984audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700985 audio_output_flags_t flags,
986 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700987{
988 // select one output among several that provide a path to a particular device or set of
989 // devices (the list was previously build by getOutputsForDevice()).
990 // The priority is as follows:
991 // 1: the output with the highest number of requested policy flags
992 // 2: the primary output
993 // 3: the first output in the list
994
995 if (outputs.size() == 0) {
996 return 0;
997 }
998 if (outputs.size() == 1) {
999 return outputs[0];
1000 }
1001
1002 int maxCommonFlags = 0;
1003 audio_io_handle_t outputFlags = 0;
1004 audio_io_handle_t outputPrimary = 0;
1005
1006 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001007 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001008 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001009 // if a valid format is specified, skip output if not compatible
1010 if (format != AUDIO_FORMAT_INVALID) {
1011 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1012 if (format != outputDesc->mFormat) {
1013 continue;
1014 }
1015 } else if (!audio_is_linear_pcm(format)) {
1016 continue;
1017 }
1018 }
1019
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001020 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001021 if (commonFlags > maxCommonFlags) {
1022 outputFlags = outputs[i];
1023 maxCommonFlags = commonFlags;
1024 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1025 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001026 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente552edb2014-03-10 17:42:56 -07001027 outputPrimary = outputs[i];
1028 }
1029 }
1030 }
1031
1032 if (outputFlags != 0) {
1033 return outputFlags;
1034 }
1035 if (outputPrimary != 0) {
1036 return outputPrimary;
1037 }
1038
1039 return outputs[0];
1040}
1041
Eric Laurente0720872014-03-11 09:30:41 -07001042status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001043 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001044 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001045{
Paul McLeanaa981192015-03-21 09:55:15 -07001046 ALOGV("startOutput() output %d, stream %d, session %d",
1047 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001048 ssize_t index = mOutputs.indexOfKey(output);
1049 if (index < 0) {
1050 ALOGW("startOutput() unknown output %d", output);
1051 return BAD_VALUE;
1052 }
1053
Eric Laurentc75307b2015-03-17 15:29:32 -07001054 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1055
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001056 // Routing?
1057 mOutputRoutes.incRouteActivity(session);
1058
Eric Laurentc75307b2015-03-17 15:29:32 -07001059 audio_devices_t newDevice;
1060 if (outputDesc->mPolicyMix != NULL) {
1061 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent493404d2015-04-21 15:07:36 -07001062 } else if (mOutputRoutes.hasRouteChanged(session)) {
1063 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001064 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001065 } else {
1066 newDevice = AUDIO_DEVICE_NONE;
1067 }
1068
1069 uint32_t delayMs = 0;
1070
Eric Laurentc75307b2015-03-17 15:29:32 -07001071 status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
1072
1073 if (status != NO_ERROR) {
1074 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001075 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001076 }
1077 // Automatically enable the remote submix input when output is started on a re routing mix
1078 // of type MIX_TYPE_RECORDERS
1079 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1080 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1081 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1082 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1083 outputDesc->mPolicyMix->mRegistrationId,
1084 "remote-submix");
1085 }
1086
1087 if (delayMs != 0) {
1088 usleep(delayMs * 1000);
1089 }
1090
1091 return status;
1092}
1093
1094status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1095 audio_stream_type_t stream,
1096 audio_devices_t device,
1097 uint32_t *delayMs)
1098{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001099 // cannot start playback of STREAM_TTS if any other output is being used
1100 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001101
1102 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001103 if (stream == AUDIO_STREAM_TTS) {
1104 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001105 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001106 return INVALID_OPERATION;
1107 } else {
1108 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1109 }
1110 } else {
1111 // some playback other than beacon starts
1112 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1113 }
1114
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001115 // check active before incrementing usage count
1116 bool force = !outputDesc->isActive();
1117
Eric Laurente552edb2014-03-10 17:42:56 -07001118 // increment usage count for this stream on the requested output:
1119 // NOTE that the usage count is the same for duplicated output and hardware output which is
1120 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1121 outputDesc->changeRefCount(stream, 1);
1122
Eric Laurent493404d2015-04-21 15:07:36 -07001123 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001124 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001125 if (device == AUDIO_DEVICE_NONE) {
1126 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001127 }
Eric Laurente552edb2014-03-10 17:42:56 -07001128 routing_strategy strategy = getStrategy(stream);
1129 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001130 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1131 (beaconMuteLatency > 0);
1132 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001133 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001134 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001135 if (desc != outputDesc) {
1136 // force a device change if any other output is managed by the same hw
1137 // module and has a current device selection that differs from selected device.
1138 // In this case, the audio HAL must receive the new device selection so that it can
1139 // change the device currently selected by the other active output.
1140 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001141 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001142 force = true;
1143 }
1144 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001145 // a notification so that audio focus effect can propagate, or that a mute/unmute
1146 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001147 uint32_t latency = desc->latency();
1148 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1149 waitMs = latency;
1150 }
1151 }
1152 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001153 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
Eric Laurente552edb2014-03-10 17:42:56 -07001154
1155 // handle special case for sonification while in call
1156 if (isInCall()) {
1157 handleIncallSonification(stream, true, false);
1158 }
1159
1160 // apply volume rules for current stream and device if necessary
1161 checkAndSetVolume(stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07001162 mStreams.valueFor(stream).getVolumeIndex(device),
1163 outputDesc,
1164 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001165
1166 // update the outputs if starting an output with a stream that can affect notification
1167 // routing
1168 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001169
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001170 // force reevaluating accessibility routing when ringtone or alarm starts
1171 if (strategy == STRATEGY_SONIFICATION) {
1172 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1173 }
Eric Laurente552edb2014-03-10 17:42:56 -07001174 }
1175 return NO_ERROR;
1176}
1177
1178
Eric Laurente0720872014-03-11 09:30:41 -07001179status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001180 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001181 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001182{
1183 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1184 ssize_t index = mOutputs.indexOfKey(output);
1185 if (index < 0) {
1186 ALOGW("stopOutput() unknown output %d", output);
1187 return BAD_VALUE;
1188 }
1189
Eric Laurentc75307b2015-03-17 15:29:32 -07001190 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001191
Eric Laurentc75307b2015-03-17 15:29:32 -07001192 if (outputDesc->mRefCount[stream] == 1) {
1193 // Automatically disable the remote submix input when output is stopped on a
1194 // re routing mix of type MIX_TYPE_RECORDERS
1195 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1196 outputDesc->mPolicyMix != NULL &&
1197 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1198 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1199 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1200 outputDesc->mPolicyMix->mRegistrationId,
1201 "remote-submix");
1202 }
1203 }
1204
1205 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001206 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001207 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001208 int activityCount = mOutputRoutes.decRouteActivity(session);
1209 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1210
1211 if (forceDeviceUpdate) {
1212 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1213 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001214 }
1215
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001216 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001217}
1218
1219status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001220 audio_stream_type_t stream,
1221 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001222{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001223 // always handle stream stop, check which stream type is stopping
1224 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1225
Eric Laurente552edb2014-03-10 17:42:56 -07001226 // handle special case for sonification while in call
1227 if (isInCall()) {
1228 handleIncallSonification(stream, false, false);
1229 }
1230
1231 if (outputDesc->mRefCount[stream] > 0) {
1232 // decrement usage count of this stream on the output
1233 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001234
Eric Laurente552edb2014-03-10 17:42:56 -07001235 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001236 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001237 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001238 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001239 // delay the device switch by twice the latency because stopOutput() is executed when
1240 // the track stop() command is received and at that time the audio track buffer can
1241 // still contain data that needs to be drained. The latency only covers the audio HAL
1242 // and kernel buffers. Also the latency does not always include additional delay in the
1243 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001244 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001245
1246 // force restoring the device selection on other active outputs if it differs from the
1247 // one being selected for this output
1248 for (size_t i = 0; i < mOutputs.size(); i++) {
1249 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001250 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001251 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001252 desc->isActive() &&
1253 outputDesc->sharesHwModuleWith(desc) &&
1254 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001255 setOutputDevice(desc,
1256 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001257 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001258 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001259 }
1260 }
1261 // update the outputs if stopping one with a stream that can affect notification routing
1262 handleNotificationRoutingForStream(stream);
1263 }
1264 return NO_ERROR;
1265 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001266 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001267 return INVALID_OPERATION;
1268 }
1269}
1270
Eric Laurente83b55d2014-11-14 10:06:21 -08001271void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001272 audio_stream_type_t stream __unused,
1273 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001274{
1275 ALOGV("releaseOutput() %d", output);
1276 ssize_t index = mOutputs.indexOfKey(output);
1277 if (index < 0) {
1278 ALOGW("releaseOutput() releasing unknown output %d", output);
1279 return;
1280 }
1281
1282#ifdef AUDIO_POLICY_TEST
1283 int testIndex = testOutputIndex(output);
1284 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001285 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001286 if (outputDesc->isActive()) {
1287 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001288 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001289 mTestOutputs[testIndex] = 0;
1290 }
1291 return;
1292 }
1293#endif //AUDIO_POLICY_TEST
1294
Paul McLeanaa981192015-03-21 09:55:15 -07001295 // Routing
1296 mOutputRoutes.removeRoute(session);
1297
Eric Laurentc75307b2015-03-17 15:29:32 -07001298 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001299 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001300 if (desc->mDirectOpenCount <= 0) {
1301 ALOGW("releaseOutput() invalid open count %d for output %d",
1302 desc->mDirectOpenCount, output);
1303 return;
1304 }
1305 if (--desc->mDirectOpenCount == 0) {
1306 closeOutput(output);
1307 // If effects where present on the output, audioflinger moved them to the primary
1308 // output by default: move them back to the appropriate output.
1309 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001310 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001311 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1312 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001313 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001314 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001315 }
1316 }
1317}
1318
1319
Eric Laurentcaf7f482014-11-25 17:50:47 -08001320status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1321 audio_io_handle_t *input,
1322 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001323 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001324 uint32_t samplingRate,
1325 audio_format_t format,
1326 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001327 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001328 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001329 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001330{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001331 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1332 "session %d, flags %#x",
1333 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001334
Eric Laurentcaf7f482014-11-25 17:50:47 -08001335 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001336 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001337 audio_devices_t device;
1338 // handle legacy remote submix case where the address was not always specified
1339 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001340 audio_source_t inputSource = attr->source;
1341 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001342 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001343
Eric Laurentc447ded2015-01-06 08:47:05 -08001344 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1345 inputSource = AUDIO_SOURCE_MIC;
1346 }
1347 halInputSource = inputSource;
1348
Paul McLean466dc8e2015-04-17 13:15:36 -06001349 // Explicit routing?
1350 sp<DeviceDescriptor> deviceDesc;
1351 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1352 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1353 deviceDesc = mAvailableInputDevices[i];
1354 break;
1355 }
1356 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001357 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001358
Eric Laurentc447ded2015-01-06 08:47:05 -08001359 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001360 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001361 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001362 if (ret != NO_ERROR) {
1363 return ret;
1364 }
1365 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001366 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1367 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001368 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001369 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001370 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001371 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001372 return BAD_VALUE;
1373 }
Eric Laurentc722f302014-12-10 11:21:49 -08001374 if (policyMix != NULL) {
1375 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001376 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1377 // there is an external policy, but this input is attached to a mix of recorders,
1378 // meaning it receives audio injected into the framework, so the recorder doesn't
1379 // know about it and is therefore considered "legacy"
1380 *inputType = API_INPUT_LEGACY;
1381 } else {
1382 // recording a mix of players defined by an external policy, we're rerouting for
1383 // an external policy
1384 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1385 }
Eric Laurentc722f302014-12-10 11:21:49 -08001386 } else if (audio_is_remote_submix_device(device)) {
1387 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001388 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001389 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1390 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001391 } else {
1392 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001393 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001394
Eric Laurent599c7582015-12-07 18:05:55 -08001395 }
1396
1397 *input = getInputForDevice(device, address, session, uid, inputSource,
1398 samplingRate, format, channelMask, flags,
1399 policyMix);
1400 if (*input == AUDIO_IO_HANDLE_NONE) {
1401 mInputRoutes.removeRoute(session);
1402 return INVALID_OPERATION;
1403 }
1404 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1405 return NO_ERROR;
1406}
1407
1408
1409audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1410 String8 address,
1411 audio_session_t session,
1412 uid_t uid,
1413 audio_source_t inputSource,
1414 uint32_t samplingRate,
1415 audio_format_t format,
1416 audio_channel_mask_t channelMask,
1417 audio_input_flags_t flags,
1418 AudioMix *policyMix)
1419{
1420 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1421 audio_source_t halInputSource = inputSource;
1422 bool isSoundTrigger = false;
1423
1424 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1425 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1426 if (index >= 0) {
1427 input = mSoundTriggerSessions.valueFor(session);
1428 isSoundTrigger = true;
1429 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1430 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1431 } else {
1432 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001433 }
1434 }
1435
Andy Hungf129b032015-04-07 13:45:50 -07001436 // find a compatible input profile (not necessarily identical in parameters)
1437 sp<IOProfile> profile;
1438 // samplingRate and flags may be updated by getInputProfile
1439 uint32_t profileSamplingRate = samplingRate;
1440 audio_format_t profileFormat = format;
1441 audio_channel_mask_t profileChannelMask = channelMask;
1442 audio_input_flags_t profileFlags = flags;
1443 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001444 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001445 profileSamplingRate, profileFormat, profileChannelMask,
1446 profileFlags);
1447 if (profile != 0) {
1448 break; // success
1449 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1450 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1451 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001452 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1453 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001454 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001455 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001456 }
Eric Laurente552edb2014-03-10 17:42:56 -07001457 }
1458
Eric Laurent322b4d22015-04-03 15:57:54 -07001459 if (profile->getModuleHandle() == 0) {
1460 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001461 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001462 }
1463
Eric Laurent599c7582015-12-07 18:05:55 -08001464 sp<AudioSession> audioSession = new AudioSession(session,
1465 inputSource,
1466 format,
1467 samplingRate,
1468 channelMask,
1469 flags,
1470 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001471 isSoundTrigger,
1472 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001473
1474// TODO enable input reuse
1475#if 0
1476 // reuse an open input if possible
1477 for (size_t i = 0; i < mInputs.size(); i++) {
1478 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
1479 // reuse input if it shares the same profile and same sound trigger attribute
1480 if (profile == desc->mProfile &&
1481 isSoundTrigger == desc->isSoundTrigger()) {
1482
1483 sp<AudioSession> as = desc->getAudioSession(session);
1484 if (as != 0) {
1485 // do not allow unmatching properties on same session
1486 if (as->matches(audioSession)) {
1487 as->changeOpenCount(1);
1488 } else {
1489 ALOGW("getInputForDevice() record with different attributes"
1490 " exists for session %d", session);
1491 return input;
1492 }
1493 } else {
1494 desc->addAudioSession(session, audioSession);
1495 }
1496 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1497 return mInputs.keyAt(i);
1498 }
1499 }
1500#endif
1501
Eric Laurentcf2c0212014-07-25 16:20:43 -07001502 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001503 config.sample_rate = profileSamplingRate;
1504 config.channel_mask = profileChannelMask;
1505 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001506
Eric Laurent322b4d22015-04-03 15:57:54 -07001507 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001508 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001509 &config,
1510 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001511 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001512 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001513 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001514
1515 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001516 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001517 (profileSamplingRate != config.sample_rate) ||
1518 (profileFormat != config.format) ||
1519 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001520 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1521 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001522 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001523 if (input != AUDIO_IO_HANDLE_NONE) {
1524 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001525 }
Eric Laurent599c7582015-12-07 18:05:55 -08001526 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001527 }
1528
Eric Laurent1f2f2232014-06-02 12:01:23 -07001529 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001530 inputDesc->mSamplingRate = profileSamplingRate;
1531 inputDesc->mFormat = profileFormat;
1532 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001533 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001534 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001535 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001536
Eric Laurent599c7582015-12-07 18:05:55 -08001537 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001538 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001539
Eric Laurent599c7582015-12-07 18:05:55 -08001540 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001541}
1542
Eric Laurent4dc68062014-07-28 17:26:49 -07001543status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1544 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001545{
1546 ALOGV("startInput() input %d", input);
1547 ssize_t index = mInputs.indexOfKey(input);
1548 if (index < 0) {
1549 ALOGW("startInput() unknown input %d", input);
1550 return BAD_VALUE;
1551 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001552 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001553
Eric Laurent599c7582015-12-07 18:05:55 -08001554 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1555 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001556 ALOGW("startInput() unknown session %d on input %d", session, input);
1557 return BAD_VALUE;
1558 }
1559
Glenn Kasten74a8e252014-07-24 14:09:55 -07001560 // virtual input devices are compatible with other input devices
François Gaffie53615e22015-03-19 09:24:12 +01001561 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001562
1563 // for a non-virtual input device, check if there is another (non-virtual) active input
François Gaffie53615e22015-03-19 09:24:12 +01001564 audio_io_handle_t activeInput = mInputs.getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001565 if (activeInput != 0 && activeInput != input) {
1566
1567 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1568 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001569 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurent599c7582015-12-07 18:05:55 -08001570 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
Eric Laurent64265b22015-09-18 18:32:07 -07001571 !activeDesc->hasPreemptedSession(session)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001572 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent599c7582015-12-07 18:05:55 -08001573 //FIXME: consider all active sessions
1574 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1575 audio_session_t activeSession = activeSessions.keyAt(0);
1576 SortedVector<audio_session_t> sessions =
1577 activeDesc->getPreemptedSessions();
Eric Laurent64265b22015-09-18 18:32:07 -07001578 sessions.add(activeSession);
1579 inputDesc->setPreemptedSessions(sessions);
1580 stopInput(activeInput, activeSession);
1581 releaseInput(activeInput, activeSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001582 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001583 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001584 return INVALID_OPERATION;
1585 }
1586 }
Eric Laurentc0a889f2015-10-14 14:36:34 -07001587
1588 // Do not allow capture if an active voice call is using a software patch and
1589 // the call TX source device is on the same HW module.
1590 // FIXME: would be better to refine to only inputs whose profile connects to the
1591 // call TX device but this information is not in the audio patch
1592 if (mCallTxPatch != 0 &&
1593 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1594 return INVALID_OPERATION;
1595 }
Eric Laurente552edb2014-03-10 17:42:56 -07001596 }
1597
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001598 // Routing?
1599 mInputRoutes.incRouteActivity(session);
1600
Eric Laurent599c7582015-12-07 18:05:55 -08001601 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001602 // if input maps to a dynamic policy with an activity listener, notify of state change
1603 if ((inputDesc->mPolicyMix != NULL)
Jean-Michel Trivif613d422015-04-23 18:41:29 -07001604 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001605 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1606 MIX_STATE_MIXING);
1607 }
1608
François Gaffie53615e22015-03-19 09:24:12 +01001609 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001610 SoundTrigger::setCaptureState(true);
1611 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001612 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001613
Eric Laurentc722f302014-12-10 11:21:49 -08001614 // automatically enable the remote submix output when input is started if not
1615 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001616 // For remote submix (a virtual device), we open only one input per capture request.
1617 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001618 String8 address = String8("");
1619 if (inputDesc->mPolicyMix == NULL) {
1620 address = String8("0");
1621 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1622 address = inputDesc->mPolicyMix->mRegistrationId;
1623 }
1624 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001625 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001626 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001627 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001628 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001629 }
Eric Laurente552edb2014-03-10 17:42:56 -07001630 }
1631
Eric Laurent599c7582015-12-07 18:05:55 -08001632 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001633
Eric Laurent599c7582015-12-07 18:05:55 -08001634 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001635 return NO_ERROR;
1636}
1637
Eric Laurent4dc68062014-07-28 17:26:49 -07001638status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1639 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001640{
1641 ALOGV("stopInput() input %d", input);
1642 ssize_t index = mInputs.indexOfKey(input);
1643 if (index < 0) {
1644 ALOGW("stopInput() unknown input %d", input);
1645 return BAD_VALUE;
1646 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001647 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001648
Eric Laurent599c7582015-12-07 18:05:55 -08001649 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001650 if (index < 0) {
1651 ALOGW("stopInput() unknown session %d on input %d", session, input);
1652 return BAD_VALUE;
1653 }
1654
Eric Laurent599c7582015-12-07 18:05:55 -08001655 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001656 ALOGW("stopInput() input %d already stopped", input);
1657 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001658 }
1659
Eric Laurent599c7582015-12-07 18:05:55 -08001660 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001661
1662 // Routing?
1663 mInputRoutes.decRouteActivity(session);
1664
Eric Laurent599c7582015-12-07 18:05:55 -08001665 if (!inputDesc->isActive()) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001666 // if input maps to a dynamic policy with an activity listener, notify of state change
1667 if ((inputDesc->mPolicyMix != NULL)
Jean-Michel Trivif613d422015-04-23 18:41:29 -07001668 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001669 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1670 MIX_STATE_IDLE);
1671 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001672
Eric Laurentc722f302014-12-10 11:21:49 -08001673 // automatically disable the remote submix output when input is stopped if not
1674 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001675 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001676 String8 address = String8("");
1677 if (inputDesc->mPolicyMix == NULL) {
1678 address = String8("0");
1679 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1680 address = inputDesc->mPolicyMix->mRegistrationId;
1681 }
1682 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001683 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001684 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001685 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001686 }
Eric Laurente552edb2014-03-10 17:42:56 -07001687 }
1688
Eric Laurent1c333e22014-05-20 10:48:17 -07001689 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001690
François Gaffie53615e22015-03-19 09:24:12 +01001691 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001692 SoundTrigger::setCaptureState(false);
1693 }
Eric Laurent64265b22015-09-18 18:32:07 -07001694 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001695 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001696 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001697}
1698
Eric Laurent4dc68062014-07-28 17:26:49 -07001699void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1700 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001701{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001702
Eric Laurente552edb2014-03-10 17:42:56 -07001703 ALOGV("releaseInput() %d", input);
1704 ssize_t index = mInputs.indexOfKey(input);
1705 if (index < 0) {
1706 ALOGW("releaseInput() releasing unknown input %d", input);
1707 return;
1708 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001709
1710 // Routing
1711 mInputRoutes.removeRoute(session);
1712
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001713 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1714 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001715
Eric Laurent599c7582015-12-07 18:05:55 -08001716 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001717 if (index < 0) {
1718 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1719 return;
1720 }
Eric Laurent599c7582015-12-07 18:05:55 -08001721
1722 if (audioSession->openCount() == 0) {
1723 ALOGW("releaseInput() invalid open count %d on session %d",
1724 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001725 return;
1726 }
Eric Laurent599c7582015-12-07 18:05:55 -08001727
1728 if (audioSession->changeOpenCount(-1) == 0) {
1729 inputDesc->removeAudioSession(session);
1730 }
1731
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001732 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001733 ALOGV("releaseInput() exit > 0");
1734 return;
1735 }
1736
Eric Laurent05b90f82014-08-27 15:32:29 -07001737 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001738 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001739 ALOGV("releaseInput() exit");
1740}
1741
Eric Laurentd4692962014-05-05 18:13:44 -07001742void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001743 bool patchRemoved = false;
1744
Eric Laurentd4692962014-05-05 18:13:44 -07001745 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001746 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1747 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1748 if (patch_index >= 0) {
1749 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1750 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1751 mAudioPatches.removeItemsAt(patch_index);
1752 patchRemoved = true;
1753 }
Eric Laurentd4692962014-05-05 18:13:44 -07001754 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1755 }
1756 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001757 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001758
1759 if (patchRemoved) {
1760 mpClientInterface->onAudioPatchListUpdate();
1761 }
Eric Laurentd4692962014-05-05 18:13:44 -07001762}
1763
Eric Laurente0720872014-03-11 09:30:41 -07001764void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001765 int indexMin,
1766 int indexMax)
1767{
1768 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffie2110e042015-03-24 08:41:51 +01001769 mEngine->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001770 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1771 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffie2110e042015-03-24 08:41:51 +01001772 mEngine->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001773 }
Eric Laurente552edb2014-03-10 17:42:56 -07001774}
1775
Eric Laurente0720872014-03-11 09:30:41 -07001776status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001777 int index,
1778 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001779{
1780
Eric Laurentc75307b2015-03-17 15:29:32 -07001781 if ((index < mStreams.valueFor(stream).getVolumeIndexMin()) ||
1782 (index > mStreams.valueFor(stream).getVolumeIndexMax())) {
Eric Laurente552edb2014-03-10 17:42:56 -07001783 return BAD_VALUE;
1784 }
1785 if (!audio_is_output_device(device)) {
1786 return BAD_VALUE;
1787 }
1788
1789 // Force max volume if stream cannot be muted
Eric Laurentc75307b2015-03-17 15:29:32 -07001790 if (!mStreams.canBeMuted(stream)) index = mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07001791
1792 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1793 stream, device, index);
1794
1795 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1796 // clear all device specific values
1797 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
François Gaffiedfd74092015-03-19 12:10:59 +01001798 mStreams.clearCurrentVolumeIndex(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001799 }
François Gaffiedfd74092015-03-19 12:10:59 +01001800 mStreams.addCurrentVolumeIndex(stream, device, index);
Eric Laurente552edb2014-03-10 17:42:56 -07001801
Eric Laurent31551f82014-10-10 18:21:56 -07001802 // update volume on all outputs whose current device is also selected by the same
1803 // strategy as the device specified by the caller
1804 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001805
1806
1807 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1808 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1809 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffiedfd74092015-03-19 12:10:59 +01001810 mStreams.addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001811 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1812 }
1813 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1814 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001815 return NO_ERROR;
1816 }
Eric Laurente552edb2014-03-10 17:42:56 -07001817 status_t status = NO_ERROR;
1818 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001819 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1820 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001821 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001822 status_t volStatus = checkAndSetVolume(stream, index, desc, curDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07001823 if (volStatus != NO_ERROR) {
1824 status = volStatus;
1825 }
1826 }
Jean-Michel Triviaf20bc22015-09-14 16:37:07 -07001827 if ((accessibilityDevice != AUDIO_DEVICE_NONE) &&
1828 ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)))
1829 {
Eric Laurent223fd5c2014-11-11 13:43:36 -08001830 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
Eric Laurentc75307b2015-03-17 15:29:32 -07001831 index, desc, curDevice);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001832 }
Eric Laurente552edb2014-03-10 17:42:56 -07001833 }
1834 return status;
1835}
1836
Eric Laurente0720872014-03-11 09:30:41 -07001837status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001838 int *index,
1839 audio_devices_t device)
1840{
1841 if (index == NULL) {
1842 return BAD_VALUE;
1843 }
1844 if (!audio_is_output_device(device)) {
1845 return BAD_VALUE;
1846 }
1847 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1848 // the strategy the stream belongs to.
1849 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1850 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1851 }
François Gaffiedfd74092015-03-19 12:10:59 +01001852 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001853
Eric Laurentc75307b2015-03-17 15:29:32 -07001854 *index = mStreams.valueFor(stream).getVolumeIndex(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001855 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1856 return NO_ERROR;
1857}
1858
Eric Laurente0720872014-03-11 09:30:41 -07001859audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001860 const SortedVector<audio_io_handle_t>& outputs)
1861{
1862 // select one output among several suitable for global effects.
1863 // The priority is as follows:
1864 // 1: An offloaded output. If the effect ends up not being offloadable,
1865 // AudioFlinger will invalidate the track and the offloaded output
1866 // will be closed causing the effect to be moved to a PCM output.
1867 // 2: A deep buffer output
1868 // 3: the first output in the list
1869
1870 if (outputs.size() == 0) {
1871 return 0;
1872 }
1873
1874 audio_io_handle_t outputOffloaded = 0;
1875 audio_io_handle_t outputDeepBuffer = 0;
1876
1877 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001878 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001879 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001880 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1881 outputOffloaded = outputs[i];
1882 }
1883 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1884 outputDeepBuffer = outputs[i];
1885 }
1886 }
1887
1888 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1889 outputOffloaded, outputDeepBuffer);
1890 if (outputOffloaded != 0) {
1891 return outputOffloaded;
1892 }
1893 if (outputDeepBuffer != 0) {
1894 return outputDeepBuffer;
1895 }
1896
1897 return outputs[0];
1898}
1899
Eric Laurente0720872014-03-11 09:30:41 -07001900audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001901{
1902 // apply simple rule where global effects are attached to the same output as MUSIC streams
1903
Eric Laurent3b73df72014-03-11 09:06:29 -07001904 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001905 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1906 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1907
1908 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1909 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1910 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1911
1912 return output;
1913}
1914
Eric Laurente0720872014-03-11 09:30:41 -07001915status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001916 audio_io_handle_t io,
1917 uint32_t strategy,
1918 int session,
1919 int id)
1920{
1921 ssize_t index = mOutputs.indexOfKey(io);
1922 if (index < 0) {
1923 index = mInputs.indexOfKey(io);
1924 if (index < 0) {
1925 ALOGW("registerEffect() unknown io %d", io);
1926 return INVALID_OPERATION;
1927 }
1928 }
François Gaffie45ed3b02015-03-19 10:35:14 +01001929 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07001930}
1931
Eric Laurentc75307b2015-03-17 15:29:32 -07001932bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1933{
1934 return mOutputs.isStreamActive(stream, inPastMs);
1935}
1936
1937bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
1938{
1939 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
1940}
1941
Eric Laurente0720872014-03-11 09:30:41 -07001942bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001943{
1944 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001945 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001946 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001947 return true;
1948 }
1949 }
1950 return false;
1951}
1952
Eric Laurent275e8e92014-11-30 15:14:47 -08001953// Register a list of custom mixes with their attributes and format.
1954// When a mix is registered, corresponding input and output profiles are
1955// added to the remote submix hw module. The profile contains only the
1956// parameters (sampling rate, format...) specified by the mix.
1957// The corresponding input remote submix device is also connected.
1958//
1959// When a remote submix device is connected, the address is checked to select the
1960// appropriate profile and the corresponding input or output stream is opened.
1961//
1962// When capture starts, getInputForAttr() will:
1963// - 1 look for a mix matching the address passed in attribtutes tags if any
1964// - 2 if none found, getDeviceForInputSource() will:
1965// - 2.1 look for a mix matching the attributes source
1966// - 2.2 if none found, default to device selection by policy rules
1967// At this time, the corresponding output remote submix device is also connected
1968// and active playback use cases can be transferred to this mix if needed when reconnecting
1969// after AudioTracks are invalidated
1970//
1971// When playback starts, getOutputForAttr() will:
1972// - 1 look for a mix matching the address passed in attribtutes tags if any
1973// - 2 if none found, look for a mix matching the attributes usage
1974// - 3 if none found, default to device and output selection by policy rules.
1975
1976status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
1977{
1978 sp<HwModule> module;
1979 for (size_t i = 0; i < mHwModules.size(); i++) {
1980 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1981 mHwModules[i]->mHandle != 0) {
1982 module = mHwModules[i];
1983 break;
1984 }
1985 }
1986
1987 if (module == 0) {
1988 return INVALID_OPERATION;
1989 }
1990
Eric Laurent7b279bb2015-12-14 10:18:23 -08001991 ALOGV("registerPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08001992
1993 for (size_t i = 0; i < mixes.size(); i++) {
1994 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01001995
1996 if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001997 continue;
1998 }
1999 audio_config_t outputConfig = mixes[i].mFormat;
2000 audio_config_t inputConfig = mixes[i].mFormat;
2001 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2002 // stereo and let audio flinger do the channel conversion if needed.
2003 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2004 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2005 module->addOutputProfile(address, &outputConfig,
2006 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2007 module->addInputProfile(address, &inputConfig,
2008 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002009
Eric Laurentc722f302014-12-10 11:21:49 -08002010 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002011 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002012 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002013 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002014 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002015 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002016 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002017 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002018 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002019 }
2020 return NO_ERROR;
2021}
2022
2023status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2024{
2025 sp<HwModule> module;
2026 for (size_t i = 0; i < mHwModules.size(); i++) {
2027 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2028 mHwModules[i]->mHandle != 0) {
2029 module = mHwModules[i];
2030 break;
2031 }
2032 }
2033
2034 if (module == 0) {
2035 return INVALID_OPERATION;
2036 }
2037
Eric Laurent7b279bb2015-12-14 10:18:23 -08002038 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002039
2040 for (size_t i = 0; i < mixes.size(); i++) {
2041 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01002042
2043 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002044 continue;
2045 }
2046
Eric Laurentc722f302014-12-10 11:21:49 -08002047 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2048 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2049 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002050 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002051 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002052 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002053 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002054
2055 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2056 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2057 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002058 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002059 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002060 address.string(), "remote-submix");
Eric Laurent275e8e92014-11-30 15:14:47 -08002061 }
2062 module->removeOutputProfile(address);
2063 module->removeInputProfile(address);
2064 }
2065 return NO_ERROR;
2066}
2067
Eric Laurente552edb2014-03-10 17:42:56 -07002068
Eric Laurente0720872014-03-11 09:30:41 -07002069status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002070{
2071 const size_t SIZE = 256;
2072 char buffer[SIZE];
2073 String8 result;
2074
2075 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2076 result.append(buffer);
2077
Eric Laurent87ffa392015-05-22 10:32:38 -07002078 snprintf(buffer, SIZE, " Primary Output: %d\n",
2079 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002080 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002081 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002082 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002083 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002084 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002085 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002086 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002087 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002088 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002089 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002090 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002091 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002092 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002093 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002094 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002095 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002096 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002097 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2098 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002099 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2100 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002101
François Gaffie2110e042015-03-24 08:41:51 +01002102 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002103
François Gaffie112b0af2015-11-19 16:13:25 +01002104 mAvailableOutputDevices.dump(fd, String8("Available output"));
2105 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002106 mHwModules.dump(fd);
2107 mOutputs.dump(fd);
2108 mInputs.dump(fd);
François Gaffiedfd74092015-03-19 12:10:59 +01002109 mStreams.dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002110 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002111 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002112
2113 return NO_ERROR;
2114}
2115
2116// This function checks for the parameters which can be offloaded.
2117// This can be enhanced depending on the capability of the DSP and policy
2118// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002119bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002120{
2121 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002122 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002123 offloadInfo.sample_rate, offloadInfo.channel_mask,
2124 offloadInfo.format,
2125 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2126 offloadInfo.has_video);
2127
Andy Hung2ddee192015-12-18 17:34:44 -08002128 if (mMasterMono) {
2129 return false; // no offloading if mono is set.
2130 }
2131
Eric Laurente552edb2014-03-10 17:42:56 -07002132 // Check if offload has been disabled
2133 char propValue[PROPERTY_VALUE_MAX];
2134 if (property_get("audio.offload.disable", propValue, "0")) {
2135 if (atoi(propValue) != 0) {
2136 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2137 return false;
2138 }
2139 }
2140
2141 // Check if stream type is music, then only allow offload as of now.
2142 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2143 {
2144 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2145 return false;
2146 }
2147
2148 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002149 const bool allowOffloadWithVideo =
2150 property_get_bool("audio.offload.video", false /* default_value */);
2151 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002152 ALOGV("isOffloadSupported: has_video == true, returning false");
2153 return false;
2154 }
2155
2156 //If duration is less than minimum value defined in property, return false
2157 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2158 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2159 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2160 return false;
2161 }
2162 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2163 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2164 return false;
2165 }
2166
2167 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2168 // creating an offloaded track and tearing it down immediately after start when audioflinger
2169 // detects there is an active non offloadable effect.
2170 // FIXME: We should check the audio session here but we do not have it in this context.
2171 // This may prevent offloading in rare situations where effects are left active by apps
2172 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002173 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002174 return false;
2175 }
2176
2177 // See if there is a profile to support this.
2178 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002179 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002180 offloadInfo.sample_rate,
2181 offloadInfo.format,
2182 offloadInfo.channel_mask,
2183 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002184 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2185 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002186}
2187
Eric Laurent6a94d692014-05-20 11:18:06 -07002188status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2189 audio_port_type_t type,
2190 unsigned int *num_ports,
2191 struct audio_port *ports,
2192 unsigned int *generation)
2193{
2194 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2195 generation == NULL) {
2196 return BAD_VALUE;
2197 }
2198 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2199 if (ports == NULL) {
2200 *num_ports = 0;
2201 }
2202
2203 size_t portsWritten = 0;
2204 size_t portsMax = *num_ports;
2205 *num_ports = 0;
2206 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2207 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2208 for (size_t i = 0;
2209 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2210 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2211 }
2212 *num_ports += mAvailableOutputDevices.size();
2213 }
2214 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2215 for (size_t i = 0;
2216 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2217 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2218 }
2219 *num_ports += mAvailableInputDevices.size();
2220 }
2221 }
2222 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2223 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2224 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2225 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2226 }
2227 *num_ports += mInputs.size();
2228 }
2229 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002230 size_t numOutputs = 0;
2231 for (size_t i = 0; i < mOutputs.size(); i++) {
2232 if (!mOutputs[i]->isDuplicated()) {
2233 numOutputs++;
2234 if (portsWritten < portsMax) {
2235 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2236 }
2237 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002238 }
Eric Laurent84c70242014-06-23 08:46:27 -07002239 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002240 }
2241 }
2242 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002243 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002244 return NO_ERROR;
2245}
2246
2247status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2248{
2249 return NO_ERROR;
2250}
2251
Eric Laurent6a94d692014-05-20 11:18:06 -07002252status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2253 audio_patch_handle_t *handle,
2254 uid_t uid)
2255{
2256 ALOGV("createAudioPatch()");
2257
2258 if (handle == NULL || patch == NULL) {
2259 return BAD_VALUE;
2260 }
2261 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2262
Eric Laurent874c42872014-08-08 15:13:39 -07002263 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2264 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2265 return BAD_VALUE;
2266 }
2267 // only one source per audio patch supported for now
2268 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002269 return INVALID_OPERATION;
2270 }
Eric Laurent874c42872014-08-08 15:13:39 -07002271
2272 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002273 return INVALID_OPERATION;
2274 }
Eric Laurent874c42872014-08-08 15:13:39 -07002275 for (size_t i = 0; i < patch->num_sinks; i++) {
2276 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2277 return INVALID_OPERATION;
2278 }
2279 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002280
2281 sp<AudioPatch> patchDesc;
2282 ssize_t index = mAudioPatches.indexOfKey(*handle);
2283
Eric Laurent6a94d692014-05-20 11:18:06 -07002284 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2285 patch->sources[0].role,
2286 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002287#if LOG_NDEBUG == 0
2288 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002289 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002290 patch->sinks[i].role,
2291 patch->sinks[i].type);
2292 }
2293#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002294
2295 if (index >= 0) {
2296 patchDesc = mAudioPatches.valueAt(index);
2297 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2298 mUidCached, patchDesc->mUid, uid);
2299 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2300 return INVALID_OPERATION;
2301 }
2302 } else {
2303 *handle = 0;
2304 }
2305
2306 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002307 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002308 if (outputDesc == NULL) {
2309 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2310 return BAD_VALUE;
2311 }
Eric Laurent84c70242014-06-23 08:46:27 -07002312 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2313 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002314 if (patchDesc != 0) {
2315 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2316 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2317 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2318 return BAD_VALUE;
2319 }
2320 }
Eric Laurent874c42872014-08-08 15:13:39 -07002321 DeviceVector devices;
2322 for (size_t i = 0; i < patch->num_sinks; i++) {
2323 // Only support mix to devices connection
2324 // TODO add support for mix to mix connection
2325 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2326 ALOGV("createAudioPatch() source mix but sink is not a device");
2327 return INVALID_OPERATION;
2328 }
2329 sp<DeviceDescriptor> devDesc =
2330 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2331 if (devDesc == 0) {
2332 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2333 return BAD_VALUE;
2334 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002335
François Gaffie53615e22015-03-19 09:24:12 +01002336 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002337 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002338 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002339 NULL, // updatedSamplingRate
2340 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002341 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002342 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002343 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002344 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002345 ALOGV("createAudioPatch() profile not supported for device %08x",
2346 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002347 return INVALID_OPERATION;
2348 }
2349 devices.add(devDesc);
2350 }
2351 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002352 return INVALID_OPERATION;
2353 }
Eric Laurent874c42872014-08-08 15:13:39 -07002354
Eric Laurent6a94d692014-05-20 11:18:06 -07002355 // TODO: reconfigure output format and channels here
2356 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002357 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002358 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002359 index = mAudioPatches.indexOfKey(*handle);
2360 if (index >= 0) {
2361 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2362 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2363 }
2364 patchDesc = mAudioPatches.valueAt(index);
2365 patchDesc->mUid = uid;
2366 ALOGV("createAudioPatch() success");
2367 } else {
2368 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2369 return INVALID_OPERATION;
2370 }
2371 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2372 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2373 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002374 // only one sink supported when connecting an input device to a mix
2375 if (patch->num_sinks > 1) {
2376 return INVALID_OPERATION;
2377 }
François Gaffie53615e22015-03-19 09:24:12 +01002378 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002379 if (inputDesc == NULL) {
2380 return BAD_VALUE;
2381 }
2382 if (patchDesc != 0) {
2383 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2384 return BAD_VALUE;
2385 }
2386 }
2387 sp<DeviceDescriptor> devDesc =
2388 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2389 if (devDesc == 0) {
2390 return BAD_VALUE;
2391 }
2392
François Gaffie53615e22015-03-19 09:24:12 +01002393 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002394 devDesc->mAddress,
2395 patch->sinks[0].sample_rate,
2396 NULL, /*updatedSampleRate*/
2397 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002398 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002399 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002400 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002401 // FIXME for the parameter type,
2402 // and the NONE
2403 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002404 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002405 return INVALID_OPERATION;
2406 }
2407 // TODO: reconfigure output format and channels here
2408 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002409 devDesc->type(), inputDesc->mIoHandle);
2410 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002411 index = mAudioPatches.indexOfKey(*handle);
2412 if (index >= 0) {
2413 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2414 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2415 }
2416 patchDesc = mAudioPatches.valueAt(index);
2417 patchDesc->mUid = uid;
2418 ALOGV("createAudioPatch() success");
2419 } else {
2420 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2421 return INVALID_OPERATION;
2422 }
2423 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2424 // device to device connection
2425 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002426 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002427 return BAD_VALUE;
2428 }
2429 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002430 sp<DeviceDescriptor> srcDeviceDesc =
2431 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002432 if (srcDeviceDesc == 0) {
2433 return BAD_VALUE;
2434 }
Eric Laurent874c42872014-08-08 15:13:39 -07002435
Eric Laurent6a94d692014-05-20 11:18:06 -07002436 //update source and sink with our own data as the data passed in the patch may
2437 // be incomplete.
2438 struct audio_patch newPatch = *patch;
2439 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002440
Eric Laurent874c42872014-08-08 15:13:39 -07002441 for (size_t i = 0; i < patch->num_sinks; i++) {
2442 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2443 ALOGV("createAudioPatch() source device but one sink is not a device");
2444 return INVALID_OPERATION;
2445 }
2446
2447 sp<DeviceDescriptor> sinkDeviceDesc =
2448 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2449 if (sinkDeviceDesc == 0) {
2450 return BAD_VALUE;
2451 }
2452 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2453
Eric Laurent3bcf8592015-04-03 12:13:24 -07002454 // create a software bridge in PatchPanel if:
2455 // - source and sink devices are on differnt HW modules OR
2456 // - audio HAL version is < 3.0
2457 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002458 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002459 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002460 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002461 return INVALID_OPERATION;
2462 }
Eric Laurent874c42872014-08-08 15:13:39 -07002463 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002464 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002465 // if the sink device is reachable via an opened output stream, request to go via
2466 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002467 audio_io_handle_t output = selectOutput(outputs,
2468 AUDIO_OUTPUT_FLAG_NONE,
2469 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002470 if (output != AUDIO_IO_HANDLE_NONE) {
2471 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2472 if (outputDesc->isDuplicated()) {
2473 return INVALID_OPERATION;
2474 }
2475 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002476 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002477 newPatch.num_sources = 2;
2478 }
Eric Laurent83b88082014-06-20 18:31:16 -07002479 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002480 }
2481 // TODO: check from routing capabilities in config file and other conflicting patches
2482
2483 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2484 if (index >= 0) {
2485 afPatchHandle = patchDesc->mAfPatchHandle;
2486 }
2487
2488 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2489 &afPatchHandle,
2490 0);
2491 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2492 status, afPatchHandle);
2493 if (status == NO_ERROR) {
2494 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002495 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002496 addAudioPatch(patchDesc->mHandle, patchDesc);
2497 } else {
2498 patchDesc->mPatch = newPatch;
2499 }
2500 patchDesc->mAfPatchHandle = afPatchHandle;
2501 *handle = patchDesc->mHandle;
2502 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002503 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002504 } else {
2505 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2506 status);
2507 return INVALID_OPERATION;
2508 }
2509 } else {
2510 return BAD_VALUE;
2511 }
2512 } else {
2513 return BAD_VALUE;
2514 }
2515 return NO_ERROR;
2516}
2517
2518status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2519 uid_t uid)
2520{
2521 ALOGV("releaseAudioPatch() patch %d", handle);
2522
2523 ssize_t index = mAudioPatches.indexOfKey(handle);
2524
2525 if (index < 0) {
2526 return BAD_VALUE;
2527 }
2528 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2529 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2530 mUidCached, patchDesc->mUid, uid);
2531 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2532 return INVALID_OPERATION;
2533 }
2534
2535 struct audio_patch *patch = &patchDesc->mPatch;
2536 patchDesc->mUid = mUidCached;
2537 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002538 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002539 if (outputDesc == NULL) {
2540 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2541 return BAD_VALUE;
2542 }
2543
Eric Laurentc75307b2015-03-17 15:29:32 -07002544 setOutputDevice(outputDesc,
2545 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002546 true,
2547 0,
2548 NULL);
2549 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2550 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002551 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002552 if (inputDesc == NULL) {
2553 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2554 return BAD_VALUE;
2555 }
2556 setInputDevice(inputDesc->mIoHandle,
2557 getNewInputDevice(inputDesc->mIoHandle),
2558 true,
2559 NULL);
2560 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2561 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2562 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2563 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2564 status, patchDesc->mAfPatchHandle);
2565 removeAudioPatch(patchDesc->mHandle);
2566 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002567 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002568 } else {
2569 return BAD_VALUE;
2570 }
2571 } else {
2572 return BAD_VALUE;
2573 }
2574 return NO_ERROR;
2575}
2576
2577status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2578 struct audio_patch *patches,
2579 unsigned int *generation)
2580{
François Gaffie53615e22015-03-19 09:24:12 +01002581 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002582 return BAD_VALUE;
2583 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002584 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002585 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002586}
2587
Eric Laurente1715a42014-05-20 11:30:42 -07002588status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002589{
Eric Laurente1715a42014-05-20 11:30:42 -07002590 ALOGV("setAudioPortConfig()");
2591
2592 if (config == NULL) {
2593 return BAD_VALUE;
2594 }
2595 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2596 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002597 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2598 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002599 }
2600
Eric Laurenta121f902014-06-03 13:32:54 -07002601 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002602 if (config->type == AUDIO_PORT_TYPE_MIX) {
2603 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002604 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002605 if (outputDesc == NULL) {
2606 return BAD_VALUE;
2607 }
Eric Laurent84c70242014-06-23 08:46:27 -07002608 ALOG_ASSERT(!outputDesc->isDuplicated(),
2609 "setAudioPortConfig() called on duplicated output %d",
2610 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002611 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002612 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002613 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002614 if (inputDesc == NULL) {
2615 return BAD_VALUE;
2616 }
Eric Laurenta121f902014-06-03 13:32:54 -07002617 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002618 } else {
2619 return BAD_VALUE;
2620 }
2621 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2622 sp<DeviceDescriptor> deviceDesc;
2623 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2624 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2625 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2626 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2627 } else {
2628 return BAD_VALUE;
2629 }
2630 if (deviceDesc == NULL) {
2631 return BAD_VALUE;
2632 }
Eric Laurenta121f902014-06-03 13:32:54 -07002633 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002634 } else {
2635 return BAD_VALUE;
2636 }
2637
Eric Laurenta121f902014-06-03 13:32:54 -07002638 struct audio_port_config backupConfig;
2639 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2640 if (status == NO_ERROR) {
2641 struct audio_port_config newConfig;
2642 audioPortConfig->toAudioPortConfig(&newConfig, config);
2643 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002644 }
Eric Laurenta121f902014-06-03 13:32:54 -07002645 if (status != NO_ERROR) {
2646 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002647 }
Eric Laurente1715a42014-05-20 11:30:42 -07002648
2649 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002650}
2651
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002652void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2653{
Eric Laurentd60560a2015-04-10 11:31:20 -07002654 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002655 clearAudioPatches(uid);
2656 clearSessionRoutes(uid);
2657}
2658
Eric Laurent6a94d692014-05-20 11:18:06 -07002659void AudioPolicyManager::clearAudioPatches(uid_t uid)
2660{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002661 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002662 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2663 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002664 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002665 }
2666 }
2667}
2668
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002669void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2670 audio_io_handle_t ouptutToSkip)
2671{
2672 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2673 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2674 for (size_t j = 0; j < mOutputs.size(); j++) {
2675 if (mOutputs.keyAt(j) == ouptutToSkip) {
2676 continue;
2677 }
2678 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2679 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2680 continue;
2681 }
2682 // If the default device for this strategy is on another output mix,
2683 // invalidate all tracks in this strategy to force re connection.
2684 // Otherwise select new device on the output mix.
2685 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
2686 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
2687 if (stream == AUDIO_STREAM_PATCH) {
2688 continue;
2689 }
2690 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2691 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2692 }
2693 }
2694 } else {
2695 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2696 setOutputDevice(outputDesc, newDevice, false);
2697 }
2698 }
2699}
2700
2701void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2702{
2703 // remove output routes associated with this uid
2704 SortedVector<routing_strategy> affectedStrategies;
2705 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2706 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2707 if (route->mUid == uid) {
2708 mOutputRoutes.removeItemsAt(i);
2709 if (route->mDeviceDescriptor != 0) {
2710 affectedStrategies.add(getStrategy(route->mStreamType));
2711 }
2712 }
2713 }
2714 // reroute outputs if necessary
2715 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2716 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2717 }
2718
2719 // remove input routes associated with this uid
2720 SortedVector<audio_source_t> affectedSources;
2721 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2722 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2723 if (route->mUid == uid) {
2724 mInputRoutes.removeItemsAt(i);
2725 if (route->mDeviceDescriptor != 0) {
2726 affectedSources.add(route->mSource);
2727 }
2728 }
2729 }
2730 // reroute inputs if necessary
2731 SortedVector<audio_io_handle_t> inputsToClose;
2732 for (size_t i = 0; i < mInputs.size(); i++) {
2733 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002734 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002735 inputsToClose.add(inputDesc->mIoHandle);
2736 }
2737 }
2738 for (size_t i = 0; i < inputsToClose.size(); i++) {
2739 closeInput(inputsToClose[i]);
2740 }
2741}
2742
Eric Laurentd60560a2015-04-10 11:31:20 -07002743void AudioPolicyManager::clearAudioSources(uid_t uid)
2744{
2745 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2746 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2747 if (sourceDesc->mUid == uid) {
2748 stopAudioSource(mAudioSources.keyAt(i));
2749 }
2750 }
2751}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002752
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002753status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2754 audio_io_handle_t *ioHandle,
2755 audio_devices_t *device)
2756{
2757 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2758 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002759 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002760
François Gaffiedf372692015-03-19 10:43:27 +01002761 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002762}
2763
Eric Laurentd60560a2015-04-10 11:31:20 -07002764status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2765 const audio_attributes_t *attributes,
2766 audio_io_handle_t *handle,
2767 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002768{
Eric Laurentd60560a2015-04-10 11:31:20 -07002769 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2770 if (source == NULL || attributes == NULL || handle == NULL) {
2771 return BAD_VALUE;
2772 }
2773
2774 *handle = AUDIO_IO_HANDLE_NONE;
2775
2776 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2777 source->type != AUDIO_PORT_TYPE_DEVICE) {
2778 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2779 return INVALID_OPERATION;
2780 }
2781
2782 sp<DeviceDescriptor> srcDeviceDesc =
2783 mAvailableInputDevices.getDevice(source->ext.device.type,
2784 String8(source->ext.device.address));
2785 if (srcDeviceDesc == 0) {
2786 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2787 return BAD_VALUE;
2788 }
2789 sp<AudioSourceDescriptor> sourceDesc =
2790 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2791
2792 struct audio_patch dummyPatch;
2793 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2794 sourceDesc->mPatchDesc = patchDesc;
2795
2796 status_t status = connectAudioSource(sourceDesc);
2797 if (status == NO_ERROR) {
2798 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2799 *handle = sourceDesc->getHandle();
2800 }
2801 return status;
2802}
2803
2804status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2805{
2806 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2807
2808 // make sure we only have one patch per source.
2809 disconnectAudioSource(sourceDesc);
2810
2811 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2812 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2813 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2814
2815 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2816 sp<DeviceDescriptor> sinkDeviceDesc =
2817 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2818
2819 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2820 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2821
2822 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2823 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002824 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002825 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2826 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2827 // create patch between src device and output device
2828 // create Hwoutput and add to mHwOutputs
2829 } else {
2830 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2831 audio_io_handle_t output =
2832 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2833 if (output == AUDIO_IO_HANDLE_NONE) {
2834 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2835 return INVALID_OPERATION;
2836 }
2837 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2838 if (outputDesc->isDuplicated()) {
2839 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2840 return INVALID_OPERATION;
2841 }
2842 // create a special patch with no sink and two sources:
2843 // - the second source indicates to PatchPanel through which output mix this patch should
2844 // be connected as well as the stream type for volume control
2845 // - the sink is defined by whatever output device is currently selected for the output
2846 // though which this patch is routed.
2847 patch->num_sinks = 0;
2848 patch->num_sources = 2;
2849 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2850 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2851 patch->sources[1].ext.mix.usecase.stream = stream;
2852 status_t status = mpClientInterface->createAudioPatch(patch,
2853 &afPatchHandle,
2854 0);
2855 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
2856 status, afPatchHandle);
2857 if (status != NO_ERROR) {
2858 ALOGW("%s patch panel could not connect device patch, error %d",
2859 __FUNCTION__, status);
2860 return INVALID_OPERATION;
2861 }
2862 uint32_t delayMs = 0;
2863 status = startSource(outputDesc, stream, sinkDevice, &delayMs);
2864
2865 if (status != NO_ERROR) {
2866 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
2867 return status;
2868 }
2869 sourceDesc->mSwOutput = outputDesc;
2870 if (delayMs != 0) {
2871 usleep(delayMs * 1000);
2872 }
2873 }
2874
2875 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
2876 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
2877
2878 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07002879}
2880
Eric Laurent493404d2015-04-21 15:07:36 -07002881status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07002882{
Eric Laurentd60560a2015-04-10 11:31:20 -07002883 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
2884 ALOGV("%s handle %d", __FUNCTION__, handle);
2885 if (sourceDesc == 0) {
2886 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
2887 return BAD_VALUE;
2888 }
2889 status_t status = disconnectAudioSource(sourceDesc);
2890
2891 mAudioSources.removeItem(handle);
2892 return status;
2893}
2894
Andy Hung2ddee192015-12-18 17:34:44 -08002895status_t AudioPolicyManager::setMasterMono(bool mono)
2896{
2897 if (mMasterMono == mono) {
2898 return NO_ERROR;
2899 }
2900 mMasterMono = mono;
2901 // if enabling mono we close all offloaded devices, which will invalidate the
2902 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
2903 // for recreating the new AudioTrack as non-offloaded PCM.
2904 //
2905 // If disabling mono, we leave all tracks as is: we don't know which clients
2906 // and tracks are able to be recreated as offloaded. The next "song" should
2907 // play back offloaded.
2908 if (mMasterMono) {
2909 Vector<audio_io_handle_t> offloaded;
2910 for (size_t i = 0; i < mOutputs.size(); ++i) {
2911 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2912 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2913 offloaded.push(desc->mIoHandle);
2914 }
2915 }
2916 for (size_t i = 0; i < offloaded.size(); ++i) {
2917 closeOutput(offloaded[i]);
2918 }
2919 }
2920 // update master mono for all remaining outputs
2921 for (size_t i = 0; i < mOutputs.size(); ++i) {
2922 updateMono(mOutputs.keyAt(i));
2923 }
2924 return NO_ERROR;
2925}
2926
2927status_t AudioPolicyManager::getMasterMono(bool *mono)
2928{
2929 *mono = mMasterMono;
2930 return NO_ERROR;
2931}
2932
Eric Laurentd60560a2015-04-10 11:31:20 -07002933status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2934{
2935 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2936
2937 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
2938 if (patchDesc == 0) {
2939 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
2940 sourceDesc->mPatchDesc->mHandle);
2941 return BAD_VALUE;
2942 }
2943 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
2944
2945 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2946 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
2947 if (swOutputDesc != 0) {
2948 stopSource(swOutputDesc, stream, false);
2949 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2950 } else {
2951 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
2952 if (hwOutputDesc != 0) {
2953 // release patch between src device and output device
2954 // close Hwoutput and remove from mHwOutputs
2955 } else {
2956 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
2957 }
2958 }
2959 return NO_ERROR;
2960}
2961
2962sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
2963 audio_io_handle_t output, routing_strategy strategy)
2964{
2965 sp<AudioSourceDescriptor> source;
2966 for (size_t i = 0; i < mAudioSources.size(); i++) {
2967 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2968 routing_strategy sourceStrategy =
2969 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2970 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
2971 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
2972 source = sourceDesc;
2973 break;
2974 }
2975 }
2976 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07002977}
2978
Eric Laurente552edb2014-03-10 17:42:56 -07002979// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002980// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002981// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07002982uint32_t AudioPolicyManager::nextAudioPortGeneration()
2983{
2984 return android_atomic_inc(&mAudioPortGeneration);
2985}
2986
Eric Laurente0720872014-03-11 09:30:41 -07002987AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002988 :
2989#ifdef AUDIO_POLICY_TEST
2990 Thread(false),
2991#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07002992 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002993 mA2dpSuspended(false),
Paul McLeane743a472015-01-28 11:07:31 -08002994 mSpeakerDrcEnabled(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002995 mAudioPortGeneration(1),
2996 mBeaconMuteRefCount(0),
2997 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07002998 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08002999 mTtsOutputAvailable(false),
3000 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003001{
François Gaffie2110e042015-03-24 08:41:51 +01003002 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3003 if (!engineInstance) {
3004 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3005 return;
3006 }
3007 // Retrieve the Policy Manager Interface
3008 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3009 if (mEngine == NULL) {
3010 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3011 return;
3012 }
3013 mEngine->setObserver(this);
3014 status_t status = mEngine->initCheck();
3015 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3016
Eric Laurent6a94d692014-05-20 11:18:06 -07003017 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003018 mpClientInterface = clientInterface;
3019
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003020 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3021 mDefaultOutputDevice, mSpeakerDrcEnabled);
3022
François Gaffief4ad6e52015-11-19 16:59:57 +01003023#ifdef USE_XML_AUDIO_POLICY_CONF
3024 PolicySerializer serializer;
3025 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3026#else
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003027 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
François Gaffief4ad6e52015-11-19 16:59:57 +01003028 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3029#endif
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003030 ALOGE("could not load audio policy configuration file, setting defaults");
3031 config.setDefault();
Eric Laurente552edb2014-03-10 17:42:56 -07003032 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003033 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003034
François Gaffie2110e042015-03-24 08:41:51 +01003035 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3036 mEngine->initializeVolumeCurves(mSpeakerDrcEnabled);
Eric Laurente552edb2014-03-10 17:42:56 -07003037
3038 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003039 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3040 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003041 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003042 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003043 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003044 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003045 continue;
3046 }
3047 // open all output streams needed to access attached devices
3048 // except for direct output streams that are only opened when they are actually
3049 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003050 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003051 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3052 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003053 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003054
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003055 if (!outProfile->hasSupportedDevices()) {
3056 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003057 continue;
3058 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003059 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003060 mTtsOutputAvailable = true;
3061 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003062
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003063 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003064 continue;
3065 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003066 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003067 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3068 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003069 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003070 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003071 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003072 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003073 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003074 if ((profileType & outputDeviceTypes) == 0) {
3075 continue;
3076 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003077 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3078 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003079
3080 outputDesc->mDevice = profileType;
3081 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3082 config.sample_rate = outputDesc->mSamplingRate;
3083 config.channel_mask = outputDesc->mChannelMask;
3084 config.format = outputDesc->mFormat;
3085 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003086 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003087 &output,
3088 &config,
3089 &outputDesc->mDevice,
3090 String8(""),
3091 &outputDesc->mLatency,
3092 outputDesc->mFlags);
3093
3094 if (status != NO_ERROR) {
3095 ALOGW("Cannot open output stream for device %08x on hw module %s",
3096 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003097 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003098 } else {
3099 outputDesc->mSamplingRate = config.sample_rate;
3100 outputDesc->mChannelMask = config.channel_mask;
3101 outputDesc->mFormat = config.format;
3102
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003103 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3104 for (size_t k = 0; k < supportedDevices.size(); k++) {
3105 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003106 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003107 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3108 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003109 }
3110 }
3111 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003112 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003113 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003114 }
3115 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003116 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003117 outputDesc->mDevice,
3118 true);
3119 }
Eric Laurente552edb2014-03-10 17:42:56 -07003120 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003121 // open input streams needed to access attached devices to validate
3122 // mAvailableInputDevices list
3123 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3124 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003125 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003126
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003127 if (!inProfile->hasSupportedDevices()) {
3128 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003129 continue;
3130 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003131 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003132 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003133 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3134
Eric Laurentd78f1532014-09-16 16:38:20 -07003135 if ((profileType & inputDeviceTypes) == 0) {
3136 continue;
3137 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003138 sp<AudioInputDescriptor> inputDesc =
3139 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003140
Eric Laurentd78f1532014-09-16 16:38:20 -07003141 inputDesc->mDevice = profileType;
3142
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003143 // find the address
3144 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3145 // the inputs vector must be of size 1, but we don't want to crash here
3146 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3147 : String8("");
3148 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3149 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3150
Eric Laurentd78f1532014-09-16 16:38:20 -07003151 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3152 config.sample_rate = inputDesc->mSamplingRate;
3153 config.channel_mask = inputDesc->mChannelMask;
3154 config.format = inputDesc->mFormat;
3155 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003156 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003157 &input,
3158 &config,
3159 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003160 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003161 AUDIO_SOURCE_MIC,
3162 AUDIO_INPUT_FLAG_NONE);
3163
3164 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003165 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3166 for (size_t k = 0; k < supportedDevices.size(); k++) {
3167 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003168 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003169 if (index >= 0) {
3170 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3171 if (!devDesc->isAttached()) {
3172 devDesc->attach(mHwModules[i]);
3173 devDesc->importAudioPort(inProfile);
3174 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003175 }
3176 }
3177 mpClientInterface->closeInput(input);
3178 } else {
3179 ALOGW("Cannot open input stream for device %08x on hw module %s",
3180 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003181 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003182 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003183 }
3184 }
3185 // make sure all attached devices have been allocated a unique ID
3186 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003187 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003188 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003189 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3190 continue;
3191 }
François Gaffie2110e042015-03-24 08:41:51 +01003192 // The device is now validated and can be appended to the available devices of the engine
3193 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3194 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003195 i++;
3196 }
3197 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003198 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003199 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003200 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3201 continue;
3202 }
François Gaffie2110e042015-03-24 08:41:51 +01003203 // The device is now validated and can be appended to the available devices of the engine
3204 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3205 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003206 i++;
3207 }
3208 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003209 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003210 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003211 }
Eric Laurente552edb2014-03-10 17:42:56 -07003212
3213 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3214
3215 updateDevicesAndOutputs();
3216
3217#ifdef AUDIO_POLICY_TEST
3218 if (mPrimaryOutput != 0) {
3219 AudioParameter outputCmd = AudioParameter();
3220 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003221 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003222
3223 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3224 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003225 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3226 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003227 mTestLatencyMs = 0;
3228 mCurOutput = 0;
3229 mDirectOutput = false;
3230 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3231 mTestOutputs[i] = 0;
3232 }
3233
3234 const size_t SIZE = 256;
3235 char buffer[SIZE];
3236 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3237 run(buffer, ANDROID_PRIORITY_AUDIO);
3238 }
3239#endif //AUDIO_POLICY_TEST
3240}
3241
Eric Laurente0720872014-03-11 09:30:41 -07003242AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003243{
3244#ifdef AUDIO_POLICY_TEST
3245 exit();
3246#endif //AUDIO_POLICY_TEST
3247 for (size_t i = 0; i < mOutputs.size(); i++) {
3248 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003249 }
3250 for (size_t i = 0; i < mInputs.size(); i++) {
3251 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003252 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003253 mAvailableOutputDevices.clear();
3254 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003255 mOutputs.clear();
3256 mInputs.clear();
3257 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003258}
3259
Eric Laurente0720872014-03-11 09:30:41 -07003260status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003261{
Eric Laurent87ffa392015-05-22 10:32:38 -07003262 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003263}
3264
3265#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003266bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003267{
3268 ALOGV("entering threadLoop()");
3269 while (!exitPending())
3270 {
3271 String8 command;
3272 int valueInt;
3273 String8 value;
3274
3275 Mutex::Autolock _l(mLock);
3276 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3277
3278 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3279 AudioParameter param = AudioParameter(command);
3280
3281 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3282 valueInt != 0) {
3283 ALOGV("Test command %s received", command.string());
3284 String8 target;
3285 if (param.get(String8("target"), target) != NO_ERROR) {
3286 target = "Manager";
3287 }
3288 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3289 param.remove(String8("test_cmd_policy_output"));
3290 mCurOutput = valueInt;
3291 }
3292 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3293 param.remove(String8("test_cmd_policy_direct"));
3294 if (value == "false") {
3295 mDirectOutput = false;
3296 } else if (value == "true") {
3297 mDirectOutput = true;
3298 }
3299 }
3300 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3301 param.remove(String8("test_cmd_policy_input"));
3302 mTestInput = valueInt;
3303 }
3304
3305 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3306 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003307 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003308 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003309 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003310 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003311 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003312 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003313 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003314 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003315 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003316 if (target == "Manager") {
3317 mTestFormat = format;
3318 } else if (mTestOutputs[mCurOutput] != 0) {
3319 AudioParameter outputParam = AudioParameter();
3320 outputParam.addInt(String8("format"), format);
3321 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3322 }
3323 }
3324 }
3325 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3326 param.remove(String8("test_cmd_policy_channels"));
3327 int channels = 0;
3328
3329 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003330 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003331 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003332 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003333 }
3334 if (channels != 0) {
3335 if (target == "Manager") {
3336 mTestChannels = channels;
3337 } else if (mTestOutputs[mCurOutput] != 0) {
3338 AudioParameter outputParam = AudioParameter();
3339 outputParam.addInt(String8("channels"), channels);
3340 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3341 }
3342 }
3343 }
3344 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3345 param.remove(String8("test_cmd_policy_sampleRate"));
3346 if (valueInt >= 0 && valueInt <= 96000) {
3347 int samplingRate = valueInt;
3348 if (target == "Manager") {
3349 mTestSamplingRate = samplingRate;
3350 } else if (mTestOutputs[mCurOutput] != 0) {
3351 AudioParameter outputParam = AudioParameter();
3352 outputParam.addInt(String8("sampling_rate"), samplingRate);
3353 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3354 }
3355 }
3356 }
3357
3358 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3359 param.remove(String8("test_cmd_policy_reopen"));
3360
Eric Laurentc75307b2015-03-17 15:29:32 -07003361 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003362
Eric Laurentc75307b2015-03-17 15:29:32 -07003363 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003364
Eric Laurentc75307b2015-03-17 15:29:32 -07003365 removeOutput(mPrimaryOutput->mIoHandle);
3366 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3367 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003368 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003369 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3370 config.sample_rate = outputDesc->mSamplingRate;
3371 config.channel_mask = outputDesc->mChannelMask;
3372 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003373 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003374 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003375 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003376 &config,
3377 &outputDesc->mDevice,
3378 String8(""),
3379 &outputDesc->mLatency,
3380 outputDesc->mFlags);
3381 if (status != NO_ERROR) {
3382 ALOGE("Failed to reopen hardware output stream, "
3383 "samplingRate: %d, format %d, channels %d",
3384 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003385 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003386 outputDesc->mSamplingRate = config.sample_rate;
3387 outputDesc->mChannelMask = config.channel_mask;
3388 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003389 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003390 AudioParameter outputCmd = AudioParameter();
3391 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003392 mpClientInterface->setParameters(handle, outputCmd.toString());
3393 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003394 }
3395 }
3396
3397
3398 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3399 }
3400 }
3401 return false;
3402}
3403
Eric Laurente0720872014-03-11 09:30:41 -07003404void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003405{
3406 {
3407 AutoMutex _l(mLock);
3408 requestExit();
3409 mWaitWorkCV.signal();
3410 }
3411 requestExitAndWait();
3412}
3413
Eric Laurente0720872014-03-11 09:30:41 -07003414int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003415{
3416 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3417 if (output == mTestOutputs[i]) return i;
3418 }
3419 return 0;
3420}
3421#endif //AUDIO_POLICY_TEST
3422
3423// ---
3424
Eric Laurentc75307b2015-03-17 15:29:32 -07003425void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003426{
François Gaffie98cc1912015-03-18 17:52:40 +01003427 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003428 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003429 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003430 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003431}
3432
François Gaffie53615e22015-03-19 09:24:12 +01003433void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3434{
3435 mOutputs.removeItem(output);
3436}
3437
Eric Laurent1f2f2232014-06-02 12:01:23 -07003438void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003439{
François Gaffie98cc1912015-03-18 17:52:40 +01003440 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003441 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003442 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003443}
Eric Laurente552edb2014-03-10 17:42:56 -07003444
Eric Laurentc75307b2015-03-17 15:29:32 -07003445void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003446 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003447 const String8 address /*in*/,
3448 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003449 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003450 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003451 if (devDesc != 0) {
3452 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3453 desc->mIoHandle, address.string());
3454 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003455 }
3456}
3457
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003458status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003459 audio_policy_dev_state_t state,
3460 SortedVector<audio_io_handle_t>& outputs,
3461 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003462{
François Gaffie53615e22015-03-19 09:24:12 +01003463 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003464 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003465
3466 if (audio_device_is_digital(device)) {
3467 // erase all current sample rates, formats and channel masks
3468 devDesc->clearCapabilities();
3469 }
Eric Laurente552edb2014-03-10 17:42:56 -07003470
Eric Laurent3b73df72014-03-11 09:06:29 -07003471 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003472 // first list already open outputs that can be routed to this device
3473 for (size_t i = 0; i < mOutputs.size(); i++) {
3474 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003475 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003476 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003477 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3478 outputs.add(mOutputs.keyAt(i));
3479 } else {
3480 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003481 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003482 }
Eric Laurente552edb2014-03-10 17:42:56 -07003483 }
3484 }
3485 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003486 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003487 for (size_t i = 0; i < mHwModules.size(); i++)
3488 {
3489 if (mHwModules[i]->mHandle == 0) {
3490 continue;
3491 }
3492 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3493 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003494 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003495 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003496 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003497 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003498 profiles.add(profile);
3499 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3500 }
Eric Laurente552edb2014-03-10 17:42:56 -07003501 }
3502 }
3503 }
3504
Eric Laurent7b279bb2015-12-14 10:18:23 -08003505 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003506
Eric Laurente552edb2014-03-10 17:42:56 -07003507 if (profiles.isEmpty() && outputs.isEmpty()) {
3508 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3509 return BAD_VALUE;
3510 }
3511
3512 // open outputs for matching profiles if needed. Direct outputs are also opened to
3513 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3514 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003515 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003516
3517 // nothing to do if one output is already opened for this profile
3518 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003519 for (j = 0; j < outputs.size(); j++) {
3520 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003521 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003522 // matching profile: save the sample rates, format and channel masks supported
3523 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003524 if (audio_device_is_digital(device)) {
3525 devDesc->importAudioPort(profile);
3526 }
Eric Laurente552edb2014-03-10 17:42:56 -07003527 break;
3528 }
3529 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003530 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003531 continue;
3532 }
3533
Eric Laurent83b88082014-06-20 18:31:16 -07003534 ALOGV("opening output for device %08x with params %s profile %p",
3535 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003536 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003537 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003538 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3539 config.sample_rate = desc->mSamplingRate;
3540 config.channel_mask = desc->mChannelMask;
3541 config.format = desc->mFormat;
3542 config.offload_info.sample_rate = desc->mSamplingRate;
3543 config.offload_info.channel_mask = desc->mChannelMask;
3544 config.offload_info.format = desc->mFormat;
3545 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003546 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003547 &output,
3548 &config,
3549 &desc->mDevice,
3550 address,
3551 &desc->mLatency,
3552 desc->mFlags);
3553 if (status == NO_ERROR) {
3554 desc->mSamplingRate = config.sample_rate;
3555 desc->mChannelMask = config.channel_mask;
3556 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003557
Eric Laurentd4692962014-05-05 18:13:44 -07003558 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003559 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003560 char *param = audio_device_address_to_parameter(device, address);
3561 mpClientInterface->setParameters(output, String8(param));
3562 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003563 }
François Gaffie112b0af2015-11-19 16:13:25 +01003564 updateAudioProfiles(output, profile->getAudioProfiles());
3565 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003566 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003567 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003568 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003569 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003570 mpClientInterface->closeOutput(output);
François Gaffie112b0af2015-11-19 16:13:25 +01003571 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003572 config.offload_info.sample_rate = config.sample_rate;
3573 config.offload_info.channel_mask = config.channel_mask;
3574 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003575 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003576 &output,
3577 &config,
3578 &desc->mDevice,
3579 address,
3580 &desc->mLatency,
3581 desc->mFlags);
3582 if (status == NO_ERROR) {
3583 desc->mSamplingRate = config.sample_rate;
3584 desc->mChannelMask = config.channel_mask;
3585 desc->mFormat = config.format;
3586 } else {
3587 output = AUDIO_IO_HANDLE_NONE;
3588 }
Eric Laurentd4692962014-05-05 18:13:44 -07003589 }
3590
Eric Laurentcf2c0212014-07-25 16:20:43 -07003591 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003592 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003593 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003594 sp<AudioPolicyMix> policyMix;
3595 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003596 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3597 address.string());
3598 }
François Gaffie036e1e92015-03-19 10:16:24 +01003599 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003600 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003601
Eric Laurent87ffa392015-05-22 10:32:38 -07003602 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3603 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003604 // no duplicated output for direct outputs and
3605 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003606 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003607
Eric Laurentd4692962014-05-05 18:13:44 -07003608 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003609 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003610
Eric Laurentd4692962014-05-05 18:13:44 -07003611 //TODO: configure audio effect output stage here
3612
3613 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003614 duplicatedOutput =
3615 mpClientInterface->openDuplicateOutput(output,
3616 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003617 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003618 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003619 sp<SwAudioOutputDescriptor> dupOutputDesc =
3620 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3621 dupOutputDesc->mOutput1 = mPrimaryOutput;
3622 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003623 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3624 dupOutputDesc->mFormat = desc->mFormat;
3625 dupOutputDesc->mChannelMask = desc->mChannelMask;
3626 dupOutputDesc->mLatency = desc->mLatency;
3627 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003628 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003629 } else {
3630 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003631 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003632 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003633 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003634 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003635 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003636 }
Eric Laurente552edb2014-03-10 17:42:56 -07003637 }
3638 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003639 } else {
3640 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003641 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003642 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003643 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003644 profiles.removeAt(profile_index);
3645 profile_index--;
3646 } else {
3647 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003648 // Load digital format info only for digital devices
3649 if (audio_device_is_digital(device)) {
3650 devDesc->importAudioPort(profile);
3651 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003652
François Gaffie53615e22015-03-19 09:24:12 +01003653 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003654 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3655 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003656 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003657 NULL/*patch handle*/, address.string());
3658 }
Eric Laurente552edb2014-03-10 17:42:56 -07003659 ALOGV("checkOutputsForDevice(): adding output %d", output);
3660 }
3661 }
3662
3663 if (profiles.isEmpty()) {
3664 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3665 return BAD_VALUE;
3666 }
Eric Laurentd4692962014-05-05 18:13:44 -07003667 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003668 // check if one opened output is not needed any more after disconnecting one device
3669 for (size_t i = 0; i < mOutputs.size(); i++) {
3670 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003671 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003672 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003673 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003674 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003675 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003676 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003677 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3678 mOutputs.keyAt(i));
3679 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003680 }
Eric Laurente552edb2014-03-10 17:42:56 -07003681 }
3682 }
Eric Laurentd4692962014-05-05 18:13:44 -07003683 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003684 for (size_t i = 0; i < mHwModules.size(); i++)
3685 {
3686 if (mHwModules[i]->mHandle == 0) {
3687 continue;
3688 }
3689 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3690 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003691 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003692 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003693 ALOGV("checkOutputsForDevice(): "
3694 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003695 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003696 }
3697 }
3698 }
3699 }
3700 return NO_ERROR;
3701}
3702
Paul McLean9080a4c2015-06-18 08:24:02 -07003703status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003704 audio_policy_dev_state_t state,
3705 SortedVector<audio_io_handle_t>& inputs,
3706 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003707{
Paul McLean9080a4c2015-06-18 08:24:02 -07003708 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003709 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003710
3711 if (audio_device_is_digital(device)) {
3712 // erase all current sample rates, formats and channel masks
3713 devDesc->clearCapabilities();
3714 }
3715
Eric Laurentd4692962014-05-05 18:13:44 -07003716 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3717 // first list already open inputs that can be routed to this device
3718 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3719 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003720 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003721 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3722 inputs.add(mInputs.keyAt(input_index));
3723 }
3724 }
3725
3726 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003727 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003728 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3729 {
3730 if (mHwModules[module_idx]->mHandle == 0) {
3731 continue;
3732 }
3733 for (size_t profile_index = 0;
3734 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3735 profile_index++)
3736 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003737 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3738
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003739 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003740 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003741 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003742 profiles.add(profile);
3743 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3744 profile_index, module_idx);
3745 }
Eric Laurentd4692962014-05-05 18:13:44 -07003746 }
3747 }
3748 }
3749
3750 if (profiles.isEmpty() && inputs.isEmpty()) {
3751 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3752 return BAD_VALUE;
3753 }
3754
3755 // open inputs for matching profiles if needed. Direct inputs are also opened to
3756 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3757 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3758
Eric Laurent1c333e22014-05-20 10:48:17 -07003759 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003760 // nothing to do if one input is already opened for this profile
3761 size_t input_index;
3762 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3763 desc = mInputs.valueAt(input_index);
3764 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003765 if (audio_device_is_digital(device)) {
3766 devDesc->importAudioPort(profile);
3767 }
Eric Laurentd4692962014-05-05 18:13:44 -07003768 break;
3769 }
3770 }
3771 if (input_index != mInputs.size()) {
3772 continue;
3773 }
3774
3775 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3776 desc = new AudioInputDescriptor(profile);
3777 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003778 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3779 config.sample_rate = desc->mSamplingRate;
3780 config.channel_mask = desc->mChannelMask;
3781 config.format = desc->mFormat;
3782 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003783 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003784 &input,
3785 &config,
3786 &desc->mDevice,
3787 address,
3788 AUDIO_SOURCE_MIC,
3789 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003790
Eric Laurentcf2c0212014-07-25 16:20:43 -07003791 if (status == NO_ERROR) {
3792 desc->mSamplingRate = config.sample_rate;
3793 desc->mChannelMask = config.channel_mask;
3794 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003795
Eric Laurentd4692962014-05-05 18:13:44 -07003796 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003797 char *param = audio_device_address_to_parameter(device, address);
3798 mpClientInterface->setParameters(input, String8(param));
3799 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003800 }
François Gaffie112b0af2015-11-19 16:13:25 +01003801 updateAudioProfiles(input, profile->getAudioProfiles());
3802 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003803 ALOGW("checkInputsForDevice() direct input missing param");
3804 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003805 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003806 }
3807
3808 if (input != 0) {
3809 addInput(input, desc);
3810 }
3811 } // endif input != 0
3812
Eric Laurentcf2c0212014-07-25 16:20:43 -07003813 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003814 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003815 profiles.removeAt(profile_index);
3816 profile_index--;
3817 } else {
3818 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003819 if (audio_device_is_digital(device)) {
3820 devDesc->importAudioPort(profile);
3821 }
Eric Laurentd4692962014-05-05 18:13:44 -07003822 ALOGV("checkInputsForDevice(): adding input %d", input);
3823 }
3824 } // end scan profiles
3825
3826 if (profiles.isEmpty()) {
3827 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3828 return BAD_VALUE;
3829 }
3830 } else {
3831 // Disconnect
3832 // check if one opened input is not needed any more after disconnecting one device
3833 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3834 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003835 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003836 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3837 mInputs.keyAt(input_index));
3838 inputs.add(mInputs.keyAt(input_index));
3839 }
3840 }
3841 // Clear any profiles associated with the disconnected device.
3842 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3843 if (mHwModules[module_index]->mHandle == 0) {
3844 continue;
3845 }
3846 for (size_t profile_index = 0;
3847 profile_index < mHwModules[module_index]->mInputProfiles.size();
3848 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003849 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003850 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003851 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003852 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01003853 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07003854 }
3855 }
3856 }
3857 } // end disconnect
3858
3859 return NO_ERROR;
3860}
3861
3862
Eric Laurente0720872014-03-11 09:30:41 -07003863void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003864{
3865 ALOGV("closeOutput(%d)", output);
3866
Eric Laurentc75307b2015-03-17 15:29:32 -07003867 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003868 if (outputDesc == NULL) {
3869 ALOGW("closeOutput() unknown output %d", output);
3870 return;
3871 }
François Gaffie036e1e92015-03-19 10:16:24 +01003872 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003873
Eric Laurente552edb2014-03-10 17:42:56 -07003874 // look for duplicated outputs connected to the output being removed.
3875 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003876 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003877 if (dupOutputDesc->isDuplicated() &&
3878 (dupOutputDesc->mOutput1 == outputDesc ||
3879 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003880 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003881 if (dupOutputDesc->mOutput1 == outputDesc) {
3882 outputDesc2 = dupOutputDesc->mOutput2;
3883 } else {
3884 outputDesc2 = dupOutputDesc->mOutput1;
3885 }
3886 // As all active tracks on duplicated output will be deleted,
3887 // and as they were also referenced on the other output, the reference
3888 // count for their stream type must be adjusted accordingly on
3889 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003890 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003891 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003892 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003893 }
3894 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3895 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3896
3897 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01003898 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003899 }
3900 }
3901
Eric Laurent05b90f82014-08-27 15:32:29 -07003902 nextAudioPortGeneration();
3903
3904 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3905 if (index >= 0) {
3906 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3907 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3908 mAudioPatches.removeItemsAt(index);
3909 mpClientInterface->onAudioPatchListUpdate();
3910 }
3911
Eric Laurente552edb2014-03-10 17:42:56 -07003912 AudioParameter param;
3913 param.add(String8("closing"), String8("true"));
3914 mpClientInterface->setParameters(output, param.toString());
3915
3916 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003917 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003918 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003919}
3920
3921void AudioPolicyManager::closeInput(audio_io_handle_t input)
3922{
3923 ALOGV("closeInput(%d)", input);
3924
3925 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3926 if (inputDesc == NULL) {
3927 ALOGW("closeInput() unknown input %d", input);
3928 return;
3929 }
3930
Eric Laurent6a94d692014-05-20 11:18:06 -07003931 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003932
3933 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3934 if (index >= 0) {
3935 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3936 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3937 mAudioPatches.removeItemsAt(index);
3938 mpClientInterface->onAudioPatchListUpdate();
3939 }
3940
3941 mpClientInterface->closeInput(input);
3942 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003943}
3944
Eric Laurentc75307b2015-03-17 15:29:32 -07003945SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
3946 audio_devices_t device,
3947 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003948{
3949 SortedVector<audio_io_handle_t> outputs;
3950
3951 ALOGVV("getOutputsForDevice() device %04x", device);
3952 for (size_t i = 0; i < openOutputs.size(); i++) {
3953 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003954 i, openOutputs.valueAt(i)->isDuplicated(),
3955 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07003956 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3957 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3958 outputs.add(openOutputs.keyAt(i));
3959 }
3960 }
3961 return outputs;
3962}
3963
Eric Laurente0720872014-03-11 09:30:41 -07003964bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01003965 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07003966{
3967 if (outputs1.size() != outputs2.size()) {
3968 return false;
3969 }
3970 for (size_t i = 0; i < outputs1.size(); i++) {
3971 if (outputs1[i] != outputs2[i]) {
3972 return false;
3973 }
3974 }
3975 return true;
3976}
3977
Eric Laurente0720872014-03-11 09:30:41 -07003978void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003979{
3980 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3981 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3982 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3983 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3984
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003985 // also take into account external policy-related changes: add all outputs which are
3986 // associated with policies in the "before" and "after" output vectors
3987 ALOGVV("checkOutputForStrategy(): policy related outputs");
3988 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003989 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003990 if (desc != 0 && desc->mPolicyMix != NULL) {
3991 srcOutputs.add(desc->mIoHandle);
3992 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
3993 }
3994 }
3995 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003996 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003997 if (desc != 0 && desc->mPolicyMix != NULL) {
3998 dstOutputs.add(desc->mIoHandle);
3999 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4000 }
4001 }
4002
Eric Laurente552edb2014-03-10 17:42:56 -07004003 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4004 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4005 strategy, srcOutputs[0], dstOutputs[0]);
4006 // mute strategy while moving tracks from one output to another
4007 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004008 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004009 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004010 setStrategyMute(strategy, true, desc);
4011 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004012 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004013 sp<AudioSourceDescriptor> source =
4014 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4015 if (source != 0){
4016 connectAudioSource(source);
4017 }
Eric Laurente552edb2014-03-10 17:42:56 -07004018 }
4019
4020 // Move effects associated to this strategy from previous output to new output
4021 if (strategy == STRATEGY_MEDIA) {
4022 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4023 SortedVector<audio_io_handle_t> moved;
4024 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004025 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4026 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4027 effectDesc->mIo != fxOutput) {
4028 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004029 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4030 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004031 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004032 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004033 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004034 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004035 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004036 }
4037 }
4038 }
4039 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004040 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004041 if (i == AUDIO_STREAM_PATCH) {
4042 continue;
4043 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004044 if (getStrategy((audio_stream_type_t)i) == strategy) {
4045 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004046 }
4047 }
4048 }
4049}
4050
Eric Laurente0720872014-03-11 09:30:41 -07004051void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004052{
François Gaffie2110e042015-03-24 08:41:51 +01004053 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004054 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004055 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004056 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004057 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004058 checkOutputForStrategy(STRATEGY_SONIFICATION);
4059 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004060 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004061 checkOutputForStrategy(STRATEGY_MEDIA);
4062 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004063 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004064}
4065
Eric Laurente0720872014-03-11 09:30:41 -07004066void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004067{
François Gaffie53615e22015-03-19 09:24:12 +01004068 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004069 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004071 return;
4072 }
4073
Eric Laurent3a4311c2014-03-17 12:00:47 -07004074 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004075 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4076 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4077 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004078 // suspend A2DP output if:
4079 // (NOT already suspended) &&
4080 // ((SCO device is connected &&
4081 // (forced usage for communication || for record is SCO))) ||
4082 // (phone state is ringing || in call)
4083 //
4084 // restore A2DP output if:
4085 // (Already suspended) &&
4086 // ((SCO device is NOT connected ||
4087 // (forced usage NOT for communication && NOT for record is SCO))) &&
4088 // (phone state is NOT ringing && NOT in call)
4089 //
4090 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004092 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4093 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4094 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4095 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004096
4097 mpClientInterface->restoreOutput(a2dpOutput);
4098 mA2dpSuspended = false;
4099 }
4100 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004101 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004102 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4103 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4104 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4105 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004106
4107 mpClientInterface->suspendOutput(a2dpOutput);
4108 mA2dpSuspended = true;
4109 }
4110 }
4111}
4112
Eric Laurentc75307b2015-03-17 15:29:32 -07004113audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4114 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004115{
4116 audio_devices_t device = AUDIO_DEVICE_NONE;
4117
Eric Laurent6a94d692014-05-20 11:18:06 -07004118 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4119 if (index >= 0) {
4120 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4121 if (patchDesc->mUid != mUidCached) {
4122 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4123 outputDesc->device(), outputDesc->mPatchHandle);
4124 return outputDesc->device();
4125 }
4126 }
4127
Eric Laurente552edb2014-03-10 17:42:56 -07004128 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004129 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004130 // use device for strategy enforced audible
4131 // 2: we are in call or the strategy phone is active on the output:
4132 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004133 // 3: the strategy for enforced audible is active but not enforced on the output:
4134 // use the device for strategy enforced audible
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004135 // 4: the strategy accessibility is active on the output:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004136 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004137 // 5: the strategy sonification is active on the output:
4138 // use device for strategy sonification
4139 // 6: the strategy "respectful" sonification is active on the output:
4140 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004141 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004142 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004143 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004144 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004145 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004146 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004147 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004148 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004149 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4150 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004151 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004152 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004153 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004154 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004155 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4156 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004157 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004158 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004159 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004160 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004161 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004162 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004163 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004164 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004165 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004166 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004167 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004168 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004169 }
4170
Eric Laurent1c333e22014-05-20 10:48:17 -07004171 ALOGV("getNewOutputDevice() selected device %x", device);
4172 return device;
4173}
4174
4175audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4176{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004177 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004178
4179 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4180 if (index >= 0) {
4181 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4182 if (patchDesc->mUid != mUidCached) {
4183 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4184 inputDesc->mDevice, inputDesc->mPatchHandle);
4185 return inputDesc->mDevice;
4186 }
4187 }
4188
Eric Laurent599c7582015-12-07 18:05:55 -08004189 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004190
Eric Laurente552edb2014-03-10 17:42:56 -07004191 return device;
4192}
4193
Eric Laurente0720872014-03-11 09:30:41 -07004194uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004195 return (uint32_t)getStrategy(stream);
4196}
4197
Eric Laurente0720872014-03-11 09:30:41 -07004198audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004199 // By checking the range of stream before calling getStrategy, we avoid
4200 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4201 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004202 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004203 return AUDIO_DEVICE_NONE;
4204 }
4205 audio_devices_t devices;
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004206 routing_strategy strategy = getStrategy(stream);
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4208 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4209 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004210 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004211 if (isStrategyActive(outputDesc, strategy)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004212 devices = outputDesc->device();
4213 break;
4214 }
Eric Laurente552edb2014-03-10 17:42:56 -07004215 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004216
4217 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4218 and doesn't really need to.*/
4219 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4220 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4221 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4222 }
4223
Eric Laurente552edb2014-03-10 17:42:56 -07004224 return devices;
4225}
4226
François Gaffie2110e042015-03-24 08:41:51 +01004227routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4228{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004229 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004230 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004231}
4232
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004233uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4234 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004235 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4236 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4237 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004238 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4239 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4240 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004241 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004242 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004243}
4244
Eric Laurente0720872014-03-11 09:30:41 -07004245void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004246 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004247 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004248 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4249 updateDevicesAndOutputs();
4250 break;
4251 default:
4252 break;
4253 }
4254}
4255
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004256uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004257
4258 // skip beacon mute management if a dedicated TTS output is available
4259 if (mTtsOutputAvailable) {
4260 return 0;
4261 }
4262
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004263 switch(event) {
4264 case STARTING_OUTPUT:
4265 mBeaconMuteRefCount++;
4266 break;
4267 case STOPPING_OUTPUT:
4268 if (mBeaconMuteRefCount > 0) {
4269 mBeaconMuteRefCount--;
4270 }
4271 break;
4272 case STARTING_BEACON:
4273 mBeaconPlayingRefCount++;
4274 break;
4275 case STOPPING_BEACON:
4276 if (mBeaconPlayingRefCount > 0) {
4277 mBeaconPlayingRefCount--;
4278 }
4279 break;
4280 }
4281
4282 if (mBeaconMuteRefCount > 0) {
4283 // any playback causes beacon to be muted
4284 return setBeaconMute(true);
4285 } else {
4286 // no other playback: unmute when beacon starts playing, mute when it stops
4287 return setBeaconMute(mBeaconPlayingRefCount == 0);
4288 }
4289}
4290
4291uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4292 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4293 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4294 // keep track of muted state to avoid repeating mute/unmute operations
4295 if (mBeaconMuted != mute) {
4296 // mute/unmute AUDIO_STREAM_TTS on all outputs
4297 ALOGV("\t muting %d", mute);
4298 uint32_t maxLatency = 0;
4299 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004300 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004301 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004302 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004303 0 /*delay*/, AUDIO_DEVICE_NONE);
4304 const uint32_t latency = desc->latency() * 2;
4305 if (latency > maxLatency) {
4306 maxLatency = latency;
4307 }
4308 }
4309 mBeaconMuted = mute;
4310 return maxLatency;
4311 }
4312 return 0;
4313}
4314
Eric Laurente0720872014-03-11 09:30:41 -07004315audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004316 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004317{
Paul McLeanaa981192015-03-21 09:55:15 -07004318 // Routing
4319 // see if we have an explicit route
4320 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4321 // (getStrategy(stream)).
4322 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4323 // and activity count is non-zero
4324 // the device = the device from the descriptor in the RouteMap, and exit.
4325 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4326 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
4327 routing_strategy strat = getStrategy(route->mStreamType);
Eric Laurent093a20c2015-06-11 12:33:29 -07004328 // Special case for accessibility strategy which must follow any strategy it is
4329 // currently remapped to
4330 bool strategyMatch = (strat == strategy) ||
4331 ((strategy == STRATEGY_ACCESSIBILITY) &&
4332 ((mEngine->getStrategyForUsage(
4333 AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) == strat) ||
4334 (strat == STRATEGY_MEDIA)));
4335 if (strategyMatch && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004336 return route->mDeviceDescriptor->type();
4337 }
4338 }
4339
Eric Laurente552edb2014-03-10 17:42:56 -07004340 if (fromCache) {
4341 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4342 strategy, mDeviceForStrategy[strategy]);
4343 return mDeviceForStrategy[strategy];
4344 }
François Gaffie2110e042015-03-24 08:41:51 +01004345 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004346}
4347
Eric Laurente0720872014-03-11 09:30:41 -07004348void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004349{
4350 for (int i = 0; i < NUM_STRATEGIES; i++) {
4351 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4352 }
4353 mPreviousOutputs = mOutputs;
4354}
4355
Eric Laurent1f2f2232014-06-02 12:01:23 -07004356uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004357 audio_devices_t prevDevice,
4358 uint32_t delayMs)
4359{
4360 // mute/unmute strategies using an incompatible device combination
4361 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4362 // if unmuting, unmute only after the specified delay
4363 if (outputDesc->isDuplicated()) {
4364 return 0;
4365 }
4366
4367 uint32_t muteWaitMs = 0;
4368 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004369 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004370
4371 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4372 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004373 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004374 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4375 bool doMute = false;
4376
4377 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4378 doMute = true;
4379 outputDesc->mStrategyMutedByDevice[i] = true;
4380 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4381 doMute = true;
4382 outputDesc->mStrategyMutedByDevice[i] = false;
4383 }
Eric Laurent99401132014-05-07 19:48:15 -07004384 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004385 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004386 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004387 // skip output if it does not share any device with current output
4388 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4389 == AUDIO_DEVICE_NONE) {
4390 continue;
4391 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004392 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4393 mute ? "muting" : "unmuting", i, curDevice);
4394 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004395 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004396 if (mute) {
4397 // FIXME: should not need to double latency if volume could be applied
4398 // immediately by the audioflinger mixer. We must account for the delay
4399 // between now and the next time the audioflinger thread for this output
4400 // will process a buffer (which corresponds to one buffer size,
4401 // usually 1/2 or 1/4 of the latency).
4402 if (muteWaitMs < desc->latency() * 2) {
4403 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004404 }
4405 }
4406 }
4407 }
4408 }
4409 }
4410
Eric Laurent99401132014-05-07 19:48:15 -07004411 // temporary mute output if device selection changes to avoid volume bursts due to
4412 // different per device volumes
4413 if (outputDesc->isActive() && (device != prevDevice)) {
4414 if (muteWaitMs < outputDesc->latency() * 2) {
4415 muteWaitMs = outputDesc->latency() * 2;
4416 }
4417 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004418 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004419 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004420 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004421 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004422 muteWaitMs *2, device);
4423 }
4424 }
4425 }
4426
Eric Laurente552edb2014-03-10 17:42:56 -07004427 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4428 if (muteWaitMs > delayMs) {
4429 muteWaitMs -= delayMs;
4430 usleep(muteWaitMs * 1000);
4431 return muteWaitMs;
4432 }
4433 return 0;
4434}
4435
Eric Laurentc75307b2015-03-17 15:29:32 -07004436uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004437 audio_devices_t device,
4438 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004439 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004440 audio_patch_handle_t *patchHandle,
4441 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004442{
Eric Laurentc75307b2015-03-17 15:29:32 -07004443 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004444 AudioParameter param;
4445 uint32_t muteWaitMs;
4446
4447 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004448 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4449 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004450 return muteWaitMs;
4451 }
4452 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4453 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004454 if ((device != AUDIO_DEVICE_NONE) &&
4455 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004456 return 0;
4457 }
4458
4459 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004460 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004461
4462 audio_devices_t prevDevice = outputDesc->mDevice;
4463
Paul McLeanaa981192015-03-21 09:55:15 -07004464 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004465
4466 if (device != AUDIO_DEVICE_NONE) {
4467 outputDesc->mDevice = device;
4468 }
4469 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4470
4471 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004472 // the requested device is AUDIO_DEVICE_NONE
4473 // OR the requested device is the same as current device
4474 // AND force is not specified
4475 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004476 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004477 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4478 !force &&
4479 outputDesc->mPatchHandle != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004480 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004481 return muteWaitMs;
4482 }
4483
4484 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004485
Eric Laurente552edb2014-03-10 17:42:56 -07004486 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004487 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004488 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004489 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004490 DeviceVector deviceList = (address == NULL) ?
4491 mAvailableOutputDevices.getDevicesFromType(device)
4492 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004493 if (!deviceList.isEmpty()) {
4494 struct audio_patch patch;
4495 outputDesc->toAudioPortConfig(&patch.sources[0]);
4496 patch.num_sources = 1;
4497 patch.num_sinks = 0;
4498 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4499 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004500 patch.num_sinks++;
4501 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004502 ssize_t index;
4503 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4504 index = mAudioPatches.indexOfKey(*patchHandle);
4505 } else {
4506 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4507 }
4508 sp< AudioPatch> patchDesc;
4509 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4510 if (index >= 0) {
4511 patchDesc = mAudioPatches.valueAt(index);
4512 afPatchHandle = patchDesc->mAfPatchHandle;
4513 }
4514
Eric Laurent1c333e22014-05-20 10:48:17 -07004515 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004516 &afPatchHandle,
4517 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004518 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4519 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004520 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004521 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004522 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004523 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004524 addAudioPatch(patchDesc->mHandle, patchDesc);
4525 } else {
4526 patchDesc->mPatch = patch;
4527 }
4528 patchDesc->mAfPatchHandle = afPatchHandle;
4529 patchDesc->mUid = mUidCached;
4530 if (patchHandle) {
4531 *patchHandle = patchDesc->mHandle;
4532 }
4533 outputDesc->mPatchHandle = patchDesc->mHandle;
4534 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004535 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004536 }
4537 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004538
4539 // inform all input as well
4540 for (size_t i = 0; i < mInputs.size(); i++) {
4541 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004542 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004543 AudioParameter inputCmd = AudioParameter();
4544 ALOGV("%s: inform input %d of device:%d", __func__,
4545 inputDescriptor->mIoHandle, device);
4546 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4547 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4548 inputCmd.toString(),
4549 delayMs);
4550 }
4551 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004552 }
Eric Laurente552edb2014-03-10 17:42:56 -07004553
4554 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004555 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004556
4557 return muteWaitMs;
4558}
4559
Eric Laurentc75307b2015-03-17 15:29:32 -07004560status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004561 int delayMs,
4562 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004563{
Eric Laurent6a94d692014-05-20 11:18:06 -07004564 ssize_t index;
4565 if (patchHandle) {
4566 index = mAudioPatches.indexOfKey(*patchHandle);
4567 } else {
4568 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4569 }
4570 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004571 return INVALID_OPERATION;
4572 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004573 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4574 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004575 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4576 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004577 removeAudioPatch(patchDesc->mHandle);
4578 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004579 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004580 return status;
4581}
4582
4583status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4584 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004585 bool force,
4586 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004587{
4588 status_t status = NO_ERROR;
4589
Eric Laurent1f2f2232014-06-02 12:01:23 -07004590 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004591 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4592 inputDesc->mDevice = device;
4593
4594 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4595 if (!deviceList.isEmpty()) {
4596 struct audio_patch patch;
4597 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004598 // AUDIO_SOURCE_HOTWORD is for internal use only:
4599 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004600 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004601 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004602 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4603 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004604 patch.num_sinks = 1;
4605 //only one input device for now
4606 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004607 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004608 ssize_t index;
4609 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4610 index = mAudioPatches.indexOfKey(*patchHandle);
4611 } else {
4612 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4613 }
4614 sp< AudioPatch> patchDesc;
4615 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4616 if (index >= 0) {
4617 patchDesc = mAudioPatches.valueAt(index);
4618 afPatchHandle = patchDesc->mAfPatchHandle;
4619 }
4620
Eric Laurent1c333e22014-05-20 10:48:17 -07004621 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004622 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004623 0);
4624 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004625 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004626 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004627 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004628 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004629 addAudioPatch(patchDesc->mHandle, patchDesc);
4630 } else {
4631 patchDesc->mPatch = patch;
4632 }
4633 patchDesc->mAfPatchHandle = afPatchHandle;
4634 patchDesc->mUid = mUidCached;
4635 if (patchHandle) {
4636 *patchHandle = patchDesc->mHandle;
4637 }
4638 inputDesc->mPatchHandle = patchDesc->mHandle;
4639 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004640 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004641 }
4642 }
4643 }
4644 return status;
4645}
4646
Eric Laurent6a94d692014-05-20 11:18:06 -07004647status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4648 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004649{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004650 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004651 ssize_t index;
4652 if (patchHandle) {
4653 index = mAudioPatches.indexOfKey(*patchHandle);
4654 } else {
4655 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4656 }
4657 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004658 return INVALID_OPERATION;
4659 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004660 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4661 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004662 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4663 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004664 removeAudioPatch(patchDesc->mHandle);
4665 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004666 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004667 return status;
4668}
4669
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004670sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004671 String8 address,
4672 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004673 audio_format_t& format,
4674 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004675 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004676{
4677 // Choose an input profile based on the requested capture parameters: select the first available
4678 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004679 //
4680 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4681 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004682
4683 for (size_t i = 0; i < mHwModules.size(); i++)
4684 {
4685 if (mHwModules[i]->mHandle == 0) {
4686 continue;
4687 }
4688 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4689 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004690 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004691 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004692 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004693 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004694 format,
4695 &format /*updatedFormat*/,
4696 channelMask,
4697 &channelMask /*updatedChannelMask*/,
4698 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004699
Eric Laurente552edb2014-03-10 17:42:56 -07004700 return profile;
4701 }
4702 }
4703 }
4704 return NULL;
4705}
4706
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004707
4708audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004709 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004710{
François Gaffie036e1e92015-03-19 10:16:24 +01004711 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4712 audio_devices_t selectedDeviceFromMix =
4713 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004714
François Gaffie036e1e92015-03-19 10:16:24 +01004715 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4716 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004717 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004718 return getDeviceForInputSource(inputSource);
4719}
4720
4721audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4722{
Paul McLean466dc8e2015-04-17 13:15:36 -06004723 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4724 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004725 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004726 return route->mDeviceDescriptor->type();
4727 }
4728 }
4729
4730 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004731}
4732
Eric Laurente0720872014-03-11 09:30:41 -07004733float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004734 int index,
4735 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004736{
Eric Laurentffbc80f2015-03-18 18:30:19 -07004737 float volumeDb = mEngine->volIndexToDb(Volume::getDeviceCategory(device), stream, index);
Eric Laurente552edb2014-03-10 17:42:56 -07004738
4739 // if a headset is connected, apply the following rules to ring tones and notifications
4740 // to avoid sound level bursts in user's ears:
4741 // - always attenuate ring tones and notifications volume by 6dB
4742 // - if music is playing, always limit the volume to current music volume,
4743 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004744 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004745 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4746 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4747 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4748 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4749 ((stream_strategy == STRATEGY_SONIFICATION)
4750 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004751 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004752 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004753 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
4754 mStreams.canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004755 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004756 // when the phone is ringing we must consider that music could have been paused just before
4757 // by the music application and behave as if music was active if the last music track was
4758 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004759 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004760 mLimitRingtoneVolume) {
4761 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004762 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
4763 mStreams.valueFor(AUDIO_STREAM_MUSIC).getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004764 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004765 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4766 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4767 if (volumeDb > minVolDB) {
4768 volumeDb = minVolDB;
4769 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004770 }
4771 }
4772 }
4773
Eric Laurentffbc80f2015-03-18 18:30:19 -07004774 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004775}
4776
Eric Laurente0720872014-03-11 09:30:41 -07004777status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004778 int index,
4779 const sp<AudioOutputDescriptor>& outputDesc,
4780 audio_devices_t device,
4781 int delayMs,
4782 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004783{
Eric Laurente552edb2014-03-10 17:42:56 -07004784 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004785 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004786 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004787 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004788 return NO_ERROR;
4789 }
François Gaffie2110e042015-03-24 08:41:51 +01004790 audio_policy_forced_cfg_t forceUseForComm =
4791 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004792 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004793 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4794 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004795 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004796 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004797 return INVALID_OPERATION;
4798 }
4799
Eric Laurentc75307b2015-03-17 15:29:32 -07004800 if (device == AUDIO_DEVICE_NONE) {
4801 device = outputDesc->device();
4802 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004803
Eric Laurentffbc80f2015-03-18 18:30:19 -07004804 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004805 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004806 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004807 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004808
Eric Laurentffbc80f2015-03-18 18:30:19 -07004809 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004810
Eric Laurent3b73df72014-03-11 09:06:29 -07004811 if (stream == AUDIO_STREAM_VOICE_CALL ||
4812 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004813 float voiceVolume;
4814 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004815 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004816 voiceVolume = (float)index/(float)mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07004817 } else {
4818 voiceVolume = 1.0;
4819 }
4820
Eric Laurentc75307b2015-03-17 15:29:32 -07004821 if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
Eric Laurente552edb2014-03-10 17:42:56 -07004822 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4823 mLastVoiceVolume = voiceVolume;
4824 }
4825 }
4826
4827 return NO_ERROR;
4828}
4829
Eric Laurentc75307b2015-03-17 15:29:32 -07004830void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4831 audio_devices_t device,
4832 int delayMs,
4833 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004834{
Eric Laurentc75307b2015-03-17 15:29:32 -07004835 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004836
Eric Laurent3b73df72014-03-11 09:06:29 -07004837 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004838 if (stream == AUDIO_STREAM_PATCH) {
4839 continue;
4840 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004841 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004842 mStreams.valueFor((audio_stream_type_t)stream).getVolumeIndex(device),
4843 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004844 device,
4845 delayMs,
4846 force);
4847 }
4848}
4849
Eric Laurente0720872014-03-11 09:30:41 -07004850void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07004851 bool on,
4852 const sp<AudioOutputDescriptor>& outputDesc,
4853 int delayMs,
4854 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004855{
Eric Laurent72249d52015-06-08 11:12:15 -07004856 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
4857 strategy, on, outputDesc->getId());
Eric Laurent3b73df72014-03-11 09:06:29 -07004858 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004859 if (stream == AUDIO_STREAM_PATCH) {
4860 continue;
4861 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004862 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004863 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004864 }
4865 }
4866}
4867
Eric Laurente0720872014-03-11 09:30:41 -07004868void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004869 bool on,
4870 const sp<AudioOutputDescriptor>& outputDesc,
4871 int delayMs,
4872 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004873{
Eric Laurentc75307b2015-03-17 15:29:32 -07004874 const StreamDescriptor& streamDesc = mStreams.valueFor(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004875 if (device == AUDIO_DEVICE_NONE) {
4876 device = outputDesc->device();
4877 }
4878
Eric Laurentc75307b2015-03-17 15:29:32 -07004879 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
4880 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07004881
4882 if (on) {
4883 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffiedfd74092015-03-19 12:10:59 +01004884 if (streamDesc.canBeMuted() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004885 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01004886 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004887 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004888 }
4889 }
4890 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4891 outputDesc->mMuteCount[stream]++;
4892 } else {
4893 if (outputDesc->mMuteCount[stream] == 0) {
4894 ALOGV("setStreamMute() unmuting non muted stream!");
4895 return;
4896 }
4897 if (--outputDesc->mMuteCount[stream] == 0) {
4898 checkAndSetVolume(stream,
4899 streamDesc.getVolumeIndex(device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004900 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004901 device,
4902 delayMs);
4903 }
4904 }
4905}
4906
Eric Laurente0720872014-03-11 09:30:41 -07004907void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004908 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004909{
Eric Laurent87ffa392015-05-22 10:32:38 -07004910 if(!hasPrimaryOutput()) {
4911 return;
4912 }
4913
Eric Laurente552edb2014-03-10 17:42:56 -07004914 // if the stream pertains to sonification strategy and we are in call we must
4915 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4916 // in the device used for phone strategy and play the tone if the selected device does not
4917 // interfere with the device used for phone strategy
4918 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4919 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004920 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004921 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4922 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004923 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004924 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4925 stream, starting, outputDesc->mDevice, stateChange);
4926 if (outputDesc->mRefCount[stream]) {
4927 int muteCount = 1;
4928 if (stateChange) {
4929 muteCount = outputDesc->mRefCount[stream];
4930 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004931 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004932 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4933 for (int i = 0; i < muteCount; i++) {
4934 setStreamMute(stream, starting, mPrimaryOutput);
4935 }
4936 } else {
4937 ALOGV("handleIncallSonification() high visibility");
4938 if (outputDesc->device() &
4939 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4940 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4941 for (int i = 0; i < muteCount; i++) {
4942 setStreamMute(stream, starting, mPrimaryOutput);
4943 }
4944 }
4945 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004946 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4947 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004948 } else {
4949 mpClientInterface->stopTone();
4950 }
4951 }
4952 }
4953 }
4954}
4955
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004956audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
4957{
4958 // flags to stream type mapping
4959 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4960 return AUDIO_STREAM_ENFORCED_AUDIBLE;
4961 }
4962 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
4963 return AUDIO_STREAM_BLUETOOTH_SCO;
4964 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08004965 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4966 return AUDIO_STREAM_TTS;
4967 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004968
4969 // usage to stream type mapping
4970 switch (attr->usage) {
4971 case AUDIO_USAGE_MEDIA:
4972 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004973 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4974 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004975 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08004976 if (isStreamActive(AUDIO_STREAM_ALARM)) {
4977 return AUDIO_STREAM_ALARM;
4978 }
4979 if (isStreamActive(AUDIO_STREAM_RING)) {
4980 return AUDIO_STREAM_RING;
4981 }
4982 if (isInCall()) {
4983 return AUDIO_STREAM_VOICE_CALL;
4984 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08004985 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004986 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4987 return AUDIO_STREAM_SYSTEM;
4988 case AUDIO_USAGE_VOICE_COMMUNICATION:
4989 return AUDIO_STREAM_VOICE_CALL;
4990
4991 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4992 return AUDIO_STREAM_DTMF;
4993
4994 case AUDIO_USAGE_ALARM:
4995 return AUDIO_STREAM_ALARM;
4996 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4997 return AUDIO_STREAM_RING;
4998
4999 case AUDIO_USAGE_NOTIFICATION:
5000 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5001 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5002 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5003 case AUDIO_USAGE_NOTIFICATION_EVENT:
5004 return AUDIO_STREAM_NOTIFICATION;
5005
5006 case AUDIO_USAGE_UNKNOWN:
5007 default:
5008 return AUDIO_STREAM_MUSIC;
5009 }
5010}
Eric Laurente83b55d2014-11-14 10:06:21 -08005011
François Gaffie53615e22015-03-19 09:24:12 +01005012bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5013{
Eric Laurente83b55d2014-11-14 10:06:21 -08005014 // has flags that map to a strategy?
5015 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5016 return true;
5017 }
5018
5019 // has known usage?
5020 switch (paa->usage) {
5021 case AUDIO_USAGE_UNKNOWN:
5022 case AUDIO_USAGE_MEDIA:
5023 case AUDIO_USAGE_VOICE_COMMUNICATION:
5024 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5025 case AUDIO_USAGE_ALARM:
5026 case AUDIO_USAGE_NOTIFICATION:
5027 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5028 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5029 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5030 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5031 case AUDIO_USAGE_NOTIFICATION_EVENT:
5032 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5033 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5034 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5035 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005036 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005037 break;
5038 default:
5039 return false;
5040 }
5041 return true;
5042}
5043
François Gaffiead3183e2015-03-18 16:55:35 +01005044bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5045 routing_strategy strategy, uint32_t inPastMs,
5046 nsecs_t sysTime) const
5047{
5048 if ((sysTime == 0) && (inPastMs != 0)) {
5049 sysTime = systemTime();
5050 }
5051 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5052 if (i == AUDIO_STREAM_PATCH) {
5053 continue;
5054 }
5055 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5056 (NUM_STRATEGIES == strategy)) &&
5057 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5058 return true;
5059 }
5060 }
5061 return false;
5062}
5063
François Gaffie2110e042015-03-24 08:41:51 +01005064audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5065{
5066 return mEngine->getForceUse(usage);
5067}
5068
5069bool AudioPolicyManager::isInCall()
5070{
5071 return isStateInCall(mEngine->getPhoneState());
5072}
5073
5074bool AudioPolicyManager::isStateInCall(int state)
5075{
5076 return is_state_in_call(state);
5077}
5078
Eric Laurentd60560a2015-04-10 11:31:20 -07005079void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5080{
5081 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5082 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5083 if (sourceDesc->mDevice->equals(deviceDesc)) {
5084 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5085 stopAudioSource(sourceDesc->getHandle());
5086 }
5087 }
5088
5089 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5090 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5091 bool release = false;
5092 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5093 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5094 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5095 source->ext.device.type == deviceDesc->type()) {
5096 release = true;
5097 }
5098 }
5099 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5100 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5101 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5102 sink->ext.device.type == deviceDesc->type()) {
5103 release = true;
5104 }
5105 }
5106 if (release) {
5107 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5108 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5109 }
5110 }
5111}
5112
François Gaffie112b0af2015-11-19 16:13:25 +01005113void AudioPolicyManager::updateAudioProfiles(audio_io_handle_t ioHandle,
5114 AudioProfileVector &profiles)
5115{
5116 String8 reply;
5117 char *value;
5118 // Format MUST be checked first to update the list of AudioProfile
5119 if (profiles.hasDynamicFormat()) {
5120 reply = mpClientInterface->getParameters(ioHandle,
5121 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
5122 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
5123 value = strpbrk((char *)reply.string(), "=");
5124 if (value == NULL) {
5125 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5126 return;
5127 }
5128 profiles.setFormats(formatsFromString(value + 1));
5129 }
5130 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5131
5132 for(size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
5133 audio_format_t format = supportedFormats[formatIndex];
5134 AudioParameter requestedParameters;
5135 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5136
5137 if (profiles.hasDynamicRateFor(format)) {
5138 reply = mpClientInterface->getParameters(ioHandle,
5139 requestedParameters.toString() + ";" +
5140 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5141 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
5142 value = strpbrk((char *)reply.string(), "=");
5143 if (value != NULL) {
5144 profiles.setSampleRatesFor(samplingRatesFromString(value + 1), format);
5145 }
5146 }
5147 if (profiles.hasDynamicChannelsFor(format)) {
5148 reply = mpClientInterface->getParameters(ioHandle,
5149 requestedParameters.toString() + ";" +
5150 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5151 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
5152 value = strpbrk((char *)reply.string(), "=");
5153 if (value != NULL) {
5154 profiles.setChannelsFor(channelMasksFromString(value + 1), format);
5155 }
5156 }
5157 }
5158}
Eric Laurentd60560a2015-04-10 11:31:20 -07005159
Eric Laurente552edb2014-03-10 17:42:56 -07005160}; // namespace android