blob: f48cbd42531347547887b7365d4a1d7e88805a41 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Phil Burk09bc4612016-02-24 15:58:15 -080017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
36#include <hardware/audio.h>
37#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
53// AudioPolicyInterface implementation
54// ----------------------------------------------------------------------------
55
Eric Laurente0720872014-03-11 09:30:41 -070056status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080057 audio_policy_dev_state_t state,
58 const char *device_address,
59 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070060{
Paul McLeane743a472015-01-28 11:07:31 -080061 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080062}
63
64status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080065 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080066 const char *device_address,
67 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080068{
Paul McLeane743a472015-01-28 11:07:31 -080069 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
70- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070071
72 // connect/disconnect only 1 device at a time
73 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
74
François Gaffie53615e22015-03-19 09:24:12 +010075 sp<DeviceDescriptor> devDesc =
76 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080077
Eric Laurente552edb2014-03-10 17:42:56 -070078 // handle output devices
79 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070080 SortedVector <audio_io_handle_t> outputs;
81
Eric Laurent3a4311c2014-03-17 12:00:47 -070082 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
83
Eric Laurente552edb2014-03-10 17:42:56 -070084 // save a copy of the opened output descriptors before any output is opened or closed
85 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
86 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -070087 switch (state)
88 {
89 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -080090 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -070092 ALOGW("setDeviceConnectionState() device already connected: %x", device);
93 return INVALID_OPERATION;
94 }
95 ALOGV("setDeviceConnectionState() connecting device %x", device);
96
Eric Laurente552edb2014-03-10 17:42:56 -070097 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -070098 index = mAvailableOutputDevices.add(devDesc);
99 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100100 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700101 if (module == 0) {
102 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
103 device);
104 mAvailableOutputDevices.remove(devDesc);
105 return INVALID_OPERATION;
106 }
Paul McLeane743a472015-01-28 11:07:31 -0800107 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700108 } else {
109 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700110 }
111
Eric Laurenta1d525f2015-01-29 13:36:45 -0800112 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700113 mAvailableOutputDevices.remove(devDesc);
114 return INVALID_OPERATION;
115 }
François Gaffie2110e042015-03-24 08:41:51 +0100116 // Propagate device availability to Engine
117 mEngine->setDeviceConnectionState(devDesc, state);
118
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700119 // outputs should never be empty here
120 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
121 "checkOutputsForDevice() returned no outputs but status OK");
122 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
123 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800124
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800125 // Send connect to HALs
Eric Laurent3ae5f312015-02-03 17:12:08 -0800126 AudioParameter param = AudioParameter(devDesc->mAddress);
127 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
128 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
129
130 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700132 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700133 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700134 ALOGW("setDeviceConnectionState() device not connected: %x", device);
135 return INVALID_OPERATION;
136 }
137
Paul McLean5c477aa2014-08-20 16:47:57 -0700138 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
139
Paul McLeane743a472015-01-28 11:07:31 -0800140 // Send Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800141 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700142 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
143 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
144
Eric Laurente552edb2014-03-10 17:42:56 -0700145 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700147
Eric Laurenta1d525f2015-01-29 13:36:45 -0800148 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100149
150 // Propagate device availability to Engine
151 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700152 } break;
153
154 default:
155 ALOGE("setDeviceConnectionState() invalid state: %x", state);
156 return BAD_VALUE;
157 }
158
Eric Laurent3a4311c2014-03-17 12:00:47 -0700159 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
160 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700161 checkA2dpSuspend();
162 checkOutputForAllStrategies();
163 // outputs must be closed after checkOutputForAllStrategies() is executed
164 if (!outputs.isEmpty()) {
165 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700166 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700167 // close unused outputs after device disconnection or direct outputs that have been
168 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700169 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700170 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
171 (desc->mDirectOpenCount == 0))) {
172 closeOutput(outputs[i]);
173 }
174 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700175 // check again after closing A2DP output to reset mA2dpSuspended if needed
176 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700177 }
178
179 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700180 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700181 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
182 updateCallRouting(newDevice);
183 }
Eric Laurente552edb2014-03-10 17:42:56 -0700184 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700185 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
186 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
187 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700188 // do not force device change on duplicated output because if device is 0, it will
189 // also force a device 0 for the two outputs it is duplicated to which may override
190 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700191 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100192 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700193 // always force when disconnecting (a non-duplicated device)
194 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700195 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700196 }
Eric Laurente552edb2014-03-10 17:42:56 -0700197 }
198
Eric Laurentd60560a2015-04-10 11:31:20 -0700199 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
200 cleanUpForDevice(devDesc);
201 }
202
Eric Laurent72aa32f2014-05-30 18:51:48 -0700203 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700204 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700205 } // end if is output device
206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // handle input devices
208 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700209 SortedVector <audio_io_handle_t> inputs;
210
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700212 switch (state)
213 {
214 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700217 ALOGW("setDeviceConnectionState() device already connected: %d", device);
218 return INVALID_OPERATION;
219 }
François Gaffie53615e22015-03-19 09:24:12 +0100220 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700221 if (module == NULL) {
222 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
223 device);
224 return INVALID_OPERATION;
225 }
Paul McLean9080a4c2015-06-18 08:24:02 -0700226 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700227 return INVALID_OPERATION;
228 }
229
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 index = mAvailableInputDevices.add(devDesc);
231 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800232 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 } else {
234 return NO_MEMORY;
235 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236
237 // Set connect to HALs
238 AudioParameter param = AudioParameter(devDesc->mAddress);
239 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
240 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
241
François Gaffie2110e042015-03-24 08:41:51 +0100242 // Propagate device availability to Engine
243 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700244 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700245
246 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700247 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700249 ALOGW("setDeviceConnectionState() device not connected: %d", device);
250 return INVALID_OPERATION;
251 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700252
253 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
254
255 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800256 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700257 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
258 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
259
Paul McLean9080a4c2015-06-18 08:24:02 -0700260 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700262
François Gaffie2110e042015-03-24 08:41:51 +0100263 // Propagate device availability to Engine
264 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700265 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700266
267 default:
268 ALOGE("setDeviceConnectionState() invalid state: %x", state);
269 return BAD_VALUE;
270 }
271
Eric Laurentd4692962014-05-05 18:13:44 -0700272 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700273
Eric Laurent87ffa392015-05-22 10:32:38 -0700274 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700275 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
276 updateCallRouting(newDevice);
277 }
278
Eric Laurentd60560a2015-04-10 11:31:20 -0700279 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
280 cleanUpForDevice(devDesc);
281 }
282
Eric Laurentb52c1522014-05-20 11:27:36 -0700283 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700284 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 ALOGW("setDeviceConnectionState() invalid device: %x", device);
288 return BAD_VALUE;
289}
290
Eric Laurente0720872014-03-11 09:30:41 -0700291audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100292 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700293{
François Gaffie53615e22015-03-19 09:24:12 +0100294 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(device, device_address, "");
295
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 DeviceVector *deviceVector;
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700300 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700301 deviceVector = &mAvailableInputDevices;
302 } else {
303 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
304 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700305 }
François Gaffie53615e22015-03-19 09:24:12 +0100306 return deviceVector->getDeviceConnectionState(devDesc);
Eric Laurenta1d525f2015-01-29 13:36:45 -0800307}
308
Eric Laurentc2730ba2014-07-20 15:47:07 -0700309void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
310{
311 bool createTxPatch = false;
312 struct audio_patch patch;
313 patch.num_sources = 1;
314 patch.num_sinks = 1;
315 status_t status;
316 audio_patch_handle_t afPatchHandle;
317 DeviceVector deviceList;
318
Eric Laurent87ffa392015-05-22 10:32:38 -0700319 if(!hasPrimaryOutput()) {
320 return;
321 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800322 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700323 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
324
325 // release existing RX patch if any
326 if (mCallRxPatch != 0) {
327 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
328 mCallRxPatch.clear();
329 }
330 // release TX patch if any
331 if (mCallTxPatch != 0) {
332 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
333 mCallTxPatch.clear();
334 }
335
336 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
337 // via setOutputDevice() on primary output.
338 // Otherwise, create two audio patches for TX and RX path.
339 if (availablePrimaryOutputDevices() & rxDevice) {
340 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
341 // If the TX device is also on the primary HW module, setOutputDevice() will take care
342 // of it due to legacy implementation. If not, create a patch.
343 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
344 == AUDIO_DEVICE_NONE) {
345 createTxPatch = true;
346 }
347 } else {
348 // create RX path audio patch
349 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
350 ALOG_ASSERT(!deviceList.isEmpty(),
351 "updateCallRouting() selected device not in output device list");
352 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
353 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
354 ALOG_ASSERT(!deviceList.isEmpty(),
355 "updateCallRouting() no telephony RX device");
356 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
357
358 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
359 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
360
361 // request to reuse existing output stream if one is already opened to reach the RX device
362 SortedVector<audio_io_handle_t> outputs =
363 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700364 audio_io_handle_t output = selectOutput(outputs,
365 AUDIO_OUTPUT_FLAG_NONE,
366 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700367 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700368 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700369 ALOG_ASSERT(!outputDesc->isDuplicated(),
370 "updateCallRouting() RX device output is duplicated");
371 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700372 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700373 patch.num_sources = 2;
374 }
375
376 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
377 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
378 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
379 status);
380 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100381 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700382 mCallRxPatch->mAfPatchHandle = afPatchHandle;
383 mCallRxPatch->mUid = mUidCached;
384 }
385 createTxPatch = true;
386 }
387 if (createTxPatch) {
388
389 struct audio_patch patch;
390 patch.num_sources = 1;
391 patch.num_sinks = 1;
392 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
393 ALOG_ASSERT(!deviceList.isEmpty(),
394 "updateCallRouting() selected device not in input device list");
395 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
396 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
397 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
398 ALOG_ASSERT(!deviceList.isEmpty(),
399 "updateCallRouting() no telephony TX device");
400 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
401 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
402
403 SortedVector<audio_io_handle_t> outputs =
404 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700405 audio_io_handle_t output = selectOutput(outputs,
406 AUDIO_OUTPUT_FLAG_NONE,
407 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700408 // request to reuse existing output stream if one is already opened to reach the TX
409 // path output device
410 if (output != AUDIO_IO_HANDLE_NONE) {
411 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
412 ALOG_ASSERT(!outputDesc->isDuplicated(),
413 "updateCallRouting() RX device output is duplicated");
414 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700415 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700416 patch.num_sources = 2;
417 }
418
Eric Laurentc0a889f2015-10-14 14:36:34 -0700419 // terminate active capture if on the same HW module as the call TX source device
420 // FIXME: would be better to refine to only inputs whose profile connects to the
421 // call TX device but this information is not in the audio patch and logic here must be
422 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800423 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
424 for (size_t i = 0; i < activeInputs.size(); i++) {
425 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
426 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
427 AudioSessionCollection activeSessions =
428 activeDesc->getAudioSessions(true /*activeOnly*/);
429 for (size_t j = 0; j < activeSessions.size(); j++) {
430 audio_session_t activeSession = activeSessions.keyAt(j);
431 stopInput(activeDesc->mIoHandle, activeSession);
432 releaseInput(activeDesc->mIoHandle, activeSession);
433 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700434 }
435 }
436
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
438 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
439 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
440 status);
441 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100442 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700443 mCallTxPatch->mAfPatchHandle = afPatchHandle;
444 mCallTxPatch->mUid = mUidCached;
445 }
446 }
447}
448
Eric Laurente0720872014-03-11 09:30:41 -0700449void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700450{
451 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100452 // store previous phone state for management of sonification strategy below
453 int oldState = mEngine->getPhoneState();
454
455 if (mEngine->setPhoneState(state) != NO_ERROR) {
456 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700457 return;
458 }
François Gaffie2110e042015-03-24 08:41:51 +0100459 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700460 // if leaving call state, handle special case of active streams
461 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700462 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700463 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700464 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800465 if (stream == AUDIO_STREAM_PATCH) {
466 continue;
467 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700468 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700469 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800470
Eric Laurent63dea1d2015-07-02 17:10:28 -0700471 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800472 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700473 }
474
François Gaffie2110e042015-03-24 08:41:51 +0100475 /**
476 * Switching to or from incall state or switching between telephony and VoIP lead to force
477 * routing command.
478 */
479 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
480 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700481
482 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700483 checkA2dpSuspend();
484 checkOutputForAllStrategies();
485 updateDevicesAndOutputs();
486
Eric Laurente552edb2014-03-10 17:42:56 -0700487 int delayMs = 0;
488 if (isStateInCall(state)) {
489 nsecs_t sysTime = systemTime();
490 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700491 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700492 // mute media and sonification strategies and delay device switch by the largest
493 // latency of any output where either strategy is active.
494 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100495 if ((isStrategyActive(desc, STRATEGY_MEDIA,
496 SONIFICATION_HEADSET_MUSIC_DELAY,
497 sysTime) ||
498 isStrategyActive(desc, STRATEGY_SONIFICATION,
499 SONIFICATION_HEADSET_MUSIC_DELAY,
500 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700501 (delayMs < (int)desc->latency()*2)) {
502 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700503 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700504 setStrategyMute(STRATEGY_MEDIA, true, desc);
505 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700506 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700507 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
508 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700509 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
510 }
511 }
512
Eric Laurent87ffa392015-05-22 10:32:38 -0700513 if (hasPrimaryOutput()) {
514 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
515 // the device returned is not necessarily reachable via this output
516 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
517 // force routing command to audio hardware when ending call
518 // even if no device change is needed
519 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
520 rxDevice = mPrimaryOutput->device();
521 }
Eric Laurente552edb2014-03-10 17:42:56 -0700522
Eric Laurent87ffa392015-05-22 10:32:38 -0700523 if (state == AUDIO_MODE_IN_CALL) {
524 updateCallRouting(rxDevice, delayMs);
525 } else if (oldState == AUDIO_MODE_IN_CALL) {
526 if (mCallRxPatch != 0) {
527 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
528 mCallRxPatch.clear();
529 }
530 if (mCallTxPatch != 0) {
531 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
532 mCallTxPatch.clear();
533 }
534 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
535 } else {
536 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700537 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700538 }
Eric Laurente552edb2014-03-10 17:42:56 -0700539 // if entering in call state, handle special case of active streams
540 // pertaining to sonification strategy see handleIncallSonification()
541 if (isStateInCall(state)) {
542 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700543 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800544 if (stream == AUDIO_STREAM_PATCH) {
545 continue;
546 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700547 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700548 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700549
550 // force reevaluating accessibility routing when call starts
551 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700552 }
553
554 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700555 if (state == AUDIO_MODE_RINGTONE &&
556 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700557 mLimitRingtoneVolume = true;
558 } else {
559 mLimitRingtoneVolume = false;
560 }
561}
562
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700563audio_mode_t AudioPolicyManager::getPhoneState() {
564 return mEngine->getPhoneState();
565}
566
Eric Laurente0720872014-03-11 09:30:41 -0700567void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700568 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700569{
François Gaffie2110e042015-03-24 08:41:51 +0100570 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700571
Phil Burk09bc4612016-02-24 15:58:15 -0800572 audio_policy_forced_cfg_t originalConfig = mEngine->getForceUse(usage);
François Gaffie2110e042015-03-24 08:41:51 +0100573 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
574 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
575 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700576 }
François Gaffie2110e042015-03-24 08:41:51 +0100577 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
578 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
579 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700580
581 // check for device and output changes triggered by new force usage
582 checkA2dpSuspend();
583 checkOutputForAllStrategies();
584 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800585
586 // Did surround forced use change?
587 if ((usage == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND)
588 && (originalConfig != config)) {
589 const char *device_address = "";
590 // Is it currently connected? If so then cycle the connection
591 // so that the supported surround formats will be reloaded.
592 //
593 // FIXME As S/PDIF is not a removable device we have to handle this differently.
594 // Probably by updating the device descriptor directly and manually
595 // tearing down active playback on S/PDIF
596 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_HDMI, device_address) ==
597 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
598 // Disconnect and reconnect output devices so that the surround
599 // encodings can be updated.
600 const char *device_name = "";
601 // disconnect
602 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
603 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
604 device_address, device_name);
605 // reconnect
606 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
607 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
608 device_address, device_name);
609 }
610 }
611
Eric Laurent87ffa392015-05-22 10:32:38 -0700612 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700613 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
614 updateCallRouting(newDevice);
615 }
Eric Laurente552edb2014-03-10 17:42:56 -0700616 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700617 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
618 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
619 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
620 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700621 }
Eric Laurente552edb2014-03-10 17:42:56 -0700622 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700623 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700624 }
625 }
626
Eric Laurentfb66dd92016-01-28 18:32:03 -0800627 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
628 for (size_t i = 0; i < activeInputs.size(); i++) {
629 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
630 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700631 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800632 if (activeDesc->mProfile->getSupportedDevices().types() &
633 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
634 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700635 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800636 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700637 }
Eric Laurente552edb2014-03-10 17:42:56 -0700638 }
Eric Laurente552edb2014-03-10 17:42:56 -0700639}
640
Eric Laurente0720872014-03-11 09:30:41 -0700641void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700642{
643 ALOGV("setSystemProperty() property %s, value %s", property, value);
644}
645
646// Find a direct output profile compatible with the parameters passed, even if the input flags do
647// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800648sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700649 audio_devices_t device,
650 uint32_t samplingRate,
651 audio_format_t format,
652 audio_channel_mask_t channelMask,
653 audio_output_flags_t flags)
654{
Eric Laurent861a6282015-05-18 15:40:16 -0700655 // only retain flags that will drive the direct output profile selection
656 // if explicitly requested
657 static const uint32_t kRelevantFlags =
658 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
659 flags =
660 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
661
662 sp<IOProfile> profile;
663
Eric Laurente552edb2014-03-10 17:42:56 -0700664 for (size_t i = 0; i < mHwModules.size(); i++) {
665 if (mHwModules[i]->mHandle == 0) {
666 continue;
667 }
668 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700669 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
670 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700671 samplingRate, NULL /*updatedSamplingRate*/,
672 format, NULL /*updatedFormat*/,
673 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700674 flags)) {
675 continue;
676 }
677 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100678 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700679 continue;
680 }
681 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100682 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700683 continue;
684 }
685 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100686 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700687 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700688 }
Eric Laurente552edb2014-03-10 17:42:56 -0700689 }
690 }
Eric Laurent861a6282015-05-18 15:40:16 -0700691 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700692}
693
Eric Laurente0720872014-03-11 09:30:41 -0700694audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100695 uint32_t samplingRate,
696 audio_format_t format,
697 audio_channel_mask_t channelMask,
698 audio_output_flags_t flags,
699 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700700{
Eric Laurent3b73df72014-03-11 09:06:29 -0700701 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700702 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
703 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
704 device, stream, samplingRate, format, channelMask, flags);
705
Eric Laurente83b55d2014-11-14 10:06:21 -0800706 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
707 stream, samplingRate,format, channelMask,
708 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700709}
710
Eric Laurente83b55d2014-11-14 10:06:21 -0800711status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
712 audio_io_handle_t *output,
713 audio_session_t session,
714 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700715 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800716 uint32_t samplingRate,
717 audio_format_t format,
718 audio_channel_mask_t channelMask,
719 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700720 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800721 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700722{
Eric Laurente83b55d2014-11-14 10:06:21 -0800723 audio_attributes_t attributes;
724 if (attr != NULL) {
725 if (!isValidAttributes(attr)) {
726 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
727 attr->usage, attr->content_type, attr->flags,
728 attr->tags);
729 return BAD_VALUE;
730 }
731 attributes = *attr;
732 } else {
733 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
734 ALOGE("getOutputForAttr(): invalid stream type");
735 return BAD_VALUE;
736 }
737 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700738 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700739 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800740 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100741 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800742 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100743 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800744 }
François Gaffie036e1e92015-03-19 10:16:24 +0100745 *stream = streamTypefromAttributesInt(&attributes);
746 *output = desc->mIoHandle;
747 ALOGV("getOutputForAttr() returns output %d", *output);
748 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800749 }
750 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
751 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
752 return BAD_VALUE;
753 }
754
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700755 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
756 " session %d selectedDeviceId %d",
757 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
758 session, selectedDeviceId);
759
760 *stream = streamTypefromAttributesInt(&attributes);
761
762 // Explicit routing?
763 sp<DeviceDescriptor> deviceDesc;
764 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
765 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
766 deviceDesc = mAvailableOutputDevices[i];
767 break;
768 }
769 }
770 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700771
Eric Laurente83b55d2014-11-14 10:06:21 -0800772 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700773 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700774
Eric Laurente83b55d2014-11-14 10:06:21 -0800775 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700776 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
777 }
778
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700779 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700780 device, samplingRate, format, channelMask, flags);
781
Eric Laurente83b55d2014-11-14 10:06:21 -0800782 *output = getOutputForDevice(device, session, *stream,
783 samplingRate, format, channelMask,
784 flags, offloadInfo);
785 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700786 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800787 return INVALID_OPERATION;
788 }
Paul McLeanaa981192015-03-21 09:55:15 -0700789
Eric Laurente83b55d2014-11-14 10:06:21 -0800790 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700791}
792
793audio_io_handle_t AudioPolicyManager::getOutputForDevice(
794 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800795 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700796 audio_stream_type_t stream,
797 uint32_t samplingRate,
798 audio_format_t format,
799 audio_channel_mask_t channelMask,
800 audio_output_flags_t flags,
801 const audio_offload_info_t *offloadInfo)
802{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700803 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700804 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700805 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700806
Eric Laurente552edb2014-03-10 17:42:56 -0700807#ifdef AUDIO_POLICY_TEST
808 if (mCurOutput != 0) {
809 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
810 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
811
812 if (mTestOutputs[mCurOutput] == 0) {
813 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700814 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
815 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700816 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700817 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700818 outputDesc->mFlags =
819 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700820 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700821 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
822 config.sample_rate = mTestSamplingRate;
823 config.channel_mask = mTestChannels;
824 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700825 if (offloadInfo != NULL) {
826 config.offload_info = *offloadInfo;
827 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700828 status = mpClientInterface->openOutput(0,
829 &mTestOutputs[mCurOutput],
830 &config,
831 &outputDesc->mDevice,
832 String8(""),
833 &outputDesc->mLatency,
834 outputDesc->mFlags);
835 if (status == NO_ERROR) {
836 outputDesc->mSamplingRate = config.sample_rate;
837 outputDesc->mFormat = config.format;
838 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700839 AudioParameter outputCmd = AudioParameter();
840 outputCmd.addInt(String8("set_id"),mCurOutput);
841 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
842 addOutput(mTestOutputs[mCurOutput], outputDesc);
843 }
844 }
845 return mTestOutputs[mCurOutput];
846 }
847#endif //AUDIO_POLICY_TEST
848
849 // open a direct output if required by specified parameters
850 //force direct flag if offload flag is set: offloading implies a direct output stream
851 // and all common behaviors are driven by checking only the direct flag
852 // this should normally be set appropriately in the policy configuration file
853 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700854 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700855 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700856 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
857 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
858 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800859 // only allow deep buffering for music stream type
860 if (stream != AUDIO_STREAM_MUSIC) {
861 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700862 } else if (/* stream == AUDIO_STREAM_MUSIC && */
863 flags == AUDIO_OUTPUT_FLAG_NONE &&
864 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
865 // use DEEP_BUFFER as default output for music stream type
866 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800867 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700868 if (stream == AUDIO_STREAM_TTS) {
869 flags = AUDIO_OUTPUT_FLAG_TTS;
870 }
Eric Laurente552edb2014-03-10 17:42:56 -0700871
Eric Laurentb732cf52014-09-24 19:08:21 -0700872 sp<IOProfile> profile;
873
874 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700875 // and not explicitly requested
876 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
877 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700878 audio_channel_count_from_out_mask(channelMask) <= 2) {
879 goto non_direct_output;
880 }
881
Andy Hung2ddee192015-12-18 17:34:44 -0800882 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
883 // This prevents creating an offloaded track and tearing it down immediately after start
884 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700885 // FIXME: We should check the audio session here but we do not have it in this context.
886 // This may prevent offloading in rare situations where effects are left active by apps
887 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700888
Eric Laurente552edb2014-03-10 17:42:56 -0700889 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800890 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700891 profile = getProfileForDirectOutput(device,
892 samplingRate,
893 format,
894 channelMask,
895 (audio_output_flags_t)flags);
896 }
897
Eric Laurent1c333e22014-05-20 10:48:17 -0700898 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700899 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700900
901 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700902 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700903 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
904 outputDesc = desc;
905 // reuse direct output if currently open and configured with same parameters
906 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800907 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700908 (channelMask == outputDesc->mChannelMask)) {
909 outputDesc->mDirectOpenCount++;
910 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
911 return mOutputs.keyAt(i);
912 }
913 }
914 }
915 // close direct output if currently open and configured with different parameters
916 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700917 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700918 }
Eric Laurent861a6282015-05-18 15:40:16 -0700919
920 // if the selected profile is offloaded and no offload info was specified,
921 // create a default one
922 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100923 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700924 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
925 defaultOffloadInfo.sample_rate = samplingRate;
926 defaultOffloadInfo.channel_mask = channelMask;
927 defaultOffloadInfo.format = format;
928 defaultOffloadInfo.stream_type = stream;
929 defaultOffloadInfo.bit_rate = 0;
930 defaultOffloadInfo.duration_us = -1;
931 defaultOffloadInfo.has_video = true; // conservative
932 defaultOffloadInfo.is_streaming = true; // likely
933 offloadInfo = &defaultOffloadInfo;
934 }
935
Eric Laurentc75307b2015-03-17 15:29:32 -0700936 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700937 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700938 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700939 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700940 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
941 config.sample_rate = samplingRate;
942 config.channel_mask = channelMask;
943 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700944 if (offloadInfo != NULL) {
945 config.offload_info = *offloadInfo;
946 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700947 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700948 &output,
949 &config,
950 &outputDesc->mDevice,
951 String8(""),
952 &outputDesc->mLatency,
953 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700954
955 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700956 if (status != NO_ERROR ||
957 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800958 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700959 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700960 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
961 "format %d %d, channelMask %04x %04x", output, samplingRate,
962 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
963 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700964 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700965 mpClientInterface->closeOutput(output);
966 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800967 // fall back to mixer output if possible when the direct output could not be open
968 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
969 goto non_direct_output;
970 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700971 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700972 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700973 outputDesc->mSamplingRate = config.sample_rate;
974 outputDesc->mChannelMask = config.channel_mask;
975 outputDesc->mFormat = config.format;
976 outputDesc->mRefCount[stream] = 0;
977 outputDesc->mStopTime[stream] = 0;
978 outputDesc->mDirectOpenCount = 1;
979
Eric Laurente552edb2014-03-10 17:42:56 -0700980 audio_io_handle_t srcOutput = getOutputForEffect();
981 addOutput(output, outputDesc);
982 audio_io_handle_t dstOutput = getOutputForEffect();
983 if (dstOutput == output) {
984 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
985 }
986 mPreviousOutputs = mOutputs;
987 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700988 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700989 return output;
990 }
991
Eric Laurentb732cf52014-09-24 19:08:21 -0700992non_direct_output:
Eric Laurente552edb2014-03-10 17:42:56 -0700993 // ignoring channel mask due to downmix capability in mixer
994
995 // open a non direct output
996
997 // for non direct outputs, only PCM is supported
998 if (audio_is_linear_pcm(format)) {
999 // get which output is suitable for the specified stream. The actual
1000 // routing change will happen when startOutput() will be called
1001 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1002
Eric Laurent8838a382014-09-08 16:44:28 -07001003 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1004 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1005 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001006 }
1007 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1008 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1009
Paul McLeanaa981192015-03-21 09:55:15 -07001010 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001011
1012 return output;
1013}
1014
Eric Laurente0720872014-03-11 09:30:41 -07001015audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001016 audio_output_flags_t flags,
1017 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001018{
1019 // select one output among several that provide a path to a particular device or set of
1020 // devices (the list was previously build by getOutputsForDevice()).
1021 // The priority is as follows:
1022 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001023 // 2: the output with the bit depth the closest to the requested one
1024 // 3: the primary output
1025 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001026
1027 if (outputs.size() == 0) {
1028 return 0;
1029 }
1030 if (outputs.size() == 1) {
1031 return outputs[0];
1032 }
1033
1034 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001035 audio_io_handle_t outputForFlags = 0;
1036 audio_io_handle_t outputForPrimary = 0;
1037 audio_io_handle_t outputForFormat = 0;
1038 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1039 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001040
1041 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001044 // if a valid format is specified, skip output if not compatible
1045 if (format != AUDIO_FORMAT_INVALID) {
1046 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001047 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001048 continue;
1049 }
1050 } else if (!audio_is_linear_pcm(format)) {
1051 continue;
1052 }
Eric Laurente6930022016-02-11 10:20:40 -08001053 if (AudioPort::isBetterFormatMatch(
1054 outputDesc->mFormat, bestFormat, format)) {
1055 outputForFormat = outputs[i];
1056 bestFormat = outputDesc->mFormat;
1057 }
Eric Laurent8838a382014-09-08 16:44:28 -07001058 }
1059
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001060 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001061 if (commonFlags >= maxCommonFlags) {
1062 if (commonFlags == maxCommonFlags) {
1063 if (AudioPort::isBetterFormatMatch(
1064 outputDesc->mFormat, bestFormatForFlags, format)) {
1065 outputForFlags = outputs[i];
1066 bestFormatForFlags = outputDesc->mFormat;
1067 }
1068 } else {
1069 outputForFlags = outputs[i];
1070 maxCommonFlags = commonFlags;
1071 bestFormatForFlags = outputDesc->mFormat;
1072 }
Eric Laurente552edb2014-03-10 17:42:56 -07001073 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1074 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001075 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001076 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001077 }
1078 }
1079 }
1080
Eric Laurente6930022016-02-11 10:20:40 -08001081 if (outputForFlags != 0) {
1082 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001083 }
Eric Laurente6930022016-02-11 10:20:40 -08001084 if (outputForFormat != 0) {
1085 return outputForFormat;
1086 }
1087 if (outputForPrimary != 0) {
1088 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001089 }
1090
1091 return outputs[0];
1092}
1093
Eric Laurente0720872014-03-11 09:30:41 -07001094status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001095 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001096 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001097{
Paul McLeanaa981192015-03-21 09:55:15 -07001098 ALOGV("startOutput() output %d, stream %d, session %d",
1099 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001100 ssize_t index = mOutputs.indexOfKey(output);
1101 if (index < 0) {
1102 ALOGW("startOutput() unknown output %d", output);
1103 return BAD_VALUE;
1104 }
1105
Eric Laurentc75307b2015-03-17 15:29:32 -07001106 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1107
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001108 // Routing?
1109 mOutputRoutes.incRouteActivity(session);
1110
Eric Laurentc75307b2015-03-17 15:29:32 -07001111 audio_devices_t newDevice;
1112 if (outputDesc->mPolicyMix != NULL) {
1113 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent493404d2015-04-21 15:07:36 -07001114 } else if (mOutputRoutes.hasRouteChanged(session)) {
1115 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001116 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001117 } else {
1118 newDevice = AUDIO_DEVICE_NONE;
1119 }
1120
1121 uint32_t delayMs = 0;
1122
Eric Laurentc75307b2015-03-17 15:29:32 -07001123 status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
1124
1125 if (status != NO_ERROR) {
1126 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001127 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001128 }
1129 // Automatically enable the remote submix input when output is started on a re routing mix
1130 // of type MIX_TYPE_RECORDERS
1131 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1132 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1133 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1134 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1135 outputDesc->mPolicyMix->mRegistrationId,
1136 "remote-submix");
1137 }
1138
1139 if (delayMs != 0) {
1140 usleep(delayMs * 1000);
1141 }
1142
1143 return status;
1144}
1145
1146status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1147 audio_stream_type_t stream,
1148 audio_devices_t device,
1149 uint32_t *delayMs)
1150{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001151 // cannot start playback of STREAM_TTS if any other output is being used
1152 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001153
1154 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001155 if (stream == AUDIO_STREAM_TTS) {
1156 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001157 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001158 return INVALID_OPERATION;
1159 } else {
1160 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1161 }
1162 } else {
1163 // some playback other than beacon starts
1164 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1165 }
1166
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001167 // check active before incrementing usage count
1168 bool force = !outputDesc->isActive();
1169
Eric Laurente552edb2014-03-10 17:42:56 -07001170 // increment usage count for this stream on the requested output:
1171 // NOTE that the usage count is the same for duplicated output and hardware output which is
1172 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1173 outputDesc->changeRefCount(stream, 1);
1174
Eric Laurent493404d2015-04-21 15:07:36 -07001175 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001176 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001177 if (device == AUDIO_DEVICE_NONE) {
1178 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001179 }
Eric Laurente552edb2014-03-10 17:42:56 -07001180 routing_strategy strategy = getStrategy(stream);
1181 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001182 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1183 (beaconMuteLatency > 0);
1184 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001185 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001186 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001187 if (desc != outputDesc) {
1188 // force a device change if any other output is managed by the same hw
1189 // module and has a current device selection that differs from selected device.
1190 // In this case, the audio HAL must receive the new device selection so that it can
1191 // change the device currently selected by the other active output.
1192 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001193 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001194 force = true;
1195 }
1196 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001197 // a notification so that audio focus effect can propagate, or that a mute/unmute
1198 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001199 uint32_t latency = desc->latency();
1200 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1201 waitMs = latency;
1202 }
1203 }
1204 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001205 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
Eric Laurente552edb2014-03-10 17:42:56 -07001206
1207 // handle special case for sonification while in call
1208 if (isInCall()) {
1209 handleIncallSonification(stream, true, false);
1210 }
1211
1212 // apply volume rules for current stream and device if necessary
1213 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001214 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001215 outputDesc,
1216 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001217
1218 // update the outputs if starting an output with a stream that can affect notification
1219 // routing
1220 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001221
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001222 // force reevaluating accessibility routing when ringtone or alarm starts
1223 if (strategy == STRATEGY_SONIFICATION) {
1224 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1225 }
Eric Laurente552edb2014-03-10 17:42:56 -07001226 }
1227 return NO_ERROR;
1228}
1229
1230
Eric Laurente0720872014-03-11 09:30:41 -07001231status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001232 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001233 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001234{
1235 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1236 ssize_t index = mOutputs.indexOfKey(output);
1237 if (index < 0) {
1238 ALOGW("stopOutput() unknown output %d", output);
1239 return BAD_VALUE;
1240 }
1241
Eric Laurentc75307b2015-03-17 15:29:32 -07001242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001243
Eric Laurentc75307b2015-03-17 15:29:32 -07001244 if (outputDesc->mRefCount[stream] == 1) {
1245 // Automatically disable the remote submix input when output is stopped on a
1246 // re routing mix of type MIX_TYPE_RECORDERS
1247 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1248 outputDesc->mPolicyMix != NULL &&
1249 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1250 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1251 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1252 outputDesc->mPolicyMix->mRegistrationId,
1253 "remote-submix");
1254 }
1255 }
1256
1257 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001258 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001259 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001260 int activityCount = mOutputRoutes.decRouteActivity(session);
1261 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1262
1263 if (forceDeviceUpdate) {
1264 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1265 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001266 }
1267
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001268 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001269}
1270
1271status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001272 audio_stream_type_t stream,
1273 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001274{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001275 // always handle stream stop, check which stream type is stopping
1276 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1277
Eric Laurente552edb2014-03-10 17:42:56 -07001278 // handle special case for sonification while in call
1279 if (isInCall()) {
1280 handleIncallSonification(stream, false, false);
1281 }
1282
1283 if (outputDesc->mRefCount[stream] > 0) {
1284 // decrement usage count of this stream on the output
1285 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001286
Eric Laurente552edb2014-03-10 17:42:56 -07001287 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001288 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001289 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001290 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001291 // delay the device switch by twice the latency because stopOutput() is executed when
1292 // the track stop() command is received and at that time the audio track buffer can
1293 // still contain data that needs to be drained. The latency only covers the audio HAL
1294 // and kernel buffers. Also the latency does not always include additional delay in the
1295 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001296 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001297
1298 // force restoring the device selection on other active outputs if it differs from the
1299 // one being selected for this output
1300 for (size_t i = 0; i < mOutputs.size(); i++) {
1301 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001302 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001303 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001304 desc->isActive() &&
1305 outputDesc->sharesHwModuleWith(desc) &&
1306 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001307 setOutputDevice(desc,
1308 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001309 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001310 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001311 }
1312 }
1313 // update the outputs if stopping one with a stream that can affect notification routing
1314 handleNotificationRoutingForStream(stream);
1315 }
1316 return NO_ERROR;
1317 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001318 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001319 return INVALID_OPERATION;
1320 }
1321}
1322
Eric Laurente83b55d2014-11-14 10:06:21 -08001323void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001324 audio_stream_type_t stream __unused,
1325 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001326{
1327 ALOGV("releaseOutput() %d", output);
1328 ssize_t index = mOutputs.indexOfKey(output);
1329 if (index < 0) {
1330 ALOGW("releaseOutput() releasing unknown output %d", output);
1331 return;
1332 }
1333
1334#ifdef AUDIO_POLICY_TEST
1335 int testIndex = testOutputIndex(output);
1336 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001337 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001338 if (outputDesc->isActive()) {
1339 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001340 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001341 mTestOutputs[testIndex] = 0;
1342 }
1343 return;
1344 }
1345#endif //AUDIO_POLICY_TEST
1346
Paul McLeanaa981192015-03-21 09:55:15 -07001347 // Routing
1348 mOutputRoutes.removeRoute(session);
1349
Eric Laurentc75307b2015-03-17 15:29:32 -07001350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001351 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001352 if (desc->mDirectOpenCount <= 0) {
1353 ALOGW("releaseOutput() invalid open count %d for output %d",
1354 desc->mDirectOpenCount, output);
1355 return;
1356 }
1357 if (--desc->mDirectOpenCount == 0) {
1358 closeOutput(output);
1359 // If effects where present on the output, audioflinger moved them to the primary
1360 // output by default: move them back to the appropriate output.
1361 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001362 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001363 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1364 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001365 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001366 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001367 }
1368 }
1369}
1370
1371
Eric Laurentcaf7f482014-11-25 17:50:47 -08001372status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1373 audio_io_handle_t *input,
1374 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001375 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001376 uint32_t samplingRate,
1377 audio_format_t format,
1378 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001379 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001380 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001381 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001382{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001383 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1384 "session %d, flags %#x",
1385 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001386
Eric Laurentcaf7f482014-11-25 17:50:47 -08001387 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001388 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001389
Eric Laurent275e8e92014-11-30 15:14:47 -08001390 audio_devices_t device;
1391 // handle legacy remote submix case where the address was not always specified
1392 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001393 audio_source_t inputSource = attr->source;
1394 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001395 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001396
Eric Laurentc447ded2015-01-06 08:47:05 -08001397 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1398 inputSource = AUDIO_SOURCE_MIC;
1399 }
1400 halInputSource = inputSource;
1401
Paul McLean466dc8e2015-04-17 13:15:36 -06001402 // Explicit routing?
1403 sp<DeviceDescriptor> deviceDesc;
1404 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1405 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1406 deviceDesc = mAvailableInputDevices[i];
1407 break;
1408 }
1409 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001410 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001411
Eric Laurentc447ded2015-01-06 08:47:05 -08001412 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001413 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001414 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001415 if (ret != NO_ERROR) {
1416 return ret;
1417 }
1418 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001419 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1420 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001421 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001422 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001423 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001424 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001425 return BAD_VALUE;
1426 }
Eric Laurentc722f302014-12-10 11:21:49 -08001427 if (policyMix != NULL) {
1428 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001429 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1430 // there is an external policy, but this input is attached to a mix of recorders,
1431 // meaning it receives audio injected into the framework, so the recorder doesn't
1432 // know about it and is therefore considered "legacy"
1433 *inputType = API_INPUT_LEGACY;
1434 } else {
1435 // recording a mix of players defined by an external policy, we're rerouting for
1436 // an external policy
1437 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1438 }
Eric Laurentc722f302014-12-10 11:21:49 -08001439 } else if (audio_is_remote_submix_device(device)) {
1440 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001441 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001442 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1443 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001444 } else {
1445 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001446 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001447
Eric Laurent599c7582015-12-07 18:05:55 -08001448 }
1449
1450 *input = getInputForDevice(device, address, session, uid, inputSource,
1451 samplingRate, format, channelMask, flags,
1452 policyMix);
1453 if (*input == AUDIO_IO_HANDLE_NONE) {
1454 mInputRoutes.removeRoute(session);
1455 return INVALID_OPERATION;
1456 }
1457 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1458 return NO_ERROR;
1459}
1460
1461
1462audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1463 String8 address,
1464 audio_session_t session,
1465 uid_t uid,
1466 audio_source_t inputSource,
1467 uint32_t samplingRate,
1468 audio_format_t format,
1469 audio_channel_mask_t channelMask,
1470 audio_input_flags_t flags,
1471 AudioMix *policyMix)
1472{
1473 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1474 audio_source_t halInputSource = inputSource;
1475 bool isSoundTrigger = false;
1476
1477 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1478 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1479 if (index >= 0) {
1480 input = mSoundTriggerSessions.valueFor(session);
1481 isSoundTrigger = true;
1482 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1483 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1484 } else {
1485 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001486 }
1487 }
1488
Andy Hungf129b032015-04-07 13:45:50 -07001489 // find a compatible input profile (not necessarily identical in parameters)
1490 sp<IOProfile> profile;
1491 // samplingRate and flags may be updated by getInputProfile
1492 uint32_t profileSamplingRate = samplingRate;
1493 audio_format_t profileFormat = format;
1494 audio_channel_mask_t profileChannelMask = channelMask;
1495 audio_input_flags_t profileFlags = flags;
1496 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001497 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001498 profileSamplingRate, profileFormat, profileChannelMask,
1499 profileFlags);
1500 if (profile != 0) {
1501 break; // success
1502 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1503 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1504 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001505 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1506 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001507 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001508 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001509 }
Eric Laurente552edb2014-03-10 17:42:56 -07001510 }
1511
Eric Laurent322b4d22015-04-03 15:57:54 -07001512 if (profile->getModuleHandle() == 0) {
1513 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001514 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001515 }
1516
Eric Laurent599c7582015-12-07 18:05:55 -08001517 sp<AudioSession> audioSession = new AudioSession(session,
1518 inputSource,
1519 format,
1520 samplingRate,
1521 channelMask,
1522 flags,
1523 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001524 isSoundTrigger,
1525 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001526
Eric Laurentfb66dd92016-01-28 18:32:03 -08001527
Eric Laurent599c7582015-12-07 18:05:55 -08001528 // reuse an open input if possible
1529 for (size_t i = 0; i < mInputs.size(); i++) {
1530 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001531 // reuse input if:
1532 // - it shares the same profile
1533 // AND
1534 // - it is not a reroute submix input
1535 // AND
1536 // - it is: not used for sound trigger
1537 // OR
1538 // used for sound trigger and all clients use the same session ID
1539 //
1540 if ((profile == desc->mProfile) &&
1541 (isSoundTrigger == desc->isSoundTrigger()) &&
1542 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001543
1544 sp<AudioSession> as = desc->getAudioSession(session);
1545 if (as != 0) {
1546 // do not allow unmatching properties on same session
1547 if (as->matches(audioSession)) {
1548 as->changeOpenCount(1);
1549 } else {
1550 ALOGW("getInputForDevice() record with different attributes"
1551 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001552 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001553 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001554 } else if (isSoundTrigger) {
1555 break;
1556 }
1557 // force close input if current source is now the highest priority request on this input
1558 // and current input properties are not exactly as requested.
1559 if ((desc->mSamplingRate != samplingRate ||
1560 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001561 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001562 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1563 source_priority(inputSource))) {
1564 ALOGV("%s: ", __FUNCTION__);
1565 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1566 for (size_t j = 0; j < sessions.size(); j++) {
1567 audio_session_t currentSession = sessions.keyAt(j);
1568 stopInput(desc->mIoHandle, currentSession);
1569 releaseInput(desc->mIoHandle, currentSession);
1570 }
1571 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001572 } else {
1573 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001574 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1575 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001576 }
Eric Laurent599c7582015-12-07 18:05:55 -08001577 }
1578 }
Eric Laurent599c7582015-12-07 18:05:55 -08001579
Eric Laurentcf2c0212014-07-25 16:20:43 -07001580 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001581 config.sample_rate = profileSamplingRate;
1582 config.channel_mask = profileChannelMask;
1583 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001584
Eric Laurent322b4d22015-04-03 15:57:54 -07001585 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001586 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001587 &config,
1588 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001589 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001590 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001591 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001592
1593 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001594 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001595 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001596 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001597 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001598 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1599 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001600 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001601 if (input != AUDIO_IO_HANDLE_NONE) {
1602 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001603 }
Eric Laurent599c7582015-12-07 18:05:55 -08001604 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001605 }
1606
Eric Laurent1f2f2232014-06-02 12:01:23 -07001607 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001608 inputDesc->mSamplingRate = profileSamplingRate;
1609 inputDesc->mFormat = profileFormat;
1610 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001611 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001612 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001613 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001614
Eric Laurent599c7582015-12-07 18:05:55 -08001615 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001616 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001617
Eric Laurent599c7582015-12-07 18:05:55 -08001618 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001619}
1620
Eric Laurentfb66dd92016-01-28 18:32:03 -08001621bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1622 const sp<AudioSession>& audioSession)
1623{
1624 // Do not allow capture if an active voice call is using a software patch and
1625 // the call TX source device is on the same HW module.
1626 // FIXME: would be better to refine to only inputs whose profile connects to the
1627 // call TX device but this information is not in the audio patch
1628 if (mCallTxPatch != 0 &&
1629 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1630 return false;
1631 }
1632
1633 // starting concurrent capture is enabled if:
1634 // 1) capturing for re-routing
1635 // 2) capturing for HOTWORD source
1636 // 3) capturing for FM TUNER source
1637 // 3) All other active captures are either for re-routing or HOTWORD
1638
1639 if (is_virtual_input_device(inputDesc->mDevice) ||
1640 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1641 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1642 return true;
1643 }
1644
1645 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1646 for (size_t i = 0; i < activeInputs.size(); i++) {
1647 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1648 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1649 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1650 !is_virtual_input_device(activeInput->mDevice)) {
1651 return false;
1652 }
1653 }
1654
1655 return true;
1656}
1657
1658
Eric Laurent4dc68062014-07-28 17:26:49 -07001659status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001660 audio_session_t session,
1661 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001662{
1663 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001664 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001665 ssize_t index = mInputs.indexOfKey(input);
1666 if (index < 0) {
1667 ALOGW("startInput() unknown input %d", input);
1668 return BAD_VALUE;
1669 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001670 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001671
Eric Laurent599c7582015-12-07 18:05:55 -08001672 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1673 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001674 ALOGW("startInput() unknown session %d on input %d", session, input);
1675 return BAD_VALUE;
1676 }
1677
Eric Laurentfb66dd92016-01-28 18:32:03 -08001678 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1679 ALOGW("startInput(%d) failed: other input already started", input);
1680 return INVALID_OPERATION;
1681 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001682
Eric Laurentfb66dd92016-01-28 18:32:03 -08001683 if (isInCall()) {
1684 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1685 }
1686 if (mInputs.activeInputsCount() != 0) {
1687 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001688 }
1689
Eric Laurent313d1e72016-01-29 09:56:57 -08001690 // increment activity count before calling getNewInputDevice() below as only active sessions
1691 // are considered for device selection
1692 audioSession->changeActiveCount(1);
1693
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001694 // Routing?
1695 mInputRoutes.incRouteActivity(session);
1696
Eric Laurent313d1e72016-01-29 09:56:57 -08001697 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001698
Eric Laurentfb66dd92016-01-28 18:32:03 -08001699 setInputDevice(input, getNewInputDevice(inputDesc), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001700
Jean-Michel Trivi56afc7a2016-02-03 11:35:52 -08001701 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001702 // if input maps to a dynamic policy with an activity listener, notify of state change
1703 if ((inputDesc->mPolicyMix != NULL)
1704 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1705 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1706 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001707 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001708
1709 if (mInputs.activeInputsCount() == 0) {
1710 SoundTrigger::setCaptureState(true);
1711 }
1712
1713 // automatically enable the remote submix output when input is started if not
1714 // used by a policy mix of type MIX_TYPE_RECORDERS
1715 // For remote submix (a virtual device), we open only one input per capture request.
1716 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1717 String8 address = String8("");
1718 if (inputDesc->mPolicyMix == NULL) {
1719 address = String8("0");
1720 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1721 address = inputDesc->mPolicyMix->mRegistrationId;
1722 }
1723 if (address != "") {
1724 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1725 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1726 address, "remote-submix");
1727 }
Eric Laurentc722f302014-12-10 11:21:49 -08001728 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001729 }
Eric Laurente552edb2014-03-10 17:42:56 -07001730 }
1731
Eric Laurent599c7582015-12-07 18:05:55 -08001732 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001733
Eric Laurente552edb2014-03-10 17:42:56 -07001734 return NO_ERROR;
1735}
1736
Eric Laurent4dc68062014-07-28 17:26:49 -07001737status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1738 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001739{
1740 ALOGV("stopInput() input %d", input);
1741 ssize_t index = mInputs.indexOfKey(input);
1742 if (index < 0) {
1743 ALOGW("stopInput() unknown input %d", input);
1744 return BAD_VALUE;
1745 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001746 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001747
Eric Laurent599c7582015-12-07 18:05:55 -08001748 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001749 if (index < 0) {
1750 ALOGW("stopInput() unknown session %d on input %d", session, input);
1751 return BAD_VALUE;
1752 }
1753
Eric Laurent599c7582015-12-07 18:05:55 -08001754 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001755 ALOGW("stopInput() input %d already stopped", input);
1756 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001757 }
1758
Eric Laurent599c7582015-12-07 18:05:55 -08001759 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001760
1761 // Routing?
1762 mInputRoutes.decRouteActivity(session);
1763
Eric Laurentfb66dd92016-01-28 18:32:03 -08001764 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001765
Eric Laurentfb66dd92016-01-28 18:32:03 -08001766 if (inputDesc->isActive()) {
1767 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1768 } else {
1769 // if input maps to a dynamic policy with an activity listener, notify of state change
1770 if ((inputDesc->mPolicyMix != NULL)
1771 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1772 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1773 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001774 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001775
1776 // automatically disable the remote submix output when input is stopped if not
1777 // used by a policy mix of type MIX_TYPE_RECORDERS
1778 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1779 String8 address = String8("");
1780 if (inputDesc->mPolicyMix == NULL) {
1781 address = String8("0");
1782 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1783 address = inputDesc->mPolicyMix->mRegistrationId;
1784 }
1785 if (address != "") {
1786 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1787 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1788 address, "remote-submix");
1789 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001790 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001791
Eric Laurentfb66dd92016-01-28 18:32:03 -08001792 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001793
Eric Laurentfb66dd92016-01-28 18:32:03 -08001794 if (mInputs.activeInputsCount() == 0) {
1795 SoundTrigger::setCaptureState(false);
1796 }
1797 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001798 }
Eric Laurente552edb2014-03-10 17:42:56 -07001799 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001800 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001801}
1802
Eric Laurent4dc68062014-07-28 17:26:49 -07001803void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1804 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001805{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001806
Eric Laurente552edb2014-03-10 17:42:56 -07001807 ALOGV("releaseInput() %d", input);
1808 ssize_t index = mInputs.indexOfKey(input);
1809 if (index < 0) {
1810 ALOGW("releaseInput() releasing unknown input %d", input);
1811 return;
1812 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001813
1814 // Routing
1815 mInputRoutes.removeRoute(session);
1816
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001817 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1818 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001819
Eric Laurent599c7582015-12-07 18:05:55 -08001820 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001821 if (index < 0) {
1822 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1823 return;
1824 }
Eric Laurent599c7582015-12-07 18:05:55 -08001825
1826 if (audioSession->openCount() == 0) {
1827 ALOGW("releaseInput() invalid open count %d on session %d",
1828 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001829 return;
1830 }
Eric Laurent599c7582015-12-07 18:05:55 -08001831
1832 if (audioSession->changeOpenCount(-1) == 0) {
1833 inputDesc->removeAudioSession(session);
1834 }
1835
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001836 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001837 ALOGV("releaseInput() exit > 0");
1838 return;
1839 }
1840
Eric Laurent05b90f82014-08-27 15:32:29 -07001841 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001842 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001843 ALOGV("releaseInput() exit");
1844}
1845
Eric Laurentd4692962014-05-05 18:13:44 -07001846void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001847 bool patchRemoved = false;
1848
Eric Laurentd4692962014-05-05 18:13:44 -07001849 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001850 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001851 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001852 if (patch_index >= 0) {
1853 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1854 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1855 mAudioPatches.removeItemsAt(patch_index);
1856 patchRemoved = true;
1857 }
Eric Laurentd4692962014-05-05 18:13:44 -07001858 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1859 }
1860 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001861 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001862 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001863
1864 if (patchRemoved) {
1865 mpClientInterface->onAudioPatchListUpdate();
1866 }
Eric Laurentd4692962014-05-05 18:13:44 -07001867}
1868
Eric Laurente0720872014-03-11 09:30:41 -07001869void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001870 int indexMin,
1871 int indexMax)
1872{
1873 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001874 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001875 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01001876 mVolumeCurves->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001877 }
Eric Laurente552edb2014-03-10 17:42:56 -07001878}
1879
Eric Laurente0720872014-03-11 09:30:41 -07001880status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001881 int index,
1882 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001883{
1884
François Gaffied1ab2bd2015-12-02 18:20:06 +01001885 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1886 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001887 return BAD_VALUE;
1888 }
1889 if (!audio_is_output_device(device)) {
1890 return BAD_VALUE;
1891 }
1892
1893 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001894 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001895
1896 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1897 stream, device, index);
1898
1899 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1900 // clear all device specific values
1901 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01001902 mVolumeCurves->clearCurrentVolumeIndex(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001903 }
François Gaffied1ab2bd2015-12-02 18:20:06 +01001904 mVolumeCurves->addCurrentVolumeIndex(stream, device, index);
Eric Laurente552edb2014-03-10 17:42:56 -07001905
Eric Laurent31551f82014-10-10 18:21:56 -07001906 // update volume on all outputs whose current device is also selected by the same
1907 // strategy as the device specified by the caller
Eric Laurente04e62b2016-01-29 18:25:01 -08001908 audio_devices_t selectedDevices = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1909 // it is possible that the requested device is not selected by the strategy (e.g an explicit
1910 // audio patch is active causing getDevicesForStream() to return this device. We must make
1911 // sure that the device passed is part of the devices considered when applying volume below.
1912 selectedDevices |= device;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001913
1914 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1915 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1916 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01001917 mVolumeCurves->addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001918 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1919 }
Eric Laurente04e62b2016-01-29 18:25:01 -08001920
Eric Laurente552edb2014-03-10 17:42:56 -07001921 status_t status = NO_ERROR;
1922 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001923 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1924 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurente04e62b2016-01-29 18:25:01 -08001925 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & selectedDevices) != 0)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001926 status_t volStatus = checkAndSetVolume(stream, index, desc, curDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07001927 if (volStatus != NO_ERROR) {
1928 status = volStatus;
1929 }
1930 }
Jean-Michel Triviaf20bc22015-09-14 16:37:07 -07001931 if ((accessibilityDevice != AUDIO_DEVICE_NONE) &&
1932 ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)))
1933 {
Eric Laurent223fd5c2014-11-11 13:43:36 -08001934 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
Eric Laurentc75307b2015-03-17 15:29:32 -07001935 index, desc, curDevice);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001936 }
Eric Laurente552edb2014-03-10 17:42:56 -07001937 }
1938 return status;
1939}
1940
Eric Laurente0720872014-03-11 09:30:41 -07001941status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001942 int *index,
1943 audio_devices_t device)
1944{
1945 if (index == NULL) {
1946 return BAD_VALUE;
1947 }
1948 if (!audio_is_output_device(device)) {
1949 return BAD_VALUE;
1950 }
1951 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1952 // the strategy the stream belongs to.
1953 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1954 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1955 }
François Gaffiedfd74092015-03-19 12:10:59 +01001956 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001957
François Gaffied1ab2bd2015-12-02 18:20:06 +01001958 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07001959 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1960 return NO_ERROR;
1961}
1962
Eric Laurente0720872014-03-11 09:30:41 -07001963audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001964 const SortedVector<audio_io_handle_t>& outputs)
1965{
1966 // select one output among several suitable for global effects.
1967 // The priority is as follows:
1968 // 1: An offloaded output. If the effect ends up not being offloadable,
1969 // AudioFlinger will invalidate the track and the offloaded output
1970 // will be closed causing the effect to be moved to a PCM output.
1971 // 2: A deep buffer output
1972 // 3: the first output in the list
1973
1974 if (outputs.size() == 0) {
1975 return 0;
1976 }
1977
1978 audio_io_handle_t outputOffloaded = 0;
1979 audio_io_handle_t outputDeepBuffer = 0;
1980
1981 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001982 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001983 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001984 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1985 outputOffloaded = outputs[i];
1986 }
1987 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1988 outputDeepBuffer = outputs[i];
1989 }
1990 }
1991
1992 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1993 outputOffloaded, outputDeepBuffer);
1994 if (outputOffloaded != 0) {
1995 return outputOffloaded;
1996 }
1997 if (outputDeepBuffer != 0) {
1998 return outputDeepBuffer;
1999 }
2000
2001 return outputs[0];
2002}
2003
Eric Laurente0720872014-03-11 09:30:41 -07002004audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002005{
2006 // apply simple rule where global effects are attached to the same output as MUSIC streams
2007
Eric Laurent3b73df72014-03-11 09:06:29 -07002008 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002009 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2010 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2011
2012 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2013 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2014 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2015
2016 return output;
2017}
2018
Eric Laurente0720872014-03-11 09:30:41 -07002019status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002020 audio_io_handle_t io,
2021 uint32_t strategy,
2022 int session,
2023 int id)
2024{
2025 ssize_t index = mOutputs.indexOfKey(io);
2026 if (index < 0) {
2027 index = mInputs.indexOfKey(io);
2028 if (index < 0) {
2029 ALOGW("registerEffect() unknown io %d", io);
2030 return INVALID_OPERATION;
2031 }
2032 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002033 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002034}
2035
Eric Laurentc75307b2015-03-17 15:29:32 -07002036bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2037{
2038 return mOutputs.isStreamActive(stream, inPastMs);
2039}
2040
2041bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2042{
2043 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2044}
2045
Eric Laurente0720872014-03-11 09:30:41 -07002046bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002047{
2048 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002049 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002050 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002051 return true;
2052 }
2053 }
2054 return false;
2055}
2056
Eric Laurent275e8e92014-11-30 15:14:47 -08002057// Register a list of custom mixes with their attributes and format.
2058// When a mix is registered, corresponding input and output profiles are
2059// added to the remote submix hw module. The profile contains only the
2060// parameters (sampling rate, format...) specified by the mix.
2061// The corresponding input remote submix device is also connected.
2062//
2063// When a remote submix device is connected, the address is checked to select the
2064// appropriate profile and the corresponding input or output stream is opened.
2065//
2066// When capture starts, getInputForAttr() will:
2067// - 1 look for a mix matching the address passed in attribtutes tags if any
2068// - 2 if none found, getDeviceForInputSource() will:
2069// - 2.1 look for a mix matching the attributes source
2070// - 2.2 if none found, default to device selection by policy rules
2071// At this time, the corresponding output remote submix device is also connected
2072// and active playback use cases can be transferred to this mix if needed when reconnecting
2073// after AudioTracks are invalidated
2074//
2075// When playback starts, getOutputForAttr() will:
2076// - 1 look for a mix matching the address passed in attribtutes tags if any
2077// - 2 if none found, look for a mix matching the attributes usage
2078// - 3 if none found, default to device and output selection by policy rules.
2079
2080status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2081{
2082 sp<HwModule> module;
2083 for (size_t i = 0; i < mHwModules.size(); i++) {
2084 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2085 mHwModules[i]->mHandle != 0) {
2086 module = mHwModules[i];
2087 break;
2088 }
2089 }
2090
2091 if (module == 0) {
2092 return INVALID_OPERATION;
2093 }
2094
Eric Laurent7b279bb2015-12-14 10:18:23 -08002095 ALOGV("registerPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002096
2097 for (size_t i = 0; i < mixes.size(); i++) {
2098 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01002099
2100 if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002101 continue;
2102 }
2103 audio_config_t outputConfig = mixes[i].mFormat;
2104 audio_config_t inputConfig = mixes[i].mFormat;
2105 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2106 // stereo and let audio flinger do the channel conversion if needed.
2107 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2108 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2109 module->addOutputProfile(address, &outputConfig,
2110 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2111 module->addInputProfile(address, &inputConfig,
2112 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002113
Eric Laurentc722f302014-12-10 11:21:49 -08002114 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002115 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002116 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002117 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002118 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002119 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002120 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002121 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002122 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002123 }
2124 return NO_ERROR;
2125}
2126
2127status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2128{
2129 sp<HwModule> module;
2130 for (size_t i = 0; i < mHwModules.size(); i++) {
2131 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2132 mHwModules[i]->mHandle != 0) {
2133 module = mHwModules[i];
2134 break;
2135 }
2136 }
2137
2138 if (module == 0) {
2139 return INVALID_OPERATION;
2140 }
2141
Eric Laurent7b279bb2015-12-14 10:18:23 -08002142 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002143
2144 for (size_t i = 0; i < mixes.size(); i++) {
2145 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01002146
2147 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002148 continue;
2149 }
2150
Eric Laurentc722f302014-12-10 11:21:49 -08002151 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2152 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2153 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002154 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002155 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002156 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002157 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002158
2159 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2160 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2161 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002162 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002163 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002164 address.string(), "remote-submix");
Eric Laurent275e8e92014-11-30 15:14:47 -08002165 }
2166 module->removeOutputProfile(address);
2167 module->removeInputProfile(address);
2168 }
2169 return NO_ERROR;
2170}
2171
Eric Laurente552edb2014-03-10 17:42:56 -07002172
Eric Laurente0720872014-03-11 09:30:41 -07002173status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002174{
2175 const size_t SIZE = 256;
2176 char buffer[SIZE];
2177 String8 result;
2178
2179 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2180 result.append(buffer);
2181
Eric Laurent87ffa392015-05-22 10:32:38 -07002182 snprintf(buffer, SIZE, " Primary Output: %d\n",
2183 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002184 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002185 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002186 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002187 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002188 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002189 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002190 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002191 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002192 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002193 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002194 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002195 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002196 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002197 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002198 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002199 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002200 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002201 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2202 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2203 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002204 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2205 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002206 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2207 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002208
François Gaffie2110e042015-03-24 08:41:51 +01002209 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002210
François Gaffie112b0af2015-11-19 16:13:25 +01002211 mAvailableOutputDevices.dump(fd, String8("Available output"));
2212 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002213 mHwModules.dump(fd);
2214 mOutputs.dump(fd);
2215 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002216 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002217 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002218 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002219
2220 return NO_ERROR;
2221}
2222
2223// This function checks for the parameters which can be offloaded.
2224// This can be enhanced depending on the capability of the DSP and policy
2225// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002226bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002227{
2228 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002229 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002230 offloadInfo.sample_rate, offloadInfo.channel_mask,
2231 offloadInfo.format,
2232 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2233 offloadInfo.has_video);
2234
Andy Hung2ddee192015-12-18 17:34:44 -08002235 if (mMasterMono) {
2236 return false; // no offloading if mono is set.
2237 }
2238
Eric Laurente552edb2014-03-10 17:42:56 -07002239 // Check if offload has been disabled
2240 char propValue[PROPERTY_VALUE_MAX];
2241 if (property_get("audio.offload.disable", propValue, "0")) {
2242 if (atoi(propValue) != 0) {
2243 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2244 return false;
2245 }
2246 }
2247
2248 // Check if stream type is music, then only allow offload as of now.
2249 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2250 {
2251 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2252 return false;
2253 }
2254
Wei Jia7b8d4342016-02-16 17:56:37 -08002255 // Check if streaming is off, then only allow offload as of now.
Wei Jia4ca44d72016-02-17 16:56:38 -08002256 // This is a temporary work around until the root cause is fixed in offload
2257 // playback path.
Wei Jia7b8d4342016-02-16 17:56:37 -08002258 if (offloadInfo.is_streaming)
2259 {
2260 ALOGV("isOffloadSupported: is_streaming == true, returning false");
2261 return false;
2262 }
2263
Eric Laurente552edb2014-03-10 17:42:56 -07002264 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002265 const bool allowOffloadWithVideo =
2266 property_get_bool("audio.offload.video", false /* default_value */);
2267 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002268 ALOGV("isOffloadSupported: has_video == true, returning false");
2269 return false;
2270 }
2271
2272 //If duration is less than minimum value defined in property, return false
2273 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2274 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2275 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2276 return false;
2277 }
2278 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2279 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2280 return false;
2281 }
2282
2283 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2284 // creating an offloaded track and tearing it down immediately after start when audioflinger
2285 // detects there is an active non offloadable effect.
2286 // FIXME: We should check the audio session here but we do not have it in this context.
2287 // This may prevent offloading in rare situations where effects are left active by apps
2288 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002289 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002290 return false;
2291 }
2292
2293 // See if there is a profile to support this.
2294 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002295 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002296 offloadInfo.sample_rate,
2297 offloadInfo.format,
2298 offloadInfo.channel_mask,
2299 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002300 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2301 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002302}
2303
Eric Laurent6a94d692014-05-20 11:18:06 -07002304status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2305 audio_port_type_t type,
2306 unsigned int *num_ports,
2307 struct audio_port *ports,
2308 unsigned int *generation)
2309{
2310 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2311 generation == NULL) {
2312 return BAD_VALUE;
2313 }
2314 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2315 if (ports == NULL) {
2316 *num_ports = 0;
2317 }
2318
2319 size_t portsWritten = 0;
2320 size_t portsMax = *num_ports;
2321 *num_ports = 0;
2322 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2323 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2324 for (size_t i = 0;
2325 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2326 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2327 }
2328 *num_ports += mAvailableOutputDevices.size();
2329 }
2330 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2331 for (size_t i = 0;
2332 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2333 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2334 }
2335 *num_ports += mAvailableInputDevices.size();
2336 }
2337 }
2338 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2339 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2340 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2341 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2342 }
2343 *num_ports += mInputs.size();
2344 }
2345 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002346 size_t numOutputs = 0;
2347 for (size_t i = 0; i < mOutputs.size(); i++) {
2348 if (!mOutputs[i]->isDuplicated()) {
2349 numOutputs++;
2350 if (portsWritten < portsMax) {
2351 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2352 }
2353 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002354 }
Eric Laurent84c70242014-06-23 08:46:27 -07002355 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002356 }
2357 }
2358 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002359 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002360 return NO_ERROR;
2361}
2362
2363status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2364{
2365 return NO_ERROR;
2366}
2367
Eric Laurent6a94d692014-05-20 11:18:06 -07002368status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2369 audio_patch_handle_t *handle,
2370 uid_t uid)
2371{
2372 ALOGV("createAudioPatch()");
2373
2374 if (handle == NULL || patch == NULL) {
2375 return BAD_VALUE;
2376 }
2377 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2378
Eric Laurent874c42872014-08-08 15:13:39 -07002379 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2380 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2381 return BAD_VALUE;
2382 }
2383 // only one source per audio patch supported for now
2384 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002385 return INVALID_OPERATION;
2386 }
Eric Laurent874c42872014-08-08 15:13:39 -07002387
2388 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002389 return INVALID_OPERATION;
2390 }
Eric Laurent874c42872014-08-08 15:13:39 -07002391 for (size_t i = 0; i < patch->num_sinks; i++) {
2392 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2393 return INVALID_OPERATION;
2394 }
2395 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002396
2397 sp<AudioPatch> patchDesc;
2398 ssize_t index = mAudioPatches.indexOfKey(*handle);
2399
Eric Laurent6a94d692014-05-20 11:18:06 -07002400 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2401 patch->sources[0].role,
2402 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002403#if LOG_NDEBUG == 0
2404 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002405 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002406 patch->sinks[i].role,
2407 patch->sinks[i].type);
2408 }
2409#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002410
2411 if (index >= 0) {
2412 patchDesc = mAudioPatches.valueAt(index);
2413 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2414 mUidCached, patchDesc->mUid, uid);
2415 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2416 return INVALID_OPERATION;
2417 }
2418 } else {
2419 *handle = 0;
2420 }
2421
2422 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002423 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002424 if (outputDesc == NULL) {
2425 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2426 return BAD_VALUE;
2427 }
Eric Laurent84c70242014-06-23 08:46:27 -07002428 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2429 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002430 if (patchDesc != 0) {
2431 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2432 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2433 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2434 return BAD_VALUE;
2435 }
2436 }
Eric Laurent874c42872014-08-08 15:13:39 -07002437 DeviceVector devices;
2438 for (size_t i = 0; i < patch->num_sinks; i++) {
2439 // Only support mix to devices connection
2440 // TODO add support for mix to mix connection
2441 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2442 ALOGV("createAudioPatch() source mix but sink is not a device");
2443 return INVALID_OPERATION;
2444 }
2445 sp<DeviceDescriptor> devDesc =
2446 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2447 if (devDesc == 0) {
2448 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2449 return BAD_VALUE;
2450 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002451
François Gaffie53615e22015-03-19 09:24:12 +01002452 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002453 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002454 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002455 NULL, // updatedSamplingRate
2456 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002457 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002458 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002459 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002460 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002461 ALOGV("createAudioPatch() profile not supported for device %08x",
2462 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002463 return INVALID_OPERATION;
2464 }
2465 devices.add(devDesc);
2466 }
2467 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002468 return INVALID_OPERATION;
2469 }
Eric Laurent874c42872014-08-08 15:13:39 -07002470
Eric Laurent6a94d692014-05-20 11:18:06 -07002471 // TODO: reconfigure output format and channels here
2472 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002473 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002474 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 index = mAudioPatches.indexOfKey(*handle);
2476 if (index >= 0) {
2477 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2478 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2479 }
2480 patchDesc = mAudioPatches.valueAt(index);
2481 patchDesc->mUid = uid;
2482 ALOGV("createAudioPatch() success");
2483 } else {
2484 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2485 return INVALID_OPERATION;
2486 }
2487 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2488 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2489 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002490 // only one sink supported when connecting an input device to a mix
2491 if (patch->num_sinks > 1) {
2492 return INVALID_OPERATION;
2493 }
François Gaffie53615e22015-03-19 09:24:12 +01002494 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002495 if (inputDesc == NULL) {
2496 return BAD_VALUE;
2497 }
2498 if (patchDesc != 0) {
2499 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2500 return BAD_VALUE;
2501 }
2502 }
2503 sp<DeviceDescriptor> devDesc =
2504 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2505 if (devDesc == 0) {
2506 return BAD_VALUE;
2507 }
2508
François Gaffie53615e22015-03-19 09:24:12 +01002509 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002510 devDesc->mAddress,
2511 patch->sinks[0].sample_rate,
2512 NULL, /*updatedSampleRate*/
2513 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002514 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002515 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002516 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002517 // FIXME for the parameter type,
2518 // and the NONE
2519 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002520 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002521 return INVALID_OPERATION;
2522 }
2523 // TODO: reconfigure output format and channels here
2524 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002525 devDesc->type(), inputDesc->mIoHandle);
2526 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002527 index = mAudioPatches.indexOfKey(*handle);
2528 if (index >= 0) {
2529 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2530 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2531 }
2532 patchDesc = mAudioPatches.valueAt(index);
2533 patchDesc->mUid = uid;
2534 ALOGV("createAudioPatch() success");
2535 } else {
2536 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2537 return INVALID_OPERATION;
2538 }
2539 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2540 // device to device connection
2541 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002542 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002543 return BAD_VALUE;
2544 }
2545 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002546 sp<DeviceDescriptor> srcDeviceDesc =
2547 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002548 if (srcDeviceDesc == 0) {
2549 return BAD_VALUE;
2550 }
Eric Laurent874c42872014-08-08 15:13:39 -07002551
Eric Laurent6a94d692014-05-20 11:18:06 -07002552 //update source and sink with our own data as the data passed in the patch may
2553 // be incomplete.
2554 struct audio_patch newPatch = *patch;
2555 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002556
Eric Laurent874c42872014-08-08 15:13:39 -07002557 for (size_t i = 0; i < patch->num_sinks; i++) {
2558 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2559 ALOGV("createAudioPatch() source device but one sink is not a device");
2560 return INVALID_OPERATION;
2561 }
2562
2563 sp<DeviceDescriptor> sinkDeviceDesc =
2564 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2565 if (sinkDeviceDesc == 0) {
2566 return BAD_VALUE;
2567 }
2568 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2569
Eric Laurent3bcf8592015-04-03 12:13:24 -07002570 // create a software bridge in PatchPanel if:
2571 // - source and sink devices are on differnt HW modules OR
2572 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002573 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002574 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002575 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002576 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002577 return INVALID_OPERATION;
2578 }
Eric Laurent874c42872014-08-08 15:13:39 -07002579 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002580 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002581 // if the sink device is reachable via an opened output stream, request to go via
2582 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002583 audio_io_handle_t output = selectOutput(outputs,
2584 AUDIO_OUTPUT_FLAG_NONE,
2585 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002586 if (output != AUDIO_IO_HANDLE_NONE) {
2587 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2588 if (outputDesc->isDuplicated()) {
2589 return INVALID_OPERATION;
2590 }
2591 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002592 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002593 newPatch.num_sources = 2;
2594 }
Eric Laurent83b88082014-06-20 18:31:16 -07002595 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002596 }
2597 // TODO: check from routing capabilities in config file and other conflicting patches
2598
2599 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2600 if (index >= 0) {
2601 afPatchHandle = patchDesc->mAfPatchHandle;
2602 }
2603
2604 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2605 &afPatchHandle,
2606 0);
2607 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2608 status, afPatchHandle);
2609 if (status == NO_ERROR) {
2610 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002611 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002612 addAudioPatch(patchDesc->mHandle, patchDesc);
2613 } else {
2614 patchDesc->mPatch = newPatch;
2615 }
2616 patchDesc->mAfPatchHandle = afPatchHandle;
2617 *handle = patchDesc->mHandle;
2618 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002619 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002620 } else {
2621 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2622 status);
2623 return INVALID_OPERATION;
2624 }
2625 } else {
2626 return BAD_VALUE;
2627 }
2628 } else {
2629 return BAD_VALUE;
2630 }
2631 return NO_ERROR;
2632}
2633
2634status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2635 uid_t uid)
2636{
2637 ALOGV("releaseAudioPatch() patch %d", handle);
2638
2639 ssize_t index = mAudioPatches.indexOfKey(handle);
2640
2641 if (index < 0) {
2642 return BAD_VALUE;
2643 }
2644 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2645 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2646 mUidCached, patchDesc->mUid, uid);
2647 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2648 return INVALID_OPERATION;
2649 }
2650
2651 struct audio_patch *patch = &patchDesc->mPatch;
2652 patchDesc->mUid = mUidCached;
2653 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002654 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002655 if (outputDesc == NULL) {
2656 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2657 return BAD_VALUE;
2658 }
2659
Eric Laurentc75307b2015-03-17 15:29:32 -07002660 setOutputDevice(outputDesc,
2661 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002662 true,
2663 0,
2664 NULL);
2665 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2666 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002667 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002668 if (inputDesc == NULL) {
2669 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2670 return BAD_VALUE;
2671 }
2672 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002673 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002674 true,
2675 NULL);
2676 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2677 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2678 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2679 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2680 status, patchDesc->mAfPatchHandle);
2681 removeAudioPatch(patchDesc->mHandle);
2682 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002683 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002684 } else {
2685 return BAD_VALUE;
2686 }
2687 } else {
2688 return BAD_VALUE;
2689 }
2690 return NO_ERROR;
2691}
2692
2693status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2694 struct audio_patch *patches,
2695 unsigned int *generation)
2696{
François Gaffie53615e22015-03-19 09:24:12 +01002697 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002698 return BAD_VALUE;
2699 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002700 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002701 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002702}
2703
Eric Laurente1715a42014-05-20 11:30:42 -07002704status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002705{
Eric Laurente1715a42014-05-20 11:30:42 -07002706 ALOGV("setAudioPortConfig()");
2707
2708 if (config == NULL) {
2709 return BAD_VALUE;
2710 }
2711 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2712 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002713 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2714 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002715 }
2716
Eric Laurenta121f902014-06-03 13:32:54 -07002717 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002718 if (config->type == AUDIO_PORT_TYPE_MIX) {
2719 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002720 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002721 if (outputDesc == NULL) {
2722 return BAD_VALUE;
2723 }
Eric Laurent84c70242014-06-23 08:46:27 -07002724 ALOG_ASSERT(!outputDesc->isDuplicated(),
2725 "setAudioPortConfig() called on duplicated output %d",
2726 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002727 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002728 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002729 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002730 if (inputDesc == NULL) {
2731 return BAD_VALUE;
2732 }
Eric Laurenta121f902014-06-03 13:32:54 -07002733 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002734 } else {
2735 return BAD_VALUE;
2736 }
2737 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2738 sp<DeviceDescriptor> deviceDesc;
2739 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2740 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2741 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2742 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2743 } else {
2744 return BAD_VALUE;
2745 }
2746 if (deviceDesc == NULL) {
2747 return BAD_VALUE;
2748 }
Eric Laurenta121f902014-06-03 13:32:54 -07002749 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002750 } else {
2751 return BAD_VALUE;
2752 }
2753
Eric Laurenta121f902014-06-03 13:32:54 -07002754 struct audio_port_config backupConfig;
2755 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2756 if (status == NO_ERROR) {
2757 struct audio_port_config newConfig;
2758 audioPortConfig->toAudioPortConfig(&newConfig, config);
2759 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002760 }
Eric Laurenta121f902014-06-03 13:32:54 -07002761 if (status != NO_ERROR) {
2762 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002763 }
Eric Laurente1715a42014-05-20 11:30:42 -07002764
2765 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002766}
2767
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002768void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2769{
Eric Laurentd60560a2015-04-10 11:31:20 -07002770 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002771 clearAudioPatches(uid);
2772 clearSessionRoutes(uid);
2773}
2774
Eric Laurent6a94d692014-05-20 11:18:06 -07002775void AudioPolicyManager::clearAudioPatches(uid_t uid)
2776{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002777 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002778 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2779 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002780 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002781 }
2782 }
2783}
2784
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002785void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2786 audio_io_handle_t ouptutToSkip)
2787{
2788 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2789 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2790 for (size_t j = 0; j < mOutputs.size(); j++) {
2791 if (mOutputs.keyAt(j) == ouptutToSkip) {
2792 continue;
2793 }
2794 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2795 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2796 continue;
2797 }
2798 // If the default device for this strategy is on another output mix,
2799 // invalidate all tracks in this strategy to force re connection.
2800 // Otherwise select new device on the output mix.
2801 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
2802 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
2803 if (stream == AUDIO_STREAM_PATCH) {
2804 continue;
2805 }
2806 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2807 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2808 }
2809 }
2810 } else {
2811 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2812 setOutputDevice(outputDesc, newDevice, false);
2813 }
2814 }
2815}
2816
2817void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2818{
2819 // remove output routes associated with this uid
2820 SortedVector<routing_strategy> affectedStrategies;
2821 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2822 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2823 if (route->mUid == uid) {
2824 mOutputRoutes.removeItemsAt(i);
2825 if (route->mDeviceDescriptor != 0) {
2826 affectedStrategies.add(getStrategy(route->mStreamType));
2827 }
2828 }
2829 }
2830 // reroute outputs if necessary
2831 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2832 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2833 }
2834
2835 // remove input routes associated with this uid
2836 SortedVector<audio_source_t> affectedSources;
2837 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2838 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2839 if (route->mUid == uid) {
2840 mInputRoutes.removeItemsAt(i);
2841 if (route->mDeviceDescriptor != 0) {
2842 affectedSources.add(route->mSource);
2843 }
2844 }
2845 }
2846 // reroute inputs if necessary
2847 SortedVector<audio_io_handle_t> inputsToClose;
2848 for (size_t i = 0; i < mInputs.size(); i++) {
2849 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002850 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002851 inputsToClose.add(inputDesc->mIoHandle);
2852 }
2853 }
2854 for (size_t i = 0; i < inputsToClose.size(); i++) {
2855 closeInput(inputsToClose[i]);
2856 }
2857}
2858
Eric Laurentd60560a2015-04-10 11:31:20 -07002859void AudioPolicyManager::clearAudioSources(uid_t uid)
2860{
2861 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2862 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2863 if (sourceDesc->mUid == uid) {
2864 stopAudioSource(mAudioSources.keyAt(i));
2865 }
2866 }
2867}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002868
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002869status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2870 audio_io_handle_t *ioHandle,
2871 audio_devices_t *device)
2872{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08002873 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2874 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002875 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002876
François Gaffiedf372692015-03-19 10:43:27 +01002877 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002878}
2879
Eric Laurentd60560a2015-04-10 11:31:20 -07002880status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2881 const audio_attributes_t *attributes,
2882 audio_io_handle_t *handle,
2883 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002884{
Eric Laurentd60560a2015-04-10 11:31:20 -07002885 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2886 if (source == NULL || attributes == NULL || handle == NULL) {
2887 return BAD_VALUE;
2888 }
2889
2890 *handle = AUDIO_IO_HANDLE_NONE;
2891
2892 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2893 source->type != AUDIO_PORT_TYPE_DEVICE) {
2894 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2895 return INVALID_OPERATION;
2896 }
2897
2898 sp<DeviceDescriptor> srcDeviceDesc =
2899 mAvailableInputDevices.getDevice(source->ext.device.type,
2900 String8(source->ext.device.address));
2901 if (srcDeviceDesc == 0) {
2902 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2903 return BAD_VALUE;
2904 }
2905 sp<AudioSourceDescriptor> sourceDesc =
2906 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2907
2908 struct audio_patch dummyPatch;
2909 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2910 sourceDesc->mPatchDesc = patchDesc;
2911
2912 status_t status = connectAudioSource(sourceDesc);
2913 if (status == NO_ERROR) {
2914 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2915 *handle = sourceDesc->getHandle();
2916 }
2917 return status;
2918}
2919
2920status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2921{
2922 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2923
2924 // make sure we only have one patch per source.
2925 disconnectAudioSource(sourceDesc);
2926
2927 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2928 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2929 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2930
2931 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2932 sp<DeviceDescriptor> sinkDeviceDesc =
2933 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2934
2935 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2936 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2937
2938 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2939 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002940 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002941 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2942 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2943 // create patch between src device and output device
2944 // create Hwoutput and add to mHwOutputs
2945 } else {
2946 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2947 audio_io_handle_t output =
2948 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2949 if (output == AUDIO_IO_HANDLE_NONE) {
2950 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2951 return INVALID_OPERATION;
2952 }
2953 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2954 if (outputDesc->isDuplicated()) {
2955 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2956 return INVALID_OPERATION;
2957 }
2958 // create a special patch with no sink and two sources:
2959 // - the second source indicates to PatchPanel through which output mix this patch should
2960 // be connected as well as the stream type for volume control
2961 // - the sink is defined by whatever output device is currently selected for the output
2962 // though which this patch is routed.
2963 patch->num_sinks = 0;
2964 patch->num_sources = 2;
2965 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2966 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2967 patch->sources[1].ext.mix.usecase.stream = stream;
2968 status_t status = mpClientInterface->createAudioPatch(patch,
2969 &afPatchHandle,
2970 0);
2971 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
2972 status, afPatchHandle);
2973 if (status != NO_ERROR) {
2974 ALOGW("%s patch panel could not connect device patch, error %d",
2975 __FUNCTION__, status);
2976 return INVALID_OPERATION;
2977 }
2978 uint32_t delayMs = 0;
2979 status = startSource(outputDesc, stream, sinkDevice, &delayMs);
2980
2981 if (status != NO_ERROR) {
2982 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
2983 return status;
2984 }
2985 sourceDesc->mSwOutput = outputDesc;
2986 if (delayMs != 0) {
2987 usleep(delayMs * 1000);
2988 }
2989 }
2990
2991 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
2992 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
2993
2994 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07002995}
2996
Eric Laurent493404d2015-04-21 15:07:36 -07002997status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07002998{
Eric Laurentd60560a2015-04-10 11:31:20 -07002999 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3000 ALOGV("%s handle %d", __FUNCTION__, handle);
3001 if (sourceDesc == 0) {
3002 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3003 return BAD_VALUE;
3004 }
3005 status_t status = disconnectAudioSource(sourceDesc);
3006
3007 mAudioSources.removeItem(handle);
3008 return status;
3009}
3010
Andy Hung2ddee192015-12-18 17:34:44 -08003011status_t AudioPolicyManager::setMasterMono(bool mono)
3012{
3013 if (mMasterMono == mono) {
3014 return NO_ERROR;
3015 }
3016 mMasterMono = mono;
3017 // if enabling mono we close all offloaded devices, which will invalidate the
3018 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3019 // for recreating the new AudioTrack as non-offloaded PCM.
3020 //
3021 // If disabling mono, we leave all tracks as is: we don't know which clients
3022 // and tracks are able to be recreated as offloaded. The next "song" should
3023 // play back offloaded.
3024 if (mMasterMono) {
3025 Vector<audio_io_handle_t> offloaded;
3026 for (size_t i = 0; i < mOutputs.size(); ++i) {
3027 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3028 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3029 offloaded.push(desc->mIoHandle);
3030 }
3031 }
3032 for (size_t i = 0; i < offloaded.size(); ++i) {
3033 closeOutput(offloaded[i]);
3034 }
3035 }
3036 // update master mono for all remaining outputs
3037 for (size_t i = 0; i < mOutputs.size(); ++i) {
3038 updateMono(mOutputs.keyAt(i));
3039 }
3040 return NO_ERROR;
3041}
3042
3043status_t AudioPolicyManager::getMasterMono(bool *mono)
3044{
3045 *mono = mMasterMono;
3046 return NO_ERROR;
3047}
3048
Eric Laurentd60560a2015-04-10 11:31:20 -07003049status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3050{
3051 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3052
3053 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3054 if (patchDesc == 0) {
3055 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3056 sourceDesc->mPatchDesc->mHandle);
3057 return BAD_VALUE;
3058 }
3059 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3060
3061 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
3062 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3063 if (swOutputDesc != 0) {
3064 stopSource(swOutputDesc, stream, false);
3065 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3066 } else {
3067 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3068 if (hwOutputDesc != 0) {
3069 // release patch between src device and output device
3070 // close Hwoutput and remove from mHwOutputs
3071 } else {
3072 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3073 }
3074 }
3075 return NO_ERROR;
3076}
3077
3078sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3079 audio_io_handle_t output, routing_strategy strategy)
3080{
3081 sp<AudioSourceDescriptor> source;
3082 for (size_t i = 0; i < mAudioSources.size(); i++) {
3083 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3084 routing_strategy sourceStrategy =
3085 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3086 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3087 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3088 source = sourceDesc;
3089 break;
3090 }
3091 }
3092 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003093}
3094
Eric Laurente552edb2014-03-10 17:42:56 -07003095// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003096// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003097// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003098uint32_t AudioPolicyManager::nextAudioPortGeneration()
3099{
3100 return android_atomic_inc(&mAudioPortGeneration);
3101}
3102
Eric Laurente0720872014-03-11 09:30:41 -07003103AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003104 :
3105#ifdef AUDIO_POLICY_TEST
3106 Thread(false),
3107#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003108 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003109 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003110 mAudioPortGeneration(1),
3111 mBeaconMuteRefCount(0),
3112 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003113 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003114 mTtsOutputAvailable(false),
3115 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003116{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003117 mUidCached = getuid();
3118 mpClientInterface = clientInterface;
3119
3120 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3121 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3122 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3123 bool speakerDrcEnabled = false;
3124
3125#ifdef USE_XML_AUDIO_POLICY_CONF
3126 mVolumeCurves = new VolumeCurvesCollection();
3127 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3128 mDefaultOutputDevice, speakerDrcEnabled,
3129 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3130 PolicySerializer serializer;
3131 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3132#else
3133 mVolumeCurves = new StreamDescriptorCollection();
3134 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3135 mDefaultOutputDevice, speakerDrcEnabled);
3136 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3137 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3138#endif
3139 ALOGE("could not load audio policy configuration file, setting defaults");
3140 config.setDefault();
3141 }
3142 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3143 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3144
3145 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003146 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3147 if (!engineInstance) {
3148 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3149 return;
3150 }
3151 // Retrieve the Policy Manager Interface
3152 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3153 if (mEngine == NULL) {
3154 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3155 return;
3156 }
3157 mEngine->setObserver(this);
3158 status_t status = mEngine->initCheck();
3159 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3160
Eric Laurent3a4311c2014-03-17 12:00:47 -07003161 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003162 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003163 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3164 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003165 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003166 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003167 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003168 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003169 continue;
3170 }
3171 // open all output streams needed to access attached devices
3172 // except for direct output streams that are only opened when they are actually
3173 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003174 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003175 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3176 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003177 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003178
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003179 if (!outProfile->hasSupportedDevices()) {
3180 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003181 continue;
3182 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003183 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003184 mTtsOutputAvailable = true;
3185 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003186
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003187 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003188 continue;
3189 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003190 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003191 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3192 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003193 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003194 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003195 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003196 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003197 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003198 if ((profileType & outputDeviceTypes) == 0) {
3199 continue;
3200 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003201 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3202 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003203
3204 outputDesc->mDevice = profileType;
3205 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3206 config.sample_rate = outputDesc->mSamplingRate;
3207 config.channel_mask = outputDesc->mChannelMask;
3208 config.format = outputDesc->mFormat;
3209 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003210 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003211 &output,
3212 &config,
3213 &outputDesc->mDevice,
3214 String8(""),
3215 &outputDesc->mLatency,
3216 outputDesc->mFlags);
3217
3218 if (status != NO_ERROR) {
3219 ALOGW("Cannot open output stream for device %08x on hw module %s",
3220 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003221 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003222 } else {
3223 outputDesc->mSamplingRate = config.sample_rate;
3224 outputDesc->mChannelMask = config.channel_mask;
3225 outputDesc->mFormat = config.format;
3226
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003227 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3228 for (size_t k = 0; k < supportedDevices.size(); k++) {
3229 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003230 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003231 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3232 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003233 }
3234 }
3235 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003236 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003237 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003238 }
3239 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003240 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003241 outputDesc->mDevice,
3242 true);
3243 }
Eric Laurente552edb2014-03-10 17:42:56 -07003244 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003245 // open input streams needed to access attached devices to validate
3246 // mAvailableInputDevices list
3247 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3248 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003249 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003250
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003251 if (!inProfile->hasSupportedDevices()) {
3252 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003253 continue;
3254 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003255 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003256 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003257 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3258
Eric Laurentd78f1532014-09-16 16:38:20 -07003259 if ((profileType & inputDeviceTypes) == 0) {
3260 continue;
3261 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003262 sp<AudioInputDescriptor> inputDesc =
3263 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003264
Eric Laurentd78f1532014-09-16 16:38:20 -07003265 inputDesc->mDevice = profileType;
3266
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003267 // find the address
3268 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3269 // the inputs vector must be of size 1, but we don't want to crash here
3270 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3271 : String8("");
3272 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3273 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3274
Eric Laurentd78f1532014-09-16 16:38:20 -07003275 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3276 config.sample_rate = inputDesc->mSamplingRate;
3277 config.channel_mask = inputDesc->mChannelMask;
3278 config.format = inputDesc->mFormat;
3279 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003280 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003281 &input,
3282 &config,
3283 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003284 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003285 AUDIO_SOURCE_MIC,
3286 AUDIO_INPUT_FLAG_NONE);
3287
3288 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003289 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3290 for (size_t k = 0; k < supportedDevices.size(); k++) {
3291 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003292 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003293 if (index >= 0) {
3294 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3295 if (!devDesc->isAttached()) {
3296 devDesc->attach(mHwModules[i]);
3297 devDesc->importAudioPort(inProfile);
3298 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003299 }
3300 }
3301 mpClientInterface->closeInput(input);
3302 } else {
3303 ALOGW("Cannot open input stream for device %08x on hw module %s",
3304 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003305 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003306 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003307 }
3308 }
3309 // make sure all attached devices have been allocated a unique ID
3310 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003311 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003312 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003313 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3314 continue;
3315 }
François Gaffie2110e042015-03-24 08:41:51 +01003316 // The device is now validated and can be appended to the available devices of the engine
3317 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3318 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003319 i++;
3320 }
3321 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003322 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003323 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003324 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3325 continue;
3326 }
François Gaffie2110e042015-03-24 08:41:51 +01003327 // The device is now validated and can be appended to the available devices of the engine
3328 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3329 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003330 i++;
3331 }
3332 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003333 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003334 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003335 }
Eric Laurente552edb2014-03-10 17:42:56 -07003336
3337 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3338
3339 updateDevicesAndOutputs();
3340
3341#ifdef AUDIO_POLICY_TEST
3342 if (mPrimaryOutput != 0) {
3343 AudioParameter outputCmd = AudioParameter();
3344 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003345 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003346
3347 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3348 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003349 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3350 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003351 mTestLatencyMs = 0;
3352 mCurOutput = 0;
3353 mDirectOutput = false;
3354 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3355 mTestOutputs[i] = 0;
3356 }
3357
3358 const size_t SIZE = 256;
3359 char buffer[SIZE];
3360 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3361 run(buffer, ANDROID_PRIORITY_AUDIO);
3362 }
3363#endif //AUDIO_POLICY_TEST
3364}
3365
Eric Laurente0720872014-03-11 09:30:41 -07003366AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003367{
3368#ifdef AUDIO_POLICY_TEST
3369 exit();
3370#endif //AUDIO_POLICY_TEST
3371 for (size_t i = 0; i < mOutputs.size(); i++) {
3372 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003373 }
3374 for (size_t i = 0; i < mInputs.size(); i++) {
3375 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003376 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003377 mAvailableOutputDevices.clear();
3378 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003379 mOutputs.clear();
3380 mInputs.clear();
3381 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003382}
3383
Eric Laurente0720872014-03-11 09:30:41 -07003384status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003385{
Eric Laurent87ffa392015-05-22 10:32:38 -07003386 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003387}
3388
3389#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003390bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003391{
3392 ALOGV("entering threadLoop()");
3393 while (!exitPending())
3394 {
3395 String8 command;
3396 int valueInt;
3397 String8 value;
3398
3399 Mutex::Autolock _l(mLock);
3400 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3401
3402 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3403 AudioParameter param = AudioParameter(command);
3404
3405 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3406 valueInt != 0) {
3407 ALOGV("Test command %s received", command.string());
3408 String8 target;
3409 if (param.get(String8("target"), target) != NO_ERROR) {
3410 target = "Manager";
3411 }
3412 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3413 param.remove(String8("test_cmd_policy_output"));
3414 mCurOutput = valueInt;
3415 }
3416 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3417 param.remove(String8("test_cmd_policy_direct"));
3418 if (value == "false") {
3419 mDirectOutput = false;
3420 } else if (value == "true") {
3421 mDirectOutput = true;
3422 }
3423 }
3424 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3425 param.remove(String8("test_cmd_policy_input"));
3426 mTestInput = valueInt;
3427 }
3428
3429 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3430 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003431 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003432 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003433 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003434 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003435 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003436 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003437 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003438 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003439 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003440 if (target == "Manager") {
3441 mTestFormat = format;
3442 } else if (mTestOutputs[mCurOutput] != 0) {
3443 AudioParameter outputParam = AudioParameter();
3444 outputParam.addInt(String8("format"), format);
3445 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3446 }
3447 }
3448 }
3449 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3450 param.remove(String8("test_cmd_policy_channels"));
3451 int channels = 0;
3452
3453 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003454 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003455 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003456 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003457 }
3458 if (channels != 0) {
3459 if (target == "Manager") {
3460 mTestChannels = channels;
3461 } else if (mTestOutputs[mCurOutput] != 0) {
3462 AudioParameter outputParam = AudioParameter();
3463 outputParam.addInt(String8("channels"), channels);
3464 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3465 }
3466 }
3467 }
3468 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3469 param.remove(String8("test_cmd_policy_sampleRate"));
3470 if (valueInt >= 0 && valueInt <= 96000) {
3471 int samplingRate = valueInt;
3472 if (target == "Manager") {
3473 mTestSamplingRate = samplingRate;
3474 } else if (mTestOutputs[mCurOutput] != 0) {
3475 AudioParameter outputParam = AudioParameter();
3476 outputParam.addInt(String8("sampling_rate"), samplingRate);
3477 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3478 }
3479 }
3480 }
3481
3482 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3483 param.remove(String8("test_cmd_policy_reopen"));
3484
Eric Laurentc75307b2015-03-17 15:29:32 -07003485 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003486
Eric Laurentc75307b2015-03-17 15:29:32 -07003487 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003488
Eric Laurentc75307b2015-03-17 15:29:32 -07003489 removeOutput(mPrimaryOutput->mIoHandle);
3490 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3491 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003492 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003493 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3494 config.sample_rate = outputDesc->mSamplingRate;
3495 config.channel_mask = outputDesc->mChannelMask;
3496 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003497 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003498 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003499 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003500 &config,
3501 &outputDesc->mDevice,
3502 String8(""),
3503 &outputDesc->mLatency,
3504 outputDesc->mFlags);
3505 if (status != NO_ERROR) {
3506 ALOGE("Failed to reopen hardware output stream, "
3507 "samplingRate: %d, format %d, channels %d",
3508 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003509 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003510 outputDesc->mSamplingRate = config.sample_rate;
3511 outputDesc->mChannelMask = config.channel_mask;
3512 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003513 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003514 AudioParameter outputCmd = AudioParameter();
3515 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003516 mpClientInterface->setParameters(handle, outputCmd.toString());
3517 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003518 }
3519 }
3520
3521
3522 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3523 }
3524 }
3525 return false;
3526}
3527
Eric Laurente0720872014-03-11 09:30:41 -07003528void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003529{
3530 {
3531 AutoMutex _l(mLock);
3532 requestExit();
3533 mWaitWorkCV.signal();
3534 }
3535 requestExitAndWait();
3536}
3537
Eric Laurente0720872014-03-11 09:30:41 -07003538int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003539{
3540 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3541 if (output == mTestOutputs[i]) return i;
3542 }
3543 return 0;
3544}
3545#endif //AUDIO_POLICY_TEST
3546
3547// ---
3548
Eric Laurentc75307b2015-03-17 15:29:32 -07003549void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003550{
François Gaffie98cc1912015-03-18 17:52:40 +01003551 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003552 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003553 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003554 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003555}
3556
François Gaffie53615e22015-03-19 09:24:12 +01003557void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3558{
3559 mOutputs.removeItem(output);
3560}
3561
Eric Laurent1f2f2232014-06-02 12:01:23 -07003562void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003563{
François Gaffie98cc1912015-03-18 17:52:40 +01003564 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003565 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003566 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003567}
Eric Laurente552edb2014-03-10 17:42:56 -07003568
Eric Laurentc75307b2015-03-17 15:29:32 -07003569void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003570 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003571 const String8 address /*in*/,
3572 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003573 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003574 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003575 if (devDesc != 0) {
3576 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3577 desc->mIoHandle, address.string());
3578 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003579 }
3580}
3581
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003582status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003583 audio_policy_dev_state_t state,
3584 SortedVector<audio_io_handle_t>& outputs,
3585 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003586{
François Gaffie53615e22015-03-19 09:24:12 +01003587 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003588 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003589
3590 if (audio_device_is_digital(device)) {
3591 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003592 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003593 }
Eric Laurente552edb2014-03-10 17:42:56 -07003594
Eric Laurent3b73df72014-03-11 09:06:29 -07003595 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003596 // first list already open outputs that can be routed to this device
3597 for (size_t i = 0; i < mOutputs.size(); i++) {
3598 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003599 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003600 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003601 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3602 outputs.add(mOutputs.keyAt(i));
3603 } else {
3604 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003605 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003606 }
Eric Laurente552edb2014-03-10 17:42:56 -07003607 }
3608 }
3609 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003610 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003611 for (size_t i = 0; i < mHwModules.size(); i++)
3612 {
3613 if (mHwModules[i]->mHandle == 0) {
3614 continue;
3615 }
3616 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3617 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003618 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003619 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003620 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003621 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003622 profiles.add(profile);
3623 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3624 }
Eric Laurente552edb2014-03-10 17:42:56 -07003625 }
3626 }
3627 }
3628
Eric Laurent7b279bb2015-12-14 10:18:23 -08003629 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003630
Eric Laurente552edb2014-03-10 17:42:56 -07003631 if (profiles.isEmpty() && outputs.isEmpty()) {
3632 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3633 return BAD_VALUE;
3634 }
3635
3636 // open outputs for matching profiles if needed. Direct outputs are also opened to
3637 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3638 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003639 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003640
3641 // nothing to do if one output is already opened for this profile
3642 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003643 for (j = 0; j < outputs.size(); j++) {
3644 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003645 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003646 // matching profile: save the sample rates, format and channel masks supported
3647 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003648 if (audio_device_is_digital(device)) {
3649 devDesc->importAudioPort(profile);
3650 }
Eric Laurente552edb2014-03-10 17:42:56 -07003651 break;
3652 }
3653 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003654 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003655 continue;
3656 }
3657
Eric Laurent83b88082014-06-20 18:31:16 -07003658 ALOGV("opening output for device %08x with params %s profile %p",
3659 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003660 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003661 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003662 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3663 config.sample_rate = desc->mSamplingRate;
3664 config.channel_mask = desc->mChannelMask;
3665 config.format = desc->mFormat;
3666 config.offload_info.sample_rate = desc->mSamplingRate;
3667 config.offload_info.channel_mask = desc->mChannelMask;
3668 config.offload_info.format = desc->mFormat;
3669 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003670 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003671 &output,
3672 &config,
3673 &desc->mDevice,
3674 address,
3675 &desc->mLatency,
3676 desc->mFlags);
3677 if (status == NO_ERROR) {
3678 desc->mSamplingRate = config.sample_rate;
3679 desc->mChannelMask = config.channel_mask;
3680 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003681
Eric Laurentd4692962014-05-05 18:13:44 -07003682 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003683 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003684 char *param = audio_device_address_to_parameter(device, address);
3685 mpClientInterface->setParameters(output, String8(param));
3686 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003687 }
François Gaffie112b0af2015-11-19 16:13:25 +01003688 updateAudioProfiles(output, profile->getAudioProfiles());
3689 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003690 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003691 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003692 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003693 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003694 mpClientInterface->closeOutput(output);
François Gaffie112b0af2015-11-19 16:13:25 +01003695 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003696 config.offload_info.sample_rate = config.sample_rate;
3697 config.offload_info.channel_mask = config.channel_mask;
3698 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003699 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003700 &output,
3701 &config,
3702 &desc->mDevice,
3703 address,
3704 &desc->mLatency,
3705 desc->mFlags);
3706 if (status == NO_ERROR) {
3707 desc->mSamplingRate = config.sample_rate;
3708 desc->mChannelMask = config.channel_mask;
3709 desc->mFormat = config.format;
3710 } else {
3711 output = AUDIO_IO_HANDLE_NONE;
3712 }
Eric Laurentd4692962014-05-05 18:13:44 -07003713 }
3714
Eric Laurentcf2c0212014-07-25 16:20:43 -07003715 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003716 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003717 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003718 sp<AudioPolicyMix> policyMix;
3719 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003720 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3721 address.string());
3722 }
François Gaffie036e1e92015-03-19 10:16:24 +01003723 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003724 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003725
Eric Laurent87ffa392015-05-22 10:32:38 -07003726 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3727 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003728 // no duplicated output for direct outputs and
3729 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003730 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003731
Eric Laurentd4692962014-05-05 18:13:44 -07003732 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003733 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003734
Eric Laurentd4692962014-05-05 18:13:44 -07003735 //TODO: configure audio effect output stage here
3736
3737 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003738 duplicatedOutput =
3739 mpClientInterface->openDuplicateOutput(output,
3740 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003741 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003742 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003743 sp<SwAudioOutputDescriptor> dupOutputDesc =
3744 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3745 dupOutputDesc->mOutput1 = mPrimaryOutput;
3746 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003747 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3748 dupOutputDesc->mFormat = desc->mFormat;
3749 dupOutputDesc->mChannelMask = desc->mChannelMask;
3750 dupOutputDesc->mLatency = desc->mLatency;
3751 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003752 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003753 } else {
3754 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003755 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003756 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003757 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003758 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003759 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003760 }
Eric Laurente552edb2014-03-10 17:42:56 -07003761 }
3762 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003763 } else {
3764 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003765 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003766 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003767 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003768 profiles.removeAt(profile_index);
3769 profile_index--;
3770 } else {
3771 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003772 // Load digital format info only for digital devices
3773 if (audio_device_is_digital(device)) {
3774 devDesc->importAudioPort(profile);
3775 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003776
François Gaffie53615e22015-03-19 09:24:12 +01003777 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003778 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3779 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003780 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003781 NULL/*patch handle*/, address.string());
3782 }
Eric Laurente552edb2014-03-10 17:42:56 -07003783 ALOGV("checkOutputsForDevice(): adding output %d", output);
3784 }
3785 }
3786
3787 if (profiles.isEmpty()) {
3788 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3789 return BAD_VALUE;
3790 }
Eric Laurentd4692962014-05-05 18:13:44 -07003791 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003792 // check if one opened output is not needed any more after disconnecting one device
3793 for (size_t i = 0; i < mOutputs.size(); i++) {
3794 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003795 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003796 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003797 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003798 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003799 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003800 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003801 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3802 mOutputs.keyAt(i));
3803 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003804 }
Eric Laurente552edb2014-03-10 17:42:56 -07003805 }
3806 }
Eric Laurentd4692962014-05-05 18:13:44 -07003807 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003808 for (size_t i = 0; i < mHwModules.size(); i++)
3809 {
3810 if (mHwModules[i]->mHandle == 0) {
3811 continue;
3812 }
3813 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3814 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003815 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003816 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003817 ALOGV("checkOutputsForDevice(): "
3818 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003819 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003820 }
3821 }
3822 }
3823 }
3824 return NO_ERROR;
3825}
3826
Paul McLean9080a4c2015-06-18 08:24:02 -07003827status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003828 audio_policy_dev_state_t state,
3829 SortedVector<audio_io_handle_t>& inputs,
3830 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003831{
Paul McLean9080a4c2015-06-18 08:24:02 -07003832 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003833 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003834
3835 if (audio_device_is_digital(device)) {
3836 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003837 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003838 }
3839
Eric Laurentd4692962014-05-05 18:13:44 -07003840 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3841 // first list already open inputs that can be routed to this device
3842 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3843 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003844 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003845 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3846 inputs.add(mInputs.keyAt(input_index));
3847 }
3848 }
3849
3850 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003851 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003852 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3853 {
3854 if (mHwModules[module_idx]->mHandle == 0) {
3855 continue;
3856 }
3857 for (size_t profile_index = 0;
3858 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3859 profile_index++)
3860 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003861 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3862
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003863 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003864 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003865 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003866 profiles.add(profile);
3867 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3868 profile_index, module_idx);
3869 }
Eric Laurentd4692962014-05-05 18:13:44 -07003870 }
3871 }
3872 }
3873
3874 if (profiles.isEmpty() && inputs.isEmpty()) {
3875 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3876 return BAD_VALUE;
3877 }
3878
3879 // open inputs for matching profiles if needed. Direct inputs are also opened to
3880 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3881 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3882
Eric Laurent1c333e22014-05-20 10:48:17 -07003883 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003884 // nothing to do if one input is already opened for this profile
3885 size_t input_index;
3886 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3887 desc = mInputs.valueAt(input_index);
3888 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003889 if (audio_device_is_digital(device)) {
3890 devDesc->importAudioPort(profile);
3891 }
Eric Laurentd4692962014-05-05 18:13:44 -07003892 break;
3893 }
3894 }
3895 if (input_index != mInputs.size()) {
3896 continue;
3897 }
3898
3899 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3900 desc = new AudioInputDescriptor(profile);
3901 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003902 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3903 config.sample_rate = desc->mSamplingRate;
3904 config.channel_mask = desc->mChannelMask;
3905 config.format = desc->mFormat;
3906 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003907 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003908 &input,
3909 &config,
3910 &desc->mDevice,
3911 address,
3912 AUDIO_SOURCE_MIC,
3913 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003914
Eric Laurentcf2c0212014-07-25 16:20:43 -07003915 if (status == NO_ERROR) {
3916 desc->mSamplingRate = config.sample_rate;
3917 desc->mChannelMask = config.channel_mask;
3918 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003919
Eric Laurentd4692962014-05-05 18:13:44 -07003920 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003921 char *param = audio_device_address_to_parameter(device, address);
3922 mpClientInterface->setParameters(input, String8(param));
3923 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003924 }
François Gaffie112b0af2015-11-19 16:13:25 +01003925 updateAudioProfiles(input, profile->getAudioProfiles());
3926 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003927 ALOGW("checkInputsForDevice() direct input missing param");
3928 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003929 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003930 }
3931
3932 if (input != 0) {
3933 addInput(input, desc);
3934 }
3935 } // endif input != 0
3936
Eric Laurentcf2c0212014-07-25 16:20:43 -07003937 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003938 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003939 profiles.removeAt(profile_index);
3940 profile_index--;
3941 } else {
3942 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003943 if (audio_device_is_digital(device)) {
3944 devDesc->importAudioPort(profile);
3945 }
Eric Laurentd4692962014-05-05 18:13:44 -07003946 ALOGV("checkInputsForDevice(): adding input %d", input);
3947 }
3948 } // end scan profiles
3949
3950 if (profiles.isEmpty()) {
3951 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3952 return BAD_VALUE;
3953 }
3954 } else {
3955 // Disconnect
3956 // check if one opened input is not needed any more after disconnecting one device
3957 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3958 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003959 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003960 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3961 mInputs.keyAt(input_index));
3962 inputs.add(mInputs.keyAt(input_index));
3963 }
3964 }
3965 // Clear any profiles associated with the disconnected device.
3966 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3967 if (mHwModules[module_index]->mHandle == 0) {
3968 continue;
3969 }
3970 for (size_t profile_index = 0;
3971 profile_index < mHwModules[module_index]->mInputProfiles.size();
3972 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003973 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003974 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003975 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003976 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01003977 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07003978 }
3979 }
3980 }
3981 } // end disconnect
3982
3983 return NO_ERROR;
3984}
3985
3986
Eric Laurente0720872014-03-11 09:30:41 -07003987void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003988{
3989 ALOGV("closeOutput(%d)", output);
3990
Eric Laurentc75307b2015-03-17 15:29:32 -07003991 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003992 if (outputDesc == NULL) {
3993 ALOGW("closeOutput() unknown output %d", output);
3994 return;
3995 }
François Gaffie036e1e92015-03-19 10:16:24 +01003996 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003997
Eric Laurente552edb2014-03-10 17:42:56 -07003998 // look for duplicated outputs connected to the output being removed.
3999 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004000 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004001 if (dupOutputDesc->isDuplicated() &&
4002 (dupOutputDesc->mOutput1 == outputDesc ||
4003 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004004 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004005 if (dupOutputDesc->mOutput1 == outputDesc) {
4006 outputDesc2 = dupOutputDesc->mOutput2;
4007 } else {
4008 outputDesc2 = dupOutputDesc->mOutput1;
4009 }
4010 // As all active tracks on duplicated output will be deleted,
4011 // and as they were also referenced on the other output, the reference
4012 // count for their stream type must be adjusted accordingly on
4013 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004014 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004015 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004016 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004017 }
4018 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4019 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4020
4021 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004022 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004023 }
4024 }
4025
Eric Laurent05b90f82014-08-27 15:32:29 -07004026 nextAudioPortGeneration();
4027
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004028 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004029 if (index >= 0) {
4030 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4031 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4032 mAudioPatches.removeItemsAt(index);
4033 mpClientInterface->onAudioPatchListUpdate();
4034 }
4035
Eric Laurente552edb2014-03-10 17:42:56 -07004036 AudioParameter param;
4037 param.add(String8("closing"), String8("true"));
4038 mpClientInterface->setParameters(output, param.toString());
4039
4040 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004041 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004042 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004043}
4044
4045void AudioPolicyManager::closeInput(audio_io_handle_t input)
4046{
4047 ALOGV("closeInput(%d)", input);
4048
4049 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4050 if (inputDesc == NULL) {
4051 ALOGW("closeInput() unknown input %d", input);
4052 return;
4053 }
4054
Eric Laurent6a94d692014-05-20 11:18:06 -07004055 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004056
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004057 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004058 if (index >= 0) {
4059 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4060 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4061 mAudioPatches.removeItemsAt(index);
4062 mpClientInterface->onAudioPatchListUpdate();
4063 }
4064
4065 mpClientInterface->closeInput(input);
4066 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004067}
4068
Eric Laurentc75307b2015-03-17 15:29:32 -07004069SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4070 audio_devices_t device,
4071 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004072{
4073 SortedVector<audio_io_handle_t> outputs;
4074
4075 ALOGVV("getOutputsForDevice() device %04x", device);
4076 for (size_t i = 0; i < openOutputs.size(); i++) {
4077 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004078 i, openOutputs.valueAt(i)->isDuplicated(),
4079 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004080 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4081 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4082 outputs.add(openOutputs.keyAt(i));
4083 }
4084 }
4085 return outputs;
4086}
4087
Eric Laurente0720872014-03-11 09:30:41 -07004088bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004089 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004090{
4091 if (outputs1.size() != outputs2.size()) {
4092 return false;
4093 }
4094 for (size_t i = 0; i < outputs1.size(); i++) {
4095 if (outputs1[i] != outputs2[i]) {
4096 return false;
4097 }
4098 }
4099 return true;
4100}
4101
Eric Laurente0720872014-03-11 09:30:41 -07004102void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004103{
4104 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4105 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4106 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4107 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4108
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004109 // also take into account external policy-related changes: add all outputs which are
4110 // associated with policies in the "before" and "after" output vectors
4111 ALOGVV("checkOutputForStrategy(): policy related outputs");
4112 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004113 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004114 if (desc != 0 && desc->mPolicyMix != NULL) {
4115 srcOutputs.add(desc->mIoHandle);
4116 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4117 }
4118 }
4119 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004120 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004121 if (desc != 0 && desc->mPolicyMix != NULL) {
4122 dstOutputs.add(desc->mIoHandle);
4123 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4124 }
4125 }
4126
Eric Laurente552edb2014-03-10 17:42:56 -07004127 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4128 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4129 strategy, srcOutputs[0], dstOutputs[0]);
4130 // mute strategy while moving tracks from one output to another
4131 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004132 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004133 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004134 setStrategyMute(strategy, true, desc);
4135 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004136 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004137 sp<AudioSourceDescriptor> source =
4138 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4139 if (source != 0){
4140 connectAudioSource(source);
4141 }
Eric Laurente552edb2014-03-10 17:42:56 -07004142 }
4143
4144 // Move effects associated to this strategy from previous output to new output
4145 if (strategy == STRATEGY_MEDIA) {
4146 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4147 SortedVector<audio_io_handle_t> moved;
4148 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004149 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4150 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4151 effectDesc->mIo != fxOutput) {
4152 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004153 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4154 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004155 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004156 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004157 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004158 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004159 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004160 }
4161 }
4162 }
4163 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004164 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004165 if (i == AUDIO_STREAM_PATCH) {
4166 continue;
4167 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004168 if (getStrategy((audio_stream_type_t)i) == strategy) {
4169 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004170 }
4171 }
4172 }
4173}
4174
Eric Laurente0720872014-03-11 09:30:41 -07004175void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004176{
François Gaffie2110e042015-03-24 08:41:51 +01004177 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004178 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004179 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004180 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004181 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004182 checkOutputForStrategy(STRATEGY_SONIFICATION);
4183 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004184 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004185 checkOutputForStrategy(STRATEGY_MEDIA);
4186 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004187 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004188}
4189
Eric Laurente0720872014-03-11 09:30:41 -07004190void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004191{
François Gaffie53615e22015-03-19 09:24:12 +01004192 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004193 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004194 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004195 return;
4196 }
4197
Eric Laurent3a4311c2014-03-17 12:00:47 -07004198 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004199 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4200 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4201 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004202 // suspend A2DP output if:
4203 // (NOT already suspended) &&
4204 // ((SCO device is connected &&
4205 // (forced usage for communication || for record is SCO))) ||
4206 // (phone state is ringing || in call)
4207 //
4208 // restore A2DP output if:
4209 // (Already suspended) &&
4210 // ((SCO device is NOT connected ||
4211 // (forced usage NOT for communication && NOT for record is SCO))) &&
4212 // (phone state is NOT ringing && NOT in call)
4213 //
4214 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004215 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004216 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4217 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4218 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4219 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004220
4221 mpClientInterface->restoreOutput(a2dpOutput);
4222 mA2dpSuspended = false;
4223 }
4224 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004225 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004226 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4227 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4228 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4229 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004230
4231 mpClientInterface->suspendOutput(a2dpOutput);
4232 mA2dpSuspended = true;
4233 }
4234 }
4235}
4236
Eric Laurentc75307b2015-03-17 15:29:32 -07004237audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4238 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004239{
4240 audio_devices_t device = AUDIO_DEVICE_NONE;
4241
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004242 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004243 if (index >= 0) {
4244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4245 if (patchDesc->mUid != mUidCached) {
4246 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004247 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004248 return outputDesc->device();
4249 }
4250 }
4251
Eric Laurente552edb2014-03-10 17:42:56 -07004252 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004253 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004254 // use device for strategy enforced audible
4255 // 2: we are in call or the strategy phone is active on the output:
4256 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004257 // 3: the strategy for enforced audible is active but not enforced on the output:
4258 // use the device for strategy enforced audible
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004259 // 4: the strategy accessibility is active on the output:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004260 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004261 // 5: the strategy sonification is active on the output:
4262 // use device for strategy sonification
4263 // 6: the strategy "respectful" sonification is active on the output:
4264 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004265 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004266 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004267 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004268 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004269 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004270 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004271 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004272 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004273 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4274 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004275 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004276 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004277 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004278 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004279 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4280 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004281 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004282 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004283 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004284 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004285 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004286 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004287 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004288 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004289 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004290 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004291 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004292 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
4294
Eric Laurent1c333e22014-05-20 10:48:17 -07004295 ALOGV("getNewOutputDevice() selected device %x", device);
4296 return device;
4297}
4298
Eric Laurentfb66dd92016-01-28 18:32:03 -08004299audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004300{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004301 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004302
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004303 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004304 if (index >= 0) {
4305 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4306 if (patchDesc->mUid != mUidCached) {
4307 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004308 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004309 return inputDesc->mDevice;
4310 }
4311 }
4312
Eric Laurentfb66dd92016-01-28 18:32:03 -08004313 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4314 if (isInCall()) {
4315 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4316 } else if (source != AUDIO_SOURCE_DEFAULT) {
4317 device = getDeviceAndMixForInputSource(source);
4318 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004319
Eric Laurente552edb2014-03-10 17:42:56 -07004320 return device;
4321}
4322
Eric Laurente0720872014-03-11 09:30:41 -07004323uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004324 return (uint32_t)getStrategy(stream);
4325}
4326
Eric Laurente0720872014-03-11 09:30:41 -07004327audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004328 // By checking the range of stream before calling getStrategy, we avoid
4329 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4330 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004331 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004332 return AUDIO_DEVICE_NONE;
4333 }
4334 audio_devices_t devices;
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004335 routing_strategy strategy = getStrategy(stream);
Eric Laurent6a94d692014-05-20 11:18:06 -07004336 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4337 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4338 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004339 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004340 if (isStrategyActive(outputDesc, strategy)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004341 devices = outputDesc->device();
4342 break;
4343 }
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004345
4346 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4347 and doesn't really need to.*/
4348 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4349 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4350 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4351 }
Eric Laurente552edb2014-03-10 17:42:56 -07004352 return devices;
4353}
4354
François Gaffie2110e042015-03-24 08:41:51 +01004355routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4356{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004357 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004358 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004359}
4360
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004361uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4362 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004363 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4364 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4365 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004366 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4367 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4368 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004369 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004370 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004371}
4372
Eric Laurente0720872014-03-11 09:30:41 -07004373void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004374 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004375 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004376 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4377 updateDevicesAndOutputs();
4378 break;
4379 default:
4380 break;
4381 }
4382}
4383
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004384uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004385
4386 // skip beacon mute management if a dedicated TTS output is available
4387 if (mTtsOutputAvailable) {
4388 return 0;
4389 }
4390
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004391 switch(event) {
4392 case STARTING_OUTPUT:
4393 mBeaconMuteRefCount++;
4394 break;
4395 case STOPPING_OUTPUT:
4396 if (mBeaconMuteRefCount > 0) {
4397 mBeaconMuteRefCount--;
4398 }
4399 break;
4400 case STARTING_BEACON:
4401 mBeaconPlayingRefCount++;
4402 break;
4403 case STOPPING_BEACON:
4404 if (mBeaconPlayingRefCount > 0) {
4405 mBeaconPlayingRefCount--;
4406 }
4407 break;
4408 }
4409
4410 if (mBeaconMuteRefCount > 0) {
4411 // any playback causes beacon to be muted
4412 return setBeaconMute(true);
4413 } else {
4414 // no other playback: unmute when beacon starts playing, mute when it stops
4415 return setBeaconMute(mBeaconPlayingRefCount == 0);
4416 }
4417}
4418
4419uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4420 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4421 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4422 // keep track of muted state to avoid repeating mute/unmute operations
4423 if (mBeaconMuted != mute) {
4424 // mute/unmute AUDIO_STREAM_TTS on all outputs
4425 ALOGV("\t muting %d", mute);
4426 uint32_t maxLatency = 0;
4427 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004428 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004429 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004430 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004431 0 /*delay*/, AUDIO_DEVICE_NONE);
4432 const uint32_t latency = desc->latency() * 2;
4433 if (latency > maxLatency) {
4434 maxLatency = latency;
4435 }
4436 }
4437 mBeaconMuted = mute;
4438 return maxLatency;
4439 }
4440 return 0;
4441}
4442
Eric Laurente0720872014-03-11 09:30:41 -07004443audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004444 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004445{
Paul McLeanaa981192015-03-21 09:55:15 -07004446 // Routing
4447 // see if we have an explicit route
4448 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4449 // (getStrategy(stream)).
4450 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4451 // and activity count is non-zero
4452 // the device = the device from the descriptor in the RouteMap, and exit.
4453 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4454 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
4455 routing_strategy strat = getStrategy(route->mStreamType);
Eric Laurent093a20c2015-06-11 12:33:29 -07004456 // Special case for accessibility strategy which must follow any strategy it is
4457 // currently remapped to
4458 bool strategyMatch = (strat == strategy) ||
4459 ((strategy == STRATEGY_ACCESSIBILITY) &&
4460 ((mEngine->getStrategyForUsage(
4461 AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) == strat) ||
4462 (strat == STRATEGY_MEDIA)));
4463 if (strategyMatch && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004464 return route->mDeviceDescriptor->type();
4465 }
4466 }
4467
Eric Laurente552edb2014-03-10 17:42:56 -07004468 if (fromCache) {
4469 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4470 strategy, mDeviceForStrategy[strategy]);
4471 return mDeviceForStrategy[strategy];
4472 }
François Gaffie2110e042015-03-24 08:41:51 +01004473 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004474}
4475
Eric Laurente0720872014-03-11 09:30:41 -07004476void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004477{
4478 for (int i = 0; i < NUM_STRATEGIES; i++) {
4479 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4480 }
4481 mPreviousOutputs = mOutputs;
4482}
4483
Eric Laurent1f2f2232014-06-02 12:01:23 -07004484uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004485 audio_devices_t prevDevice,
4486 uint32_t delayMs)
4487{
4488 // mute/unmute strategies using an incompatible device combination
4489 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4490 // if unmuting, unmute only after the specified delay
4491 if (outputDesc->isDuplicated()) {
4492 return 0;
4493 }
4494
4495 uint32_t muteWaitMs = 0;
4496 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004497 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004498
4499 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4500 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004501 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004502 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4503 bool doMute = false;
4504
4505 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4506 doMute = true;
4507 outputDesc->mStrategyMutedByDevice[i] = true;
4508 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4509 doMute = true;
4510 outputDesc->mStrategyMutedByDevice[i] = false;
4511 }
Eric Laurent99401132014-05-07 19:48:15 -07004512 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004513 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004514 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004515 // skip output if it does not share any device with current output
4516 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4517 == AUDIO_DEVICE_NONE) {
4518 continue;
4519 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004520 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4521 mute ? "muting" : "unmuting", i, curDevice);
4522 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004523 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004524 if (mute) {
4525 // FIXME: should not need to double latency if volume could be applied
4526 // immediately by the audioflinger mixer. We must account for the delay
4527 // between now and the next time the audioflinger thread for this output
4528 // will process a buffer (which corresponds to one buffer size,
4529 // usually 1/2 or 1/4 of the latency).
4530 if (muteWaitMs < desc->latency() * 2) {
4531 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004532 }
4533 }
4534 }
4535 }
4536 }
4537 }
4538
Eric Laurent99401132014-05-07 19:48:15 -07004539 // temporary mute output if device selection changes to avoid volume bursts due to
4540 // different per device volumes
4541 if (outputDesc->isActive() && (device != prevDevice)) {
4542 if (muteWaitMs < outputDesc->latency() * 2) {
4543 muteWaitMs = outputDesc->latency() * 2;
4544 }
4545 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004546 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004547 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004548 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004549 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004550 muteWaitMs *2, device);
4551 }
4552 }
4553 }
4554
Eric Laurente552edb2014-03-10 17:42:56 -07004555 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4556 if (muteWaitMs > delayMs) {
4557 muteWaitMs -= delayMs;
4558 usleep(muteWaitMs * 1000);
4559 return muteWaitMs;
4560 }
4561 return 0;
4562}
4563
Eric Laurentc75307b2015-03-17 15:29:32 -07004564uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004565 audio_devices_t device,
4566 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004567 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004568 audio_patch_handle_t *patchHandle,
4569 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004570{
Eric Laurentc75307b2015-03-17 15:29:32 -07004571 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004572 AudioParameter param;
4573 uint32_t muteWaitMs;
4574
4575 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004576 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4577 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004578 return muteWaitMs;
4579 }
4580 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4581 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004582 if ((device != AUDIO_DEVICE_NONE) &&
4583 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004584 return 0;
4585 }
4586
4587 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004588 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004589
4590 audio_devices_t prevDevice = outputDesc->mDevice;
4591
Paul McLeanaa981192015-03-21 09:55:15 -07004592 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004593
4594 if (device != AUDIO_DEVICE_NONE) {
4595 outputDesc->mDevice = device;
4596 }
4597 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4598
4599 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004600 // the requested device is AUDIO_DEVICE_NONE
4601 // OR the requested device is the same as current device
4602 // AND force is not specified
4603 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004604 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004605 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4606 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004607 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004608 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004609 return muteWaitMs;
4610 }
4611
4612 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004613
Eric Laurente552edb2014-03-10 17:42:56 -07004614 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004615 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004616 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004617 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004618 DeviceVector deviceList = (address == NULL) ?
4619 mAvailableOutputDevices.getDevicesFromType(device)
4620 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004621 if (!deviceList.isEmpty()) {
4622 struct audio_patch patch;
4623 outputDesc->toAudioPortConfig(&patch.sources[0]);
4624 patch.num_sources = 1;
4625 patch.num_sinks = 0;
4626 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4627 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004628 patch.num_sinks++;
4629 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004630 ssize_t index;
4631 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4632 index = mAudioPatches.indexOfKey(*patchHandle);
4633 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004634 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004635 }
4636 sp< AudioPatch> patchDesc;
4637 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4638 if (index >= 0) {
4639 patchDesc = mAudioPatches.valueAt(index);
4640 afPatchHandle = patchDesc->mAfPatchHandle;
4641 }
4642
Eric Laurent1c333e22014-05-20 10:48:17 -07004643 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004644 &afPatchHandle,
4645 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004646 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4647 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004648 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004649 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004650 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004651 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004652 addAudioPatch(patchDesc->mHandle, patchDesc);
4653 } else {
4654 patchDesc->mPatch = patch;
4655 }
4656 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004657 if (patchHandle) {
4658 *patchHandle = patchDesc->mHandle;
4659 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004660 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004662 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004663 }
4664 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004665
4666 // inform all input as well
4667 for (size_t i = 0; i < mInputs.size(); i++) {
4668 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004669 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004670 AudioParameter inputCmd = AudioParameter();
4671 ALOGV("%s: inform input %d of device:%d", __func__,
4672 inputDescriptor->mIoHandle, device);
4673 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4674 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4675 inputCmd.toString(),
4676 delayMs);
4677 }
4678 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004679 }
Eric Laurente552edb2014-03-10 17:42:56 -07004680
4681 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004682 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004683
4684 return muteWaitMs;
4685}
4686
Eric Laurentc75307b2015-03-17 15:29:32 -07004687status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 int delayMs,
4689 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004690{
Eric Laurent6a94d692014-05-20 11:18:06 -07004691 ssize_t index;
4692 if (patchHandle) {
4693 index = mAudioPatches.indexOfKey(*patchHandle);
4694 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004695 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 }
4697 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004698 return INVALID_OPERATION;
4699 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4701 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004702 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004703 outputDesc->setPatchHandle(0);
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 removeAudioPatch(patchDesc->mHandle);
4705 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004706 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004707 return status;
4708}
4709
4710status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4711 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004712 bool force,
4713 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004714{
4715 status_t status = NO_ERROR;
4716
Eric Laurent1f2f2232014-06-02 12:01:23 -07004717 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004718 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4719 inputDesc->mDevice = device;
4720
4721 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4722 if (!deviceList.isEmpty()) {
4723 struct audio_patch patch;
4724 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004725 // AUDIO_SOURCE_HOTWORD is for internal use only:
4726 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004727 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004728 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004729 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4730 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004731 patch.num_sinks = 1;
4732 //only one input device for now
4733 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004734 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004735 ssize_t index;
4736 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4737 index = mAudioPatches.indexOfKey(*patchHandle);
4738 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004739 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 }
4741 sp< AudioPatch> patchDesc;
4742 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4743 if (index >= 0) {
4744 patchDesc = mAudioPatches.valueAt(index);
4745 afPatchHandle = patchDesc->mAfPatchHandle;
4746 }
4747
Eric Laurent1c333e22014-05-20 10:48:17 -07004748 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004749 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004750 0);
4751 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004753 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004755 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 addAudioPatch(patchDesc->mHandle, patchDesc);
4757 } else {
4758 patchDesc->mPatch = patch;
4759 }
4760 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004761 if (patchHandle) {
4762 *patchHandle = patchDesc->mHandle;
4763 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004764 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004765 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004766 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004767 }
4768 }
4769 }
4770 return status;
4771}
4772
Eric Laurent6a94d692014-05-20 11:18:06 -07004773status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4774 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004775{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004776 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004777 ssize_t index;
4778 if (patchHandle) {
4779 index = mAudioPatches.indexOfKey(*patchHandle);
4780 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004781 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004782 }
4783 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004784 return INVALID_OPERATION;
4785 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004786 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4787 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004788 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004789 inputDesc->setPatchHandle(0);
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 removeAudioPatch(patchDesc->mHandle);
4791 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004792 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004793 return status;
4794}
4795
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004796sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004797 String8 address,
4798 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004799 audio_format_t& format,
4800 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004801 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004802{
4803 // Choose an input profile based on the requested capture parameters: select the first available
4804 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004805 //
4806 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4807 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004808
4809 for (size_t i = 0; i < mHwModules.size(); i++)
4810 {
4811 if (mHwModules[i]->mHandle == 0) {
4812 continue;
4813 }
4814 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4815 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004816 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004817 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004818 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004819 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004820 format,
4821 &format /*updatedFormat*/,
4822 channelMask,
4823 &channelMask /*updatedChannelMask*/,
4824 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004825
Eric Laurente552edb2014-03-10 17:42:56 -07004826 return profile;
4827 }
4828 }
4829 }
4830 return NULL;
4831}
4832
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004833
4834audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004835 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004836{
François Gaffie036e1e92015-03-19 10:16:24 +01004837 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4838 audio_devices_t selectedDeviceFromMix =
4839 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004840
François Gaffie036e1e92015-03-19 10:16:24 +01004841 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4842 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004843 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004844 return getDeviceForInputSource(inputSource);
4845}
4846
4847audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4848{
Paul McLean466dc8e2015-04-17 13:15:36 -06004849 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4850 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004851 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004852 return route->mDeviceDescriptor->type();
4853 }
4854 }
4855
4856 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004857}
4858
Eric Laurente0720872014-03-11 09:30:41 -07004859float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004860 int index,
4861 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004862{
François Gaffied1ab2bd2015-12-02 18:20:06 +01004863 float volumeDb = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Eric Laurente552edb2014-03-10 17:42:56 -07004864 // if a headset is connected, apply the following rules to ring tones and notifications
4865 // to avoid sound level bursts in user's ears:
4866 // - always attenuate ring tones and notifications volume by 6dB
4867 // - if music is playing, always limit the volume to current music volume,
4868 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004869 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004870 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4871 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4872 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4873 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4874 ((stream_strategy == STRATEGY_SONIFICATION)
4875 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004876 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004877 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004878 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01004879 mVolumeCurves->canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004880 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004881 // when the phone is ringing we must consider that music could have been paused just before
4882 // by the music application and behave as if music was active if the last music track was
4883 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004884 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004885 mLimitRingtoneVolume) {
4886 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004887 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004888 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
4889 musicDevice),
4890 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004891 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4892 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4893 if (volumeDb > minVolDB) {
4894 volumeDb = minVolDB;
4895 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004896 }
4897 }
4898 }
4899
Eric Laurentffbc80f2015-03-18 18:30:19 -07004900 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004901}
4902
Eric Laurente0720872014-03-11 09:30:41 -07004903status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004904 int index,
4905 const sp<AudioOutputDescriptor>& outputDesc,
4906 audio_devices_t device,
4907 int delayMs,
4908 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004909{
Eric Laurente552edb2014-03-10 17:42:56 -07004910 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004911 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004912 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004913 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004914 return NO_ERROR;
4915 }
François Gaffie2110e042015-03-24 08:41:51 +01004916 audio_policy_forced_cfg_t forceUseForComm =
4917 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004918 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004919 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4920 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004921 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004922 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004923 return INVALID_OPERATION;
4924 }
4925
Eric Laurentc75307b2015-03-17 15:29:32 -07004926 if (device == AUDIO_DEVICE_NONE) {
4927 device = outputDesc->device();
4928 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004929
Eric Laurentffbc80f2015-03-18 18:30:19 -07004930 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004931 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004932 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004933 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004934
Eric Laurentffbc80f2015-03-18 18:30:19 -07004935 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004936
Eric Laurent3b73df72014-03-11 09:06:29 -07004937 if (stream == AUDIO_STREAM_VOICE_CALL ||
4938 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004939 float voiceVolume;
4940 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004941 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004942 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004943 } else {
4944 voiceVolume = 1.0;
4945 }
4946
Eric Laurentc75307b2015-03-17 15:29:32 -07004947 if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
Eric Laurente552edb2014-03-10 17:42:56 -07004948 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4949 mLastVoiceVolume = voiceVolume;
4950 }
4951 }
4952
4953 return NO_ERROR;
4954}
4955
Eric Laurentc75307b2015-03-17 15:29:32 -07004956void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4957 audio_devices_t device,
4958 int delayMs,
4959 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004960{
Eric Laurentc75307b2015-03-17 15:29:32 -07004961 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004962
Eric Laurent3b73df72014-03-11 09:06:29 -07004963 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004964 if (stream == AUDIO_STREAM_PATCH) {
4965 continue;
4966 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004967 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004968 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004969 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004970 device,
4971 delayMs,
4972 force);
4973 }
4974}
4975
Eric Laurente0720872014-03-11 09:30:41 -07004976void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07004977 bool on,
4978 const sp<AudioOutputDescriptor>& outputDesc,
4979 int delayMs,
4980 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004981{
Eric Laurent72249d52015-06-08 11:12:15 -07004982 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
4983 strategy, on, outputDesc->getId());
Eric Laurent3b73df72014-03-11 09:06:29 -07004984 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004985 if (stream == AUDIO_STREAM_PATCH) {
4986 continue;
4987 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004988 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004989 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004990 }
4991 }
4992}
4993
Eric Laurente0720872014-03-11 09:30:41 -07004994void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004995 bool on,
4996 const sp<AudioOutputDescriptor>& outputDesc,
4997 int delayMs,
4998 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004999{
Eric Laurente552edb2014-03-10 17:42:56 -07005000 if (device == AUDIO_DEVICE_NONE) {
5001 device = outputDesc->device();
5002 }
5003
Eric Laurentc75307b2015-03-17 15:29:32 -07005004 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5005 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005006
5007 if (on) {
5008 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005009 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005010 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005011 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005012 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005013 }
5014 }
5015 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5016 outputDesc->mMuteCount[stream]++;
5017 } else {
5018 if (outputDesc->mMuteCount[stream] == 0) {
5019 ALOGV("setStreamMute() unmuting non muted stream!");
5020 return;
5021 }
5022 if (--outputDesc->mMuteCount[stream] == 0) {
5023 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005024 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005025 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005026 device,
5027 delayMs);
5028 }
5029 }
5030}
5031
Eric Laurente0720872014-03-11 09:30:41 -07005032void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005033 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005034{
Eric Laurent87ffa392015-05-22 10:32:38 -07005035 if(!hasPrimaryOutput()) {
5036 return;
5037 }
5038
Eric Laurente552edb2014-03-10 17:42:56 -07005039 // if the stream pertains to sonification strategy and we are in call we must
5040 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5041 // in the device used for phone strategy and play the tone if the selected device does not
5042 // interfere with the device used for phone strategy
5043 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5044 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005045 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005046 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5047 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005048 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005049 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5050 stream, starting, outputDesc->mDevice, stateChange);
5051 if (outputDesc->mRefCount[stream]) {
5052 int muteCount = 1;
5053 if (stateChange) {
5054 muteCount = outputDesc->mRefCount[stream];
5055 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005056 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005057 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5058 for (int i = 0; i < muteCount; i++) {
5059 setStreamMute(stream, starting, mPrimaryOutput);
5060 }
5061 } else {
5062 ALOGV("handleIncallSonification() high visibility");
5063 if (outputDesc->device() &
5064 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5065 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5066 for (int i = 0; i < muteCount; i++) {
5067 setStreamMute(stream, starting, mPrimaryOutput);
5068 }
5069 }
5070 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005071 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5072 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005073 } else {
5074 mpClientInterface->stopTone();
5075 }
5076 }
5077 }
5078 }
5079}
5080
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005081audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5082{
5083 // flags to stream type mapping
5084 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5085 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5086 }
5087 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5088 return AUDIO_STREAM_BLUETOOTH_SCO;
5089 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005090 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5091 return AUDIO_STREAM_TTS;
5092 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005093
5094 // usage to stream type mapping
5095 switch (attr->usage) {
5096 case AUDIO_USAGE_MEDIA:
5097 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005098 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5099 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005100 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08005101 if (isStreamActive(AUDIO_STREAM_ALARM)) {
5102 return AUDIO_STREAM_ALARM;
5103 }
5104 if (isStreamActive(AUDIO_STREAM_RING)) {
5105 return AUDIO_STREAM_RING;
5106 }
5107 if (isInCall()) {
5108 return AUDIO_STREAM_VOICE_CALL;
5109 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08005110 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005111 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5112 return AUDIO_STREAM_SYSTEM;
5113 case AUDIO_USAGE_VOICE_COMMUNICATION:
5114 return AUDIO_STREAM_VOICE_CALL;
5115
5116 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5117 return AUDIO_STREAM_DTMF;
5118
5119 case AUDIO_USAGE_ALARM:
5120 return AUDIO_STREAM_ALARM;
5121 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5122 return AUDIO_STREAM_RING;
5123
5124 case AUDIO_USAGE_NOTIFICATION:
5125 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5126 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5127 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5128 case AUDIO_USAGE_NOTIFICATION_EVENT:
5129 return AUDIO_STREAM_NOTIFICATION;
5130
5131 case AUDIO_USAGE_UNKNOWN:
5132 default:
5133 return AUDIO_STREAM_MUSIC;
5134 }
5135}
Eric Laurente83b55d2014-11-14 10:06:21 -08005136
François Gaffie53615e22015-03-19 09:24:12 +01005137bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5138{
Eric Laurente83b55d2014-11-14 10:06:21 -08005139 // has flags that map to a strategy?
5140 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5141 return true;
5142 }
5143
5144 // has known usage?
5145 switch (paa->usage) {
5146 case AUDIO_USAGE_UNKNOWN:
5147 case AUDIO_USAGE_MEDIA:
5148 case AUDIO_USAGE_VOICE_COMMUNICATION:
5149 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5150 case AUDIO_USAGE_ALARM:
5151 case AUDIO_USAGE_NOTIFICATION:
5152 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5153 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5154 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5155 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5156 case AUDIO_USAGE_NOTIFICATION_EVENT:
5157 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5158 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5159 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5160 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005161 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005162 break;
5163 default:
5164 return false;
5165 }
5166 return true;
5167}
5168
François Gaffiead3183e2015-03-18 16:55:35 +01005169bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5170 routing_strategy strategy, uint32_t inPastMs,
5171 nsecs_t sysTime) const
5172{
5173 if ((sysTime == 0) && (inPastMs != 0)) {
5174 sysTime = systemTime();
5175 }
5176 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5177 if (i == AUDIO_STREAM_PATCH) {
5178 continue;
5179 }
5180 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5181 (NUM_STRATEGIES == strategy)) &&
5182 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5183 return true;
5184 }
5185 }
5186 return false;
5187}
5188
François Gaffie2110e042015-03-24 08:41:51 +01005189audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5190{
5191 return mEngine->getForceUse(usage);
5192}
5193
5194bool AudioPolicyManager::isInCall()
5195{
5196 return isStateInCall(mEngine->getPhoneState());
5197}
5198
5199bool AudioPolicyManager::isStateInCall(int state)
5200{
5201 return is_state_in_call(state);
5202}
5203
Eric Laurentd60560a2015-04-10 11:31:20 -07005204void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5205{
5206 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5207 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5208 if (sourceDesc->mDevice->equals(deviceDesc)) {
5209 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5210 stopAudioSource(sourceDesc->getHandle());
5211 }
5212 }
5213
5214 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5215 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5216 bool release = false;
5217 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5218 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5219 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5220 source->ext.device.type == deviceDesc->type()) {
5221 release = true;
5222 }
5223 }
5224 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5225 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5226 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5227 sink->ext.device.type == deviceDesc->type()) {
5228 release = true;
5229 }
5230 }
5231 if (release) {
5232 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5233 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5234 }
5235 }
5236}
5237
Phil Burk09bc4612016-02-24 15:58:15 -08005238// Modify the list of surround sound formats supported.
5239void AudioPolicyManager::filterSurroundFormats(FormatVector &formats) {
5240
5241 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5242 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5243 ALOGI("%s: forced use = %d", __FUNCTION__, forceUse);
5244
5245 // Analyze original support for various formats.
5246 bool supportsRawSurround = false;
5247 bool supportsIEC61937 = false;
5248 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5249 audio_format_t format = formats[formatIndex];
5250 ALOGI("%s: original formats: #%x", __FUNCTION__, format);
5251 switch (format) {
5252 case AUDIO_FORMAT_AC3:
5253 case AUDIO_FORMAT_E_AC3:
5254 case AUDIO_FORMAT_DTS:
5255 case AUDIO_FORMAT_DTS_HD:
5256 supportsRawSurround = true;
5257 break;
5258 case AUDIO_FORMAT_IEC61937:
5259 supportsIEC61937 = true;
5260 break;
5261 default:
5262 break;
5263 }
5264 }
5265 ALOGI("%s: supportsRawSurround = %d, supportsIEC61937 = %d",
5266 __FUNCTION__, supportsRawSurround, supportsIEC61937);
5267
5268 // Modify formats based on surround preferences.
5269 // If NEVER, remove support for surround formats.
5270 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER)
5271 && (supportsRawSurround || supportsIEC61937)) {
5272 // Remove surround sound related formats.
5273 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5274 audio_format_t format = formats[formatIndex];
5275 switch(format) {
5276 case AUDIO_FORMAT_AC3:
5277 case AUDIO_FORMAT_E_AC3:
5278 case AUDIO_FORMAT_DTS:
5279 case AUDIO_FORMAT_DTS_HD:
5280 case AUDIO_FORMAT_IEC61937:
5281 ALOGI("%s: remove #%x", __FUNCTION__, format);
5282 formats.removeAt(formatIndex);
5283 break;
5284 default:
5285 formatIndex++; // keep it
5286 break;
5287 }
5288 }
5289 supportsRawSurround = false;
5290 supportsIEC61937 = false;
5291 }
5292 // If ALWAYS, add support for raw surround formats if all are missing.
5293 // This assumes that if any of these formats are reported by the HAL
5294 // then the report is valid and should not be modified.
5295 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5296 && !supportsRawSurround) {
5297 formats.add(AUDIO_FORMAT_AC3);
5298 formats.add(AUDIO_FORMAT_E_AC3);
5299 formats.add(AUDIO_FORMAT_DTS);
5300 formats.add(AUDIO_FORMAT_DTS_HD);
5301 supportsRawSurround = true;
5302 }
5303 // Add support for IEC61937 if raw surround supported.
5304 // The HAL could do this but add it here, just in case.
5305 if (supportsRawSurround && !supportsIEC61937) {
5306 formats.add(AUDIO_FORMAT_IEC61937);
5307 // supportsIEC61937 = true;
5308 }
5309 // Just for debugging.
5310 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5311 audio_format_t format = formats[formatIndex];
5312 ALOGI("%s: final formats: #%x", __FUNCTION__, format);
5313 }
5314}
5315
François Gaffie112b0af2015-11-19 16:13:25 +01005316void AudioPolicyManager::updateAudioProfiles(audio_io_handle_t ioHandle,
5317 AudioProfileVector &profiles)
5318{
5319 String8 reply;
5320 char *value;
5321 // Format MUST be checked first to update the list of AudioProfile
5322 if (profiles.hasDynamicFormat()) {
5323 reply = mpClientInterface->getParameters(ioHandle,
5324 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk09bc4612016-02-24 15:58:15 -08005325 ALOGI("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005326 AudioParameter repliedParameters(reply);
5327 if (repliedParameters.get(
5328 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005329 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5330 return;
5331 }
Phil Burk09bc4612016-02-24 15:58:15 -08005332 FormatVector formats = formatsFromString(reply.string());
5333 filterSurroundFormats(formats);
5334 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005335 }
5336 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5337
Eric Laurent20eb3a42016-01-26 18:39:17 -08005338 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005339 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005340 ChannelsVector channelMasks;
5341 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005342 AudioParameter requestedParameters;
5343 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5344
5345 if (profiles.hasDynamicRateFor(format)) {
5346 reply = mpClientInterface->getParameters(ioHandle,
5347 requestedParameters.toString() + ";" +
5348 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5349 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005350 AudioParameter repliedParameters(reply);
5351 if (repliedParameters.get(
5352 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5353 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005354 }
5355 }
5356 if (profiles.hasDynamicChannelsFor(format)) {
5357 reply = mpClientInterface->getParameters(ioHandle,
5358 requestedParameters.toString() + ";" +
5359 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5360 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005361 AudioParameter repliedParameters(reply);
5362 if (repliedParameters.get(
5363 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5364 channelMasks = channelMasksFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005365 }
5366 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005367 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005368 }
5369}
Eric Laurentd60560a2015-04-10 11:31:20 -07005370
Eric Laurente552edb2014-03-10 17:42:56 -07005371}; // namespace android