blob: 8637c94830f5283bc225c2cc529d263be09673af [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 Laurent232f26f2016-02-17 18:06:27 -0800423 audio_io_handle_t activeInput = mInputs.getActiveInput();
424 if (activeInput != 0) {
425 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
426 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
427 //FIXME: consider all active sessions
428 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
429 audio_session_t activeSession = activeSessions.keyAt(0);
430 stopInput(activeInput, activeSession);
431 releaseInput(activeInput, activeSession);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700432 }
433 }
434
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
436 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
437 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
438 status);
439 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100440 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441 mCallTxPatch->mAfPatchHandle = afPatchHandle;
442 mCallTxPatch->mUid = mUidCached;
443 }
444 }
445}
446
Eric Laurente0720872014-03-11 09:30:41 -0700447void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700448{
449 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100450 // store previous phone state for management of sonification strategy below
451 int oldState = mEngine->getPhoneState();
452
453 if (mEngine->setPhoneState(state) != NO_ERROR) {
454 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700455 return;
456 }
François Gaffie2110e042015-03-24 08:41:51 +0100457 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700458 // if leaving call state, handle special case of active streams
459 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700460 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700461 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700462 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800463 if (stream == AUDIO_STREAM_PATCH) {
464 continue;
465 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700466 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700467 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800468
Eric Laurent63dea1d2015-07-02 17:10:28 -0700469 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800470 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700471 }
472
François Gaffie2110e042015-03-24 08:41:51 +0100473 /**
474 * Switching to or from incall state or switching between telephony and VoIP lead to force
475 * routing command.
476 */
477 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
478 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700479
480 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700481 checkA2dpSuspend();
482 checkOutputForAllStrategies();
483 updateDevicesAndOutputs();
484
Eric Laurente552edb2014-03-10 17:42:56 -0700485 int delayMs = 0;
486 if (isStateInCall(state)) {
487 nsecs_t sysTime = systemTime();
488 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700489 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700490 // mute media and sonification strategies and delay device switch by the largest
491 // latency of any output where either strategy is active.
492 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100493 if ((isStrategyActive(desc, STRATEGY_MEDIA,
494 SONIFICATION_HEADSET_MUSIC_DELAY,
495 sysTime) ||
496 isStrategyActive(desc, STRATEGY_SONIFICATION,
497 SONIFICATION_HEADSET_MUSIC_DELAY,
498 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700499 (delayMs < (int)desc->latency()*2)) {
500 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700501 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700502 setStrategyMute(STRATEGY_MEDIA, true, desc);
503 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700504 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700505 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
506 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700507 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
508 }
509 }
510
Eric Laurent87ffa392015-05-22 10:32:38 -0700511 if (hasPrimaryOutput()) {
512 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
513 // the device returned is not necessarily reachable via this output
514 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
515 // force routing command to audio hardware when ending call
516 // even if no device change is needed
517 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
518 rxDevice = mPrimaryOutput->device();
519 }
Eric Laurente552edb2014-03-10 17:42:56 -0700520
Eric Laurent87ffa392015-05-22 10:32:38 -0700521 if (state == AUDIO_MODE_IN_CALL) {
522 updateCallRouting(rxDevice, delayMs);
523 } else if (oldState == AUDIO_MODE_IN_CALL) {
524 if (mCallRxPatch != 0) {
525 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
526 mCallRxPatch.clear();
527 }
528 if (mCallTxPatch != 0) {
529 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
530 mCallTxPatch.clear();
531 }
532 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
533 } else {
534 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700535 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700536 }
Eric Laurente552edb2014-03-10 17:42:56 -0700537 // if entering in call state, handle special case of active streams
538 // pertaining to sonification strategy see handleIncallSonification()
539 if (isStateInCall(state)) {
540 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700541 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800542 if (stream == AUDIO_STREAM_PATCH) {
543 continue;
544 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700545 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700546 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700547
548 // force reevaluating accessibility routing when call starts
549 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700550 }
551
552 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700553 if (state == AUDIO_MODE_RINGTONE &&
554 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700555 mLimitRingtoneVolume = true;
556 } else {
557 mLimitRingtoneVolume = false;
558 }
559}
560
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700561audio_mode_t AudioPolicyManager::getPhoneState() {
562 return mEngine->getPhoneState();
563}
564
Eric Laurente0720872014-03-11 09:30:41 -0700565void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700566 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700567{
François Gaffie2110e042015-03-24 08:41:51 +0100568 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700569
Phil Burk09bc4612016-02-24 15:58:15 -0800570 audio_policy_forced_cfg_t originalConfig = mEngine->getForceUse(usage);
François Gaffie2110e042015-03-24 08:41:51 +0100571 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
572 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
573 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700574 }
François Gaffie2110e042015-03-24 08:41:51 +0100575 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
576 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
577 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700578
579 // check for device and output changes triggered by new force usage
580 checkA2dpSuspend();
581 checkOutputForAllStrategies();
582 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800583
584 // Did surround forced use change?
585 if ((usage == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND)
586 && (originalConfig != config)) {
587 const char *device_address = "";
588 // Is it currently connected? If so then cycle the connection
589 // so that the supported surround formats will be reloaded.
590 //
591 // FIXME As S/PDIF is not a removable device we have to handle this differently.
592 // Probably by updating the device descriptor directly and manually
593 // tearing down active playback on S/PDIF
594 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_HDMI, device_address) ==
595 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
596 // Disconnect and reconnect output devices so that the surround
597 // encodings can be updated.
598 const char *device_name = "";
599 // disconnect
600 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
601 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
602 device_address, device_name);
603 // reconnect
604 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
605 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
606 device_address, device_name);
607 }
608 }
609
Eric Laurent87ffa392015-05-22 10:32:38 -0700610 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700611 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
612 updateCallRouting(newDevice);
613 }
Eric Laurente552edb2014-03-10 17:42:56 -0700614 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700615 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
616 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
617 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
618 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 }
Eric Laurente552edb2014-03-10 17:42:56 -0700620 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700621 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700622 }
623 }
624
Eric Laurent232f26f2016-02-17 18:06:27 -0800625 audio_io_handle_t activeInput = mInputs.getActiveInput();
626 if (activeInput != 0) {
627 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
628 audio_devices_t newDevice = getNewInputDevice(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700629 // Force new input selection if the new device can not be reached via current input
Eric Laurent232f26f2016-02-17 18:06:27 -0800630 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
631 setInputDevice(activeInput, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700632 } else {
Eric Laurent232f26f2016-02-17 18:06:27 -0800633 closeInput(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700634 }
Eric Laurente552edb2014-03-10 17:42:56 -0700635 }
Eric Laurente552edb2014-03-10 17:42:56 -0700636}
637
Eric Laurente0720872014-03-11 09:30:41 -0700638void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700639{
640 ALOGV("setSystemProperty() property %s, value %s", property, value);
641}
642
643// Find a direct output profile compatible with the parameters passed, even if the input flags do
644// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800645sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700646 audio_devices_t device,
647 uint32_t samplingRate,
648 audio_format_t format,
649 audio_channel_mask_t channelMask,
650 audio_output_flags_t flags)
651{
Eric Laurent861a6282015-05-18 15:40:16 -0700652 // only retain flags that will drive the direct output profile selection
653 // if explicitly requested
654 static const uint32_t kRelevantFlags =
655 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
656 flags =
657 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
658
659 sp<IOProfile> profile;
660
Eric Laurente552edb2014-03-10 17:42:56 -0700661 for (size_t i = 0; i < mHwModules.size(); i++) {
662 if (mHwModules[i]->mHandle == 0) {
663 continue;
664 }
665 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700666 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
667 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700668 samplingRate, NULL /*updatedSamplingRate*/,
669 format, NULL /*updatedFormat*/,
670 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700671 flags)) {
672 continue;
673 }
674 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100675 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700676 continue;
677 }
678 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100679 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700680 continue;
681 }
682 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100683 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700684 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 }
687 }
Eric Laurent861a6282015-05-18 15:40:16 -0700688 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700689}
690
Eric Laurente0720872014-03-11 09:30:41 -0700691audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100692 uint32_t samplingRate,
693 audio_format_t format,
694 audio_channel_mask_t channelMask,
695 audio_output_flags_t flags,
696 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700697{
Eric Laurent3b73df72014-03-11 09:06:29 -0700698 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700699 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
700 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
701 device, stream, samplingRate, format, channelMask, flags);
702
Eric Laurente83b55d2014-11-14 10:06:21 -0800703 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
704 stream, samplingRate,format, channelMask,
705 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700706}
707
Eric Laurente83b55d2014-11-14 10:06:21 -0800708status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
709 audio_io_handle_t *output,
710 audio_session_t session,
711 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700712 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800713 uint32_t samplingRate,
714 audio_format_t format,
715 audio_channel_mask_t channelMask,
716 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700717 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800718 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700719{
Eric Laurente83b55d2014-11-14 10:06:21 -0800720 audio_attributes_t attributes;
721 if (attr != NULL) {
722 if (!isValidAttributes(attr)) {
723 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
724 attr->usage, attr->content_type, attr->flags,
725 attr->tags);
726 return BAD_VALUE;
727 }
728 attributes = *attr;
729 } else {
730 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
731 ALOGE("getOutputForAttr(): invalid stream type");
732 return BAD_VALUE;
733 }
734 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700735 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700736 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800737 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100738 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800739 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100740 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800741 }
François Gaffie036e1e92015-03-19 10:16:24 +0100742 *stream = streamTypefromAttributesInt(&attributes);
743 *output = desc->mIoHandle;
744 ALOGV("getOutputForAttr() returns output %d", *output);
745 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800746 }
747 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
748 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
749 return BAD_VALUE;
750 }
751
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700752 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
753 " session %d selectedDeviceId %d",
754 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
755 session, selectedDeviceId);
756
757 *stream = streamTypefromAttributesInt(&attributes);
758
759 // Explicit routing?
760 sp<DeviceDescriptor> deviceDesc;
761 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
762 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
763 deviceDesc = mAvailableOutputDevices[i];
764 break;
765 }
766 }
767 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768
Eric Laurente83b55d2014-11-14 10:06:21 -0800769 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700770 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700771
Eric Laurente83b55d2014-11-14 10:06:21 -0800772 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700773 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
774 }
775
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700776 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700777 device, samplingRate, format, channelMask, flags);
778
Eric Laurente83b55d2014-11-14 10:06:21 -0800779 *output = getOutputForDevice(device, session, *stream,
780 samplingRate, format, channelMask,
781 flags, offloadInfo);
782 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700783 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800784 return INVALID_OPERATION;
785 }
Paul McLeanaa981192015-03-21 09:55:15 -0700786
Eric Laurente83b55d2014-11-14 10:06:21 -0800787 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700788}
789
790audio_io_handle_t AudioPolicyManager::getOutputForDevice(
791 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800792 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700793 audio_stream_type_t stream,
794 uint32_t samplingRate,
795 audio_format_t format,
796 audio_channel_mask_t channelMask,
797 audio_output_flags_t flags,
798 const audio_offload_info_t *offloadInfo)
799{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700800 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700801 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700802 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700803
Eric Laurente552edb2014-03-10 17:42:56 -0700804#ifdef AUDIO_POLICY_TEST
805 if (mCurOutput != 0) {
806 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
807 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
808
809 if (mTestOutputs[mCurOutput] == 0) {
810 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700811 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
812 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700813 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700814 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700815 outputDesc->mFlags =
816 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700818 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
819 config.sample_rate = mTestSamplingRate;
820 config.channel_mask = mTestChannels;
821 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700822 if (offloadInfo != NULL) {
823 config.offload_info = *offloadInfo;
824 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700825 status = mpClientInterface->openOutput(0,
826 &mTestOutputs[mCurOutput],
827 &config,
828 &outputDesc->mDevice,
829 String8(""),
830 &outputDesc->mLatency,
831 outputDesc->mFlags);
832 if (status == NO_ERROR) {
833 outputDesc->mSamplingRate = config.sample_rate;
834 outputDesc->mFormat = config.format;
835 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700836 AudioParameter outputCmd = AudioParameter();
837 outputCmd.addInt(String8("set_id"),mCurOutput);
838 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
839 addOutput(mTestOutputs[mCurOutput], outputDesc);
840 }
841 }
842 return mTestOutputs[mCurOutput];
843 }
844#endif //AUDIO_POLICY_TEST
845
846 // open a direct output if required by specified parameters
847 //force direct flag if offload flag is set: offloading implies a direct output stream
848 // and all common behaviors are driven by checking only the direct flag
849 // this should normally be set appropriately in the policy configuration file
850 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700851 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700852 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700853 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
854 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
855 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800856 // only allow deep buffering for music stream type
857 if (stream != AUDIO_STREAM_MUSIC) {
858 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700859 } else if (/* stream == AUDIO_STREAM_MUSIC && */
860 flags == AUDIO_OUTPUT_FLAG_NONE &&
861 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
862 // use DEEP_BUFFER as default output for music stream type
863 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800864 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700865 if (stream == AUDIO_STREAM_TTS) {
866 flags = AUDIO_OUTPUT_FLAG_TTS;
867 }
Eric Laurente552edb2014-03-10 17:42:56 -0700868
Eric Laurentb732cf52014-09-24 19:08:21 -0700869 sp<IOProfile> profile;
870
871 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700872 // and not explicitly requested
873 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800874 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700875 audio_channel_count_from_out_mask(channelMask) <= 2) {
876 goto non_direct_output;
877 }
878
Andy Hung2ddee192015-12-18 17:34:44 -0800879 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
880 // This prevents creating an offloaded track and tearing it down immediately after start
881 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700882 // FIXME: We should check the audio session here but we do not have it in this context.
883 // This may prevent offloading in rare situations where effects are left active by apps
884 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700885
Eric Laurente552edb2014-03-10 17:42:56 -0700886 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800887 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700888 profile = getProfileForDirectOutput(device,
889 samplingRate,
890 format,
891 channelMask,
892 (audio_output_flags_t)flags);
893 }
894
Eric Laurent1c333e22014-05-20 10:48:17 -0700895 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700896 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700897
898 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700899 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700900 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
901 outputDesc = desc;
902 // reuse direct output if currently open and configured with same parameters
903 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800904 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700905 (channelMask == outputDesc->mChannelMask)) {
906 outputDesc->mDirectOpenCount++;
907 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
908 return mOutputs.keyAt(i);
909 }
910 }
911 }
912 // close direct output if currently open and configured with different parameters
913 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700915 }
Eric Laurent861a6282015-05-18 15:40:16 -0700916
917 // if the selected profile is offloaded and no offload info was specified,
918 // create a default one
919 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100920 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700921 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
922 defaultOffloadInfo.sample_rate = samplingRate;
923 defaultOffloadInfo.channel_mask = channelMask;
924 defaultOffloadInfo.format = format;
925 defaultOffloadInfo.stream_type = stream;
926 defaultOffloadInfo.bit_rate = 0;
927 defaultOffloadInfo.duration_us = -1;
928 defaultOffloadInfo.has_video = true; // conservative
929 defaultOffloadInfo.is_streaming = true; // likely
930 offloadInfo = &defaultOffloadInfo;
931 }
932
Eric Laurentc75307b2015-03-17 15:29:32 -0700933 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700934 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700935 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700936 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700937 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
938 config.sample_rate = samplingRate;
939 config.channel_mask = channelMask;
940 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700941 if (offloadInfo != NULL) {
942 config.offload_info = *offloadInfo;
943 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700944 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700945 &output,
946 &config,
947 &outputDesc->mDevice,
948 String8(""),
949 &outputDesc->mLatency,
950 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700951
952 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700953 if (status != NO_ERROR ||
954 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800955 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700956 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700957 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
958 "format %d %d, channelMask %04x %04x", output, samplingRate,
959 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
960 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700961 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700962 mpClientInterface->closeOutput(output);
963 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800964 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800965 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800966 goto non_direct_output;
967 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700968 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700969 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700970 outputDesc->mSamplingRate = config.sample_rate;
971 outputDesc->mChannelMask = config.channel_mask;
972 outputDesc->mFormat = config.format;
973 outputDesc->mRefCount[stream] = 0;
974 outputDesc->mStopTime[stream] = 0;
975 outputDesc->mDirectOpenCount = 1;
976
Eric Laurente552edb2014-03-10 17:42:56 -0700977 audio_io_handle_t srcOutput = getOutputForEffect();
978 addOutput(output, outputDesc);
979 audio_io_handle_t dstOutput = getOutputForEffect();
980 if (dstOutput == output) {
981 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
982 }
983 mPreviousOutputs = mOutputs;
984 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700985 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700986 return output;
987 }
988
Eric Laurentb732cf52014-09-24 19:08:21 -0700989non_direct_output:
Eric Laurente552edb2014-03-10 17:42:56 -0700990 // ignoring channel mask due to downmix capability in mixer
991
992 // open a non direct output
993
994 // for non direct outputs, only PCM is supported
995 if (audio_is_linear_pcm(format)) {
996 // get which output is suitable for the specified stream. The actual
997 // routing change will happen when startOutput() will be called
998 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
999
Eric Laurent8838a382014-09-08 16:44:28 -07001000 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1001 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1002 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001003 }
1004 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1005 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1006
Paul McLeanaa981192015-03-21 09:55:15 -07001007 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001008
1009 return output;
1010}
1011
Eric Laurente0720872014-03-11 09:30:41 -07001012audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001013 audio_output_flags_t flags,
1014 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001015{
1016 // select one output among several that provide a path to a particular device or set of
1017 // devices (the list was previously build by getOutputsForDevice()).
1018 // The priority is as follows:
1019 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001020 // 2: the output with the bit depth the closest to the requested one
1021 // 3: the primary output
1022 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001023
1024 if (outputs.size() == 0) {
1025 return 0;
1026 }
1027 if (outputs.size() == 1) {
1028 return outputs[0];
1029 }
1030
1031 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001032 audio_io_handle_t outputForFlags = 0;
1033 audio_io_handle_t outputForPrimary = 0;
1034 audio_io_handle_t outputForFormat = 0;
1035 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1036 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001037
1038 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001039 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001040 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001041 // if a valid format is specified, skip output if not compatible
1042 if (format != AUDIO_FORMAT_INVALID) {
1043 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001044 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001045 continue;
1046 }
1047 } else if (!audio_is_linear_pcm(format)) {
1048 continue;
1049 }
Eric Laurente6930022016-02-11 10:20:40 -08001050 if (AudioPort::isBetterFormatMatch(
1051 outputDesc->mFormat, bestFormat, format)) {
1052 outputForFormat = outputs[i];
1053 bestFormat = outputDesc->mFormat;
1054 }
Eric Laurent8838a382014-09-08 16:44:28 -07001055 }
1056
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001057 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001058 if (commonFlags >= maxCommonFlags) {
1059 if (commonFlags == maxCommonFlags) {
1060 if (AudioPort::isBetterFormatMatch(
1061 outputDesc->mFormat, bestFormatForFlags, format)) {
1062 outputForFlags = outputs[i];
1063 bestFormatForFlags = outputDesc->mFormat;
1064 }
1065 } else {
1066 outputForFlags = outputs[i];
1067 maxCommonFlags = commonFlags;
1068 bestFormatForFlags = outputDesc->mFormat;
1069 }
Eric Laurente552edb2014-03-10 17:42:56 -07001070 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1071 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001072 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001073 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001074 }
1075 }
1076 }
1077
Eric Laurente6930022016-02-11 10:20:40 -08001078 if (outputForFlags != 0) {
1079 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001080 }
Eric Laurente6930022016-02-11 10:20:40 -08001081 if (outputForFormat != 0) {
1082 return outputForFormat;
1083 }
1084 if (outputForPrimary != 0) {
1085 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001086 }
1087
1088 return outputs[0];
1089}
1090
Eric Laurente0720872014-03-11 09:30:41 -07001091status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001092 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001093 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001094{
Paul McLeanaa981192015-03-21 09:55:15 -07001095 ALOGV("startOutput() output %d, stream %d, session %d",
1096 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001097 ssize_t index = mOutputs.indexOfKey(output);
1098 if (index < 0) {
1099 ALOGW("startOutput() unknown output %d", output);
1100 return BAD_VALUE;
1101 }
1102
Eric Laurentc75307b2015-03-17 15:29:32 -07001103 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1104
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001105 // Routing?
1106 mOutputRoutes.incRouteActivity(session);
1107
Eric Laurentc75307b2015-03-17 15:29:32 -07001108 audio_devices_t newDevice;
1109 if (outputDesc->mPolicyMix != NULL) {
1110 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent493404d2015-04-21 15:07:36 -07001111 } else if (mOutputRoutes.hasRouteChanged(session)) {
1112 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001113 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001114 } else {
1115 newDevice = AUDIO_DEVICE_NONE;
1116 }
1117
1118 uint32_t delayMs = 0;
1119
Eric Laurentc75307b2015-03-17 15:29:32 -07001120 status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
1121
1122 if (status != NO_ERROR) {
1123 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001124 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001125 }
1126 // Automatically enable the remote submix input when output is started on a re routing mix
1127 // of type MIX_TYPE_RECORDERS
1128 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1129 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1130 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1131 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1132 outputDesc->mPolicyMix->mRegistrationId,
1133 "remote-submix");
1134 }
1135
1136 if (delayMs != 0) {
1137 usleep(delayMs * 1000);
1138 }
1139
1140 return status;
1141}
1142
1143status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1144 audio_stream_type_t stream,
1145 audio_devices_t device,
1146 uint32_t *delayMs)
1147{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001148 // cannot start playback of STREAM_TTS if any other output is being used
1149 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001150
1151 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001152 if (stream == AUDIO_STREAM_TTS) {
1153 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001154 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001155 return INVALID_OPERATION;
1156 } else {
1157 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1158 }
1159 } else {
1160 // some playback other than beacon starts
1161 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1162 }
1163
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001164 // check active before incrementing usage count
1165 bool force = !outputDesc->isActive();
1166
Eric Laurente552edb2014-03-10 17:42:56 -07001167 // increment usage count for this stream on the requested output:
1168 // NOTE that the usage count is the same for duplicated output and hardware output which is
1169 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1170 outputDesc->changeRefCount(stream, 1);
1171
Eric Laurent493404d2015-04-21 15:07:36 -07001172 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001173 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001174 if (device == AUDIO_DEVICE_NONE) {
1175 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001176 }
Eric Laurente552edb2014-03-10 17:42:56 -07001177 routing_strategy strategy = getStrategy(stream);
1178 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001179 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1180 (beaconMuteLatency > 0);
1181 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001182 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001183 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001184 if (desc != outputDesc) {
1185 // force a device change if any other output is managed by the same hw
1186 // module and has a current device selection that differs from selected device.
1187 // In this case, the audio HAL must receive the new device selection so that it can
1188 // change the device currently selected by the other active output.
1189 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001190 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001191 force = true;
1192 }
1193 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001194 // a notification so that audio focus effect can propagate, or that a mute/unmute
1195 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001196 uint32_t latency = desc->latency();
1197 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1198 waitMs = latency;
1199 }
1200 }
1201 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001202 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
Eric Laurente552edb2014-03-10 17:42:56 -07001203
1204 // handle special case for sonification while in call
1205 if (isInCall()) {
1206 handleIncallSonification(stream, true, false);
1207 }
1208
1209 // apply volume rules for current stream and device if necessary
1210 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001211 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001212 outputDesc,
1213 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001214
1215 // update the outputs if starting an output with a stream that can affect notification
1216 // routing
1217 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001218
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001219 // force reevaluating accessibility routing when ringtone or alarm starts
1220 if (strategy == STRATEGY_SONIFICATION) {
1221 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1222 }
Eric Laurente552edb2014-03-10 17:42:56 -07001223 }
1224 return NO_ERROR;
1225}
1226
1227
Eric Laurente0720872014-03-11 09:30:41 -07001228status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001229 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001230 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001231{
1232 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1233 ssize_t index = mOutputs.indexOfKey(output);
1234 if (index < 0) {
1235 ALOGW("stopOutput() unknown output %d", output);
1236 return BAD_VALUE;
1237 }
1238
Eric Laurentc75307b2015-03-17 15:29:32 -07001239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001240
Eric Laurentc75307b2015-03-17 15:29:32 -07001241 if (outputDesc->mRefCount[stream] == 1) {
1242 // Automatically disable the remote submix input when output is stopped on a
1243 // re routing mix of type MIX_TYPE_RECORDERS
1244 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1245 outputDesc->mPolicyMix != NULL &&
1246 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1247 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1248 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1249 outputDesc->mPolicyMix->mRegistrationId,
1250 "remote-submix");
1251 }
1252 }
1253
1254 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001255 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001256 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001257 int activityCount = mOutputRoutes.decRouteActivity(session);
1258 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1259
1260 if (forceDeviceUpdate) {
1261 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1262 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001263 }
1264
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001265 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001266}
1267
1268status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001269 audio_stream_type_t stream,
1270 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001271{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001272 // always handle stream stop, check which stream type is stopping
1273 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1274
Eric Laurente552edb2014-03-10 17:42:56 -07001275 // handle special case for sonification while in call
1276 if (isInCall()) {
1277 handleIncallSonification(stream, false, false);
1278 }
1279
1280 if (outputDesc->mRefCount[stream] > 0) {
1281 // decrement usage count of this stream on the output
1282 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001283
Eric Laurente552edb2014-03-10 17:42:56 -07001284 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001285 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001286 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001287 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001288 // delay the device switch by twice the latency because stopOutput() is executed when
1289 // the track stop() command is received and at that time the audio track buffer can
1290 // still contain data that needs to be drained. The latency only covers the audio HAL
1291 // and kernel buffers. Also the latency does not always include additional delay in the
1292 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001293 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001294
1295 // force restoring the device selection on other active outputs if it differs from the
1296 // one being selected for this output
1297 for (size_t i = 0; i < mOutputs.size(); i++) {
1298 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001299 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001300 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001301 desc->isActive() &&
1302 outputDesc->sharesHwModuleWith(desc) &&
1303 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001304 setOutputDevice(desc,
1305 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001306 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001307 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
1309 }
1310 // update the outputs if stopping one with a stream that can affect notification routing
1311 handleNotificationRoutingForStream(stream);
1312 }
1313 return NO_ERROR;
1314 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001315 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001316 return INVALID_OPERATION;
1317 }
1318}
1319
Eric Laurente83b55d2014-11-14 10:06:21 -08001320void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001321 audio_stream_type_t stream __unused,
1322 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001323{
1324 ALOGV("releaseOutput() %d", output);
1325 ssize_t index = mOutputs.indexOfKey(output);
1326 if (index < 0) {
1327 ALOGW("releaseOutput() releasing unknown output %d", output);
1328 return;
1329 }
1330
1331#ifdef AUDIO_POLICY_TEST
1332 int testIndex = testOutputIndex(output);
1333 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001334 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001335 if (outputDesc->isActive()) {
1336 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001337 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001338 mTestOutputs[testIndex] = 0;
1339 }
1340 return;
1341 }
1342#endif //AUDIO_POLICY_TEST
1343
Paul McLeanaa981192015-03-21 09:55:15 -07001344 // Routing
1345 mOutputRoutes.removeRoute(session);
1346
Eric Laurentc75307b2015-03-17 15:29:32 -07001347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001348 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001349 if (desc->mDirectOpenCount <= 0) {
1350 ALOGW("releaseOutput() invalid open count %d for output %d",
1351 desc->mDirectOpenCount, output);
1352 return;
1353 }
1354 if (--desc->mDirectOpenCount == 0) {
1355 closeOutput(output);
1356 // If effects where present on the output, audioflinger moved them to the primary
1357 // output by default: move them back to the appropriate output.
1358 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001359 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001360 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1361 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001362 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001363 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001364 }
1365 }
1366}
1367
1368
Eric Laurentcaf7f482014-11-25 17:50:47 -08001369status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1370 audio_io_handle_t *input,
1371 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001373 uint32_t samplingRate,
1374 audio_format_t format,
1375 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001376 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001377 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001378 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001379{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001380 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1381 "session %d, flags %#x",
1382 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001383
Eric Laurentcaf7f482014-11-25 17:50:47 -08001384 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001385 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001386 audio_devices_t device;
1387 // handle legacy remote submix case where the address was not always specified
1388 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001389 audio_source_t inputSource = attr->source;
1390 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001391 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001392
Eric Laurentc447ded2015-01-06 08:47:05 -08001393 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1394 inputSource = AUDIO_SOURCE_MIC;
1395 }
1396 halInputSource = inputSource;
1397
Paul McLean466dc8e2015-04-17 13:15:36 -06001398 // Explicit routing?
1399 sp<DeviceDescriptor> deviceDesc;
1400 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1401 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1402 deviceDesc = mAvailableInputDevices[i];
1403 break;
1404 }
1405 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001406 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001407
Eric Laurentc447ded2015-01-06 08:47:05 -08001408 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001409 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001410 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001411 if (ret != NO_ERROR) {
1412 return ret;
1413 }
1414 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001415 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1416 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001417 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001418 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001419 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001420 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001421 return BAD_VALUE;
1422 }
Eric Laurentc722f302014-12-10 11:21:49 -08001423 if (policyMix != NULL) {
1424 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001425 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1426 // there is an external policy, but this input is attached to a mix of recorders,
1427 // meaning it receives audio injected into the framework, so the recorder doesn't
1428 // know about it and is therefore considered "legacy"
1429 *inputType = API_INPUT_LEGACY;
1430 } else {
1431 // recording a mix of players defined by an external policy, we're rerouting for
1432 // an external policy
1433 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1434 }
Eric Laurentc722f302014-12-10 11:21:49 -08001435 } else if (audio_is_remote_submix_device(device)) {
1436 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001437 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001438 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1439 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001440 } else {
1441 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001442 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001443
Eric Laurent599c7582015-12-07 18:05:55 -08001444 }
1445
1446 *input = getInputForDevice(device, address, session, uid, inputSource,
1447 samplingRate, format, channelMask, flags,
1448 policyMix);
1449 if (*input == AUDIO_IO_HANDLE_NONE) {
1450 mInputRoutes.removeRoute(session);
1451 return INVALID_OPERATION;
1452 }
1453 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1454 return NO_ERROR;
1455}
1456
1457
1458audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1459 String8 address,
1460 audio_session_t session,
1461 uid_t uid,
1462 audio_source_t inputSource,
1463 uint32_t samplingRate,
1464 audio_format_t format,
1465 audio_channel_mask_t channelMask,
1466 audio_input_flags_t flags,
1467 AudioMix *policyMix)
1468{
1469 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1470 audio_source_t halInputSource = inputSource;
1471 bool isSoundTrigger = false;
1472
1473 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1474 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1475 if (index >= 0) {
1476 input = mSoundTriggerSessions.valueFor(session);
1477 isSoundTrigger = true;
1478 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1479 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1480 } else {
1481 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001482 }
1483 }
1484
Andy Hungf129b032015-04-07 13:45:50 -07001485 // find a compatible input profile (not necessarily identical in parameters)
1486 sp<IOProfile> profile;
1487 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001488 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001489 audio_format_t profileFormat = format;
1490 audio_channel_mask_t profileChannelMask = channelMask;
1491 audio_input_flags_t profileFlags = flags;
1492 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001493 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001494 profileSamplingRate, profileFormat, profileChannelMask,
1495 profileFlags);
1496 if (profile != 0) {
1497 break; // success
1498 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1499 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1500 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001501 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1502 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001503 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001504 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001505 }
Eric Laurente552edb2014-03-10 17:42:56 -07001506 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001507 // Pick input sampling rate if not specified by client
1508 if (samplingRate == 0) {
1509 samplingRate = profileSamplingRate;
1510 }
Eric Laurente552edb2014-03-10 17:42:56 -07001511
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 Laurent232f26f2016-02-17 18:06:27 -08001527// TODO enable input reuse
1528#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001529 // reuse an open input if possible
1530 for (size_t i = 0; i < mInputs.size(); i++) {
1531 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent232f26f2016-02-17 18:06:27 -08001532 // reuse input if it shares the same profile and same sound trigger attribute
1533 if (profile == desc->mProfile &&
1534 isSoundTrigger == desc->isSoundTrigger()) {
Eric Laurent599c7582015-12-07 18:05:55 -08001535
1536 sp<AudioSession> as = desc->getAudioSession(session);
1537 if (as != 0) {
1538 // do not allow unmatching properties on same session
1539 if (as->matches(audioSession)) {
1540 as->changeOpenCount(1);
1541 } else {
1542 ALOGW("getInputForDevice() record with different attributes"
1543 " exists for session %d", session);
Eric Laurent232f26f2016-02-17 18:06:27 -08001544 return input;
Eric Laurent599c7582015-12-07 18:05:55 -08001545 }
1546 } else {
1547 desc->addAudioSession(session, audioSession);
1548 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001549 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1550 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001551 }
1552 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001553#endif
Eric Laurent599c7582015-12-07 18:05:55 -08001554
Eric Laurentcf2c0212014-07-25 16:20:43 -07001555 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001556 config.sample_rate = profileSamplingRate;
1557 config.channel_mask = profileChannelMask;
1558 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001559
Eric Laurent322b4d22015-04-03 15:57:54 -07001560 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001561 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001562 &config,
1563 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001564 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001565 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001566 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001567
1568 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001569 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001570 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001571 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001572 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001573 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1574 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001575 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001576 if (input != AUDIO_IO_HANDLE_NONE) {
1577 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001578 }
Eric Laurent599c7582015-12-07 18:05:55 -08001579 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001580 }
1581
Eric Laurent1f2f2232014-06-02 12:01:23 -07001582 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001583 inputDesc->mSamplingRate = profileSamplingRate;
1584 inputDesc->mFormat = profileFormat;
1585 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001586 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001587 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001588 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001589
Eric Laurent599c7582015-12-07 18:05:55 -08001590 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001591 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001592
Eric Laurent599c7582015-12-07 18:05:55 -08001593 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001594}
1595
Eric Laurent4dc68062014-07-28 17:26:49 -07001596status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurent232f26f2016-02-17 18:06:27 -08001597 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001598{
1599 ALOGV("startInput() input %d", input);
1600 ssize_t index = mInputs.indexOfKey(input);
1601 if (index < 0) {
1602 ALOGW("startInput() unknown input %d", input);
1603 return BAD_VALUE;
1604 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001605 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001606
Eric Laurent599c7582015-12-07 18:05:55 -08001607 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1608 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001609 ALOGW("startInput() unknown session %d on input %d", session, input);
1610 return BAD_VALUE;
1611 }
1612
Eric Laurent232f26f2016-02-17 18:06:27 -08001613 // virtual input devices are compatible with other input devices
1614 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001615
Eric Laurent232f26f2016-02-17 18:06:27 -08001616 // for a non-virtual input device, check if there is another (non-virtual) active input
1617 audio_io_handle_t activeInput = mInputs.getActiveInput();
1618 if (activeInput != 0 && activeInput != input) {
Eric Laurente552edb2014-03-10 17:42:56 -07001619
Eric Laurent232f26f2016-02-17 18:06:27 -08001620 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1621 // otherwise the active input continues and the new input cannot be started.
1622 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1623 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
1624 !activeDesc->hasPreemptedSession(session)) {
1625 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1626 //FIXME: consider all active sessions
1627 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1628 audio_session_t activeSession = activeSessions.keyAt(0);
1629 SortedVector<audio_session_t> sessions =
1630 activeDesc->getPreemptedSessions();
1631 sessions.add(activeSession);
1632 inputDesc->setPreemptedSessions(sessions);
1633 stopInput(activeInput, activeSession);
1634 releaseInput(activeInput, activeSession);
1635 } else {
1636 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1637 return INVALID_OPERATION;
1638 }
1639 }
1640
1641 // Do not allow capture if an active voice call is using a software patch and
1642 // the call TX source device is on the same HW module.
1643 // FIXME: would be better to refine to only inputs whose profile connects to the
1644 // call TX device but this information is not in the audio patch
1645 if (mCallTxPatch != 0 &&
1646 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1647 return INVALID_OPERATION;
1648 }
1649 }
Eric Laurent313d1e72016-01-29 09:56:57 -08001650
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001651 // Routing?
1652 mInputRoutes.incRouteActivity(session);
1653
Eric Laurent232f26f2016-02-17 18:06:27 -08001654 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
1655 // if input maps to a dynamic policy with an activity listener, notify of state change
1656 if ((inputDesc->mPolicyMix != NULL)
1657 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1658 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1659 MIX_STATE_MIXING);
1660 }
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001661
Eric Laurent232f26f2016-02-17 18:06:27 -08001662 if (mInputs.activeInputsCount() == 0) {
1663 SoundTrigger::setCaptureState(true);
1664 }
1665 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001666
Eric Laurent232f26f2016-02-17 18:06:27 -08001667 // automatically enable the remote submix output when input is started if not
1668 // used by a policy mix of type MIX_TYPE_RECORDERS
1669 // For remote submix (a virtual device), we open only one input per capture request.
1670 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1671 String8 address = String8("");
1672 if (inputDesc->mPolicyMix == NULL) {
1673 address = String8("0");
1674 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1675 address = inputDesc->mPolicyMix->mRegistrationId;
Eric Laurentc722f302014-12-10 11:21:49 -08001676 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001677 if (address != "") {
1678 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1679 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1680 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001681 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001682 }
Eric Laurente552edb2014-03-10 17:42:56 -07001683 }
1684
Eric Laurent599c7582015-12-07 18:05:55 -08001685 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001686
Eric Laurent232f26f2016-02-17 18:06:27 -08001687 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001688 return NO_ERROR;
1689}
1690
Eric Laurent4dc68062014-07-28 17:26:49 -07001691status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1692 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001693{
1694 ALOGV("stopInput() input %d", input);
1695 ssize_t index = mInputs.indexOfKey(input);
1696 if (index < 0) {
1697 ALOGW("stopInput() unknown input %d", input);
1698 return BAD_VALUE;
1699 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001700 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001701
Eric Laurent599c7582015-12-07 18:05:55 -08001702 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001703 if (index < 0) {
1704 ALOGW("stopInput() unknown session %d on input %d", session, input);
1705 return BAD_VALUE;
1706 }
1707
Eric Laurent599c7582015-12-07 18:05:55 -08001708 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001709 ALOGW("stopInput() input %d already stopped", input);
1710 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001711 }
1712
Eric Laurent599c7582015-12-07 18:05:55 -08001713 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001714
1715 // Routing?
1716 mInputRoutes.decRouteActivity(session);
1717
Eric Laurent232f26f2016-02-17 18:06:27 -08001718 if (!inputDesc->isActive()) {
1719 // if input maps to a dynamic policy with an activity listener, notify of state change
1720 if ((inputDesc->mPolicyMix != NULL)
1721 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1722 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1723 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001724 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001725
1726 // automatically disable the remote submix output when input is stopped if not
1727 // used by a policy mix of type MIX_TYPE_RECORDERS
1728 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1729 String8 address = String8("");
1730 if (inputDesc->mPolicyMix == NULL) {
1731 address = String8("0");
1732 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1733 address = inputDesc->mPolicyMix->mRegistrationId;
1734 }
1735 if (address != "") {
1736 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1737 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1738 address, "remote-submix");
1739 }
1740 }
1741
1742 resetInputDevice(input);
1743
1744 if (mInputs.activeInputsCount() == 0) {
1745 SoundTrigger::setCaptureState(false);
1746 }
1747 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001748 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001749 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001750}
1751
Eric Laurent4dc68062014-07-28 17:26:49 -07001752void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1753 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001754{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001755
Eric Laurente552edb2014-03-10 17:42:56 -07001756 ALOGV("releaseInput() %d", input);
1757 ssize_t index = mInputs.indexOfKey(input);
1758 if (index < 0) {
1759 ALOGW("releaseInput() releasing unknown input %d", input);
1760 return;
1761 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001762
1763 // Routing
1764 mInputRoutes.removeRoute(session);
1765
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001766 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1767 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001768
Eric Laurent599c7582015-12-07 18:05:55 -08001769 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001770 if (index < 0) {
1771 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1772 return;
1773 }
Eric Laurent599c7582015-12-07 18:05:55 -08001774
1775 if (audioSession->openCount() == 0) {
1776 ALOGW("releaseInput() invalid open count %d on session %d",
1777 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001778 return;
1779 }
Eric Laurent599c7582015-12-07 18:05:55 -08001780
1781 if (audioSession->changeOpenCount(-1) == 0) {
1782 inputDesc->removeAudioSession(session);
1783 }
1784
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001785 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001786 ALOGV("releaseInput() exit > 0");
1787 return;
1788 }
1789
Eric Laurent05b90f82014-08-27 15:32:29 -07001790 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001791 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001792 ALOGV("releaseInput() exit");
1793}
1794
Eric Laurentd4692962014-05-05 18:13:44 -07001795void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001796 bool patchRemoved = false;
1797
Eric Laurentd4692962014-05-05 18:13:44 -07001798 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001799 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001800 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001801 if (patch_index >= 0) {
1802 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1803 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1804 mAudioPatches.removeItemsAt(patch_index);
1805 patchRemoved = true;
1806 }
Eric Laurentd4692962014-05-05 18:13:44 -07001807 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1808 }
1809 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001810 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001811 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001812
1813 if (patchRemoved) {
1814 mpClientInterface->onAudioPatchListUpdate();
1815 }
Eric Laurentd4692962014-05-05 18:13:44 -07001816}
1817
Eric Laurente0720872014-03-11 09:30:41 -07001818void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001819 int indexMin,
1820 int indexMax)
1821{
1822 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001823 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001824 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01001825 mVolumeCurves->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001826 }
Eric Laurente552edb2014-03-10 17:42:56 -07001827}
1828
Eric Laurente0720872014-03-11 09:30:41 -07001829status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001830 int index,
1831 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001832{
1833
François Gaffied1ab2bd2015-12-02 18:20:06 +01001834 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1835 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001836 return BAD_VALUE;
1837 }
1838 if (!audio_is_output_device(device)) {
1839 return BAD_VALUE;
1840 }
1841
1842 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001843 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001844
1845 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1846 stream, device, index);
1847
1848 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1849 // clear all device specific values
1850 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01001851 mVolumeCurves->clearCurrentVolumeIndex(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001852 }
François Gaffied1ab2bd2015-12-02 18:20:06 +01001853 mVolumeCurves->addCurrentVolumeIndex(stream, device, index);
Eric Laurente552edb2014-03-10 17:42:56 -07001854
Eric Laurent31551f82014-10-10 18:21:56 -07001855 // update volume on all outputs whose current device is also selected by the same
1856 // strategy as the device specified by the caller
Eric Laurente04e62b2016-01-29 18:25:01 -08001857 audio_devices_t selectedDevices = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1858 // it is possible that the requested device is not selected by the strategy (e.g an explicit
1859 // audio patch is active causing getDevicesForStream() to return this device. We must make
1860 // sure that the device passed is part of the devices considered when applying volume below.
1861 selectedDevices |= device;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001862
1863 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1864 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1865 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01001866 mVolumeCurves->addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001867 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1868 }
Eric Laurente04e62b2016-01-29 18:25:01 -08001869
Eric Laurente552edb2014-03-10 17:42:56 -07001870 status_t status = NO_ERROR;
1871 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001872 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1873 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurente04e62b2016-01-29 18:25:01 -08001874 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & selectedDevices) != 0)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001875 status_t volStatus = checkAndSetVolume(stream, index, desc, curDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07001876 if (volStatus != NO_ERROR) {
1877 status = volStatus;
1878 }
1879 }
Jean-Michel Triviaf20bc22015-09-14 16:37:07 -07001880 if ((accessibilityDevice != AUDIO_DEVICE_NONE) &&
1881 ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)))
1882 {
Eric Laurent223fd5c2014-11-11 13:43:36 -08001883 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
Eric Laurentc75307b2015-03-17 15:29:32 -07001884 index, desc, curDevice);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001885 }
Eric Laurente552edb2014-03-10 17:42:56 -07001886 }
1887 return status;
1888}
1889
Eric Laurente0720872014-03-11 09:30:41 -07001890status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001891 int *index,
1892 audio_devices_t device)
1893{
1894 if (index == NULL) {
1895 return BAD_VALUE;
1896 }
1897 if (!audio_is_output_device(device)) {
1898 return BAD_VALUE;
1899 }
1900 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1901 // the strategy the stream belongs to.
1902 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1903 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1904 }
François Gaffiedfd74092015-03-19 12:10:59 +01001905 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001906
François Gaffied1ab2bd2015-12-02 18:20:06 +01001907 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07001908 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1909 return NO_ERROR;
1910}
1911
Eric Laurente0720872014-03-11 09:30:41 -07001912audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001913 const SortedVector<audio_io_handle_t>& outputs)
1914{
1915 // select one output among several suitable for global effects.
1916 // The priority is as follows:
1917 // 1: An offloaded output. If the effect ends up not being offloadable,
1918 // AudioFlinger will invalidate the track and the offloaded output
1919 // will be closed causing the effect to be moved to a PCM output.
1920 // 2: A deep buffer output
1921 // 3: the first output in the list
1922
1923 if (outputs.size() == 0) {
1924 return 0;
1925 }
1926
1927 audio_io_handle_t outputOffloaded = 0;
1928 audio_io_handle_t outputDeepBuffer = 0;
1929
1930 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001931 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001932 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001933 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1934 outputOffloaded = outputs[i];
1935 }
1936 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1937 outputDeepBuffer = outputs[i];
1938 }
1939 }
1940
1941 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1942 outputOffloaded, outputDeepBuffer);
1943 if (outputOffloaded != 0) {
1944 return outputOffloaded;
1945 }
1946 if (outputDeepBuffer != 0) {
1947 return outputDeepBuffer;
1948 }
1949
1950 return outputs[0];
1951}
1952
Eric Laurente0720872014-03-11 09:30:41 -07001953audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001954{
1955 // apply simple rule where global effects are attached to the same output as MUSIC streams
1956
Eric Laurent3b73df72014-03-11 09:06:29 -07001957 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001958 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1959 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1960
1961 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1962 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1963 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1964
1965 return output;
1966}
1967
Eric Laurente0720872014-03-11 09:30:41 -07001968status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001969 audio_io_handle_t io,
1970 uint32_t strategy,
1971 int session,
1972 int id)
1973{
1974 ssize_t index = mOutputs.indexOfKey(io);
1975 if (index < 0) {
1976 index = mInputs.indexOfKey(io);
1977 if (index < 0) {
1978 ALOGW("registerEffect() unknown io %d", io);
1979 return INVALID_OPERATION;
1980 }
1981 }
François Gaffie45ed3b02015-03-19 10:35:14 +01001982 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07001983}
1984
Eric Laurentc75307b2015-03-17 15:29:32 -07001985bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1986{
1987 return mOutputs.isStreamActive(stream, inPastMs);
1988}
1989
1990bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
1991{
1992 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
1993}
1994
Eric Laurente0720872014-03-11 09:30:41 -07001995bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001996{
1997 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001998 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001999 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002000 return true;
2001 }
2002 }
2003 return false;
2004}
2005
Eric Laurent275e8e92014-11-30 15:14:47 -08002006// Register a list of custom mixes with their attributes and format.
2007// When a mix is registered, corresponding input and output profiles are
2008// added to the remote submix hw module. The profile contains only the
2009// parameters (sampling rate, format...) specified by the mix.
2010// The corresponding input remote submix device is also connected.
2011//
2012// When a remote submix device is connected, the address is checked to select the
2013// appropriate profile and the corresponding input or output stream is opened.
2014//
2015// When capture starts, getInputForAttr() will:
2016// - 1 look for a mix matching the address passed in attribtutes tags if any
2017// - 2 if none found, getDeviceForInputSource() will:
2018// - 2.1 look for a mix matching the attributes source
2019// - 2.2 if none found, default to device selection by policy rules
2020// At this time, the corresponding output remote submix device is also connected
2021// and active playback use cases can be transferred to this mix if needed when reconnecting
2022// after AudioTracks are invalidated
2023//
2024// When playback starts, getOutputForAttr() will:
2025// - 1 look for a mix matching the address passed in attribtutes tags if any
2026// - 2 if none found, look for a mix matching the attributes usage
2027// - 3 if none found, default to device and output selection by policy rules.
2028
2029status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2030{
2031 sp<HwModule> module;
2032 for (size_t i = 0; i < mHwModules.size(); i++) {
2033 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2034 mHwModules[i]->mHandle != 0) {
2035 module = mHwModules[i];
2036 break;
2037 }
2038 }
2039
2040 if (module == 0) {
2041 return INVALID_OPERATION;
2042 }
2043
Eric Laurent7b279bb2015-12-14 10:18:23 -08002044 ALOGV("registerPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002045
2046 for (size_t i = 0; i < mixes.size(); i++) {
2047 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01002048
2049 if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002050 continue;
2051 }
2052 audio_config_t outputConfig = mixes[i].mFormat;
2053 audio_config_t inputConfig = mixes[i].mFormat;
2054 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2055 // stereo and let audio flinger do the channel conversion if needed.
2056 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2057 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2058 module->addOutputProfile(address, &outputConfig,
2059 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2060 module->addInputProfile(address, &inputConfig,
2061 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002062
Eric Laurentc722f302014-12-10 11:21:49 -08002063 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002064 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002065 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002066 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002067 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002068 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002069 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002070 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002071 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002072 }
2073 return NO_ERROR;
2074}
2075
2076status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2077{
2078 sp<HwModule> module;
2079 for (size_t i = 0; i < mHwModules.size(); i++) {
2080 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2081 mHwModules[i]->mHandle != 0) {
2082 module = mHwModules[i];
2083 break;
2084 }
2085 }
2086
2087 if (module == 0) {
2088 return INVALID_OPERATION;
2089 }
2090
Eric Laurent7b279bb2015-12-14 10:18:23 -08002091 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002092
2093 for (size_t i = 0; i < mixes.size(); i++) {
2094 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01002095
2096 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002097 continue;
2098 }
2099
Eric Laurentc722f302014-12-10 11:21:49 -08002100 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2101 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2102 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002103 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002104 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002105 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002106 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002107
2108 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2109 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2110 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002111 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002112 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002113 address.string(), "remote-submix");
Eric Laurent275e8e92014-11-30 15:14:47 -08002114 }
2115 module->removeOutputProfile(address);
2116 module->removeInputProfile(address);
2117 }
2118 return NO_ERROR;
2119}
2120
Eric Laurente552edb2014-03-10 17:42:56 -07002121
Eric Laurente0720872014-03-11 09:30:41 -07002122status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002123{
2124 const size_t SIZE = 256;
2125 char buffer[SIZE];
2126 String8 result;
2127
2128 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2129 result.append(buffer);
2130
Eric Laurent87ffa392015-05-22 10:32:38 -07002131 snprintf(buffer, SIZE, " Primary Output: %d\n",
2132 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002133 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002134 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002135 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002136 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002137 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002138 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002139 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002140 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002141 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002142 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002143 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002144 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002145 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002146 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002147 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002148 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002149 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002150 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2151 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2152 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002153 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2154 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002155 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2156 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002157
François Gaffie2110e042015-03-24 08:41:51 +01002158 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002159
François Gaffie112b0af2015-11-19 16:13:25 +01002160 mAvailableOutputDevices.dump(fd, String8("Available output"));
2161 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002162 mHwModules.dump(fd);
2163 mOutputs.dump(fd);
2164 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002165 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002166 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002167 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002168
2169 return NO_ERROR;
2170}
2171
2172// This function checks for the parameters which can be offloaded.
2173// This can be enhanced depending on the capability of the DSP and policy
2174// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002175bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002176{
2177 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002178 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002179 offloadInfo.sample_rate, offloadInfo.channel_mask,
2180 offloadInfo.format,
2181 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2182 offloadInfo.has_video);
2183
Andy Hung2ddee192015-12-18 17:34:44 -08002184 if (mMasterMono) {
2185 return false; // no offloading if mono is set.
2186 }
2187
Eric Laurente552edb2014-03-10 17:42:56 -07002188 // Check if offload has been disabled
2189 char propValue[PROPERTY_VALUE_MAX];
2190 if (property_get("audio.offload.disable", propValue, "0")) {
2191 if (atoi(propValue) != 0) {
2192 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2193 return false;
2194 }
2195 }
2196
2197 // Check if stream type is music, then only allow offload as of now.
2198 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2199 {
2200 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2201 return false;
2202 }
2203
Wei Jia7b8d4342016-02-16 17:56:37 -08002204 // Check if streaming is off, then only allow offload as of now.
Wei Jia4ca44d72016-02-17 16:56:38 -08002205 // This is a temporary work around until the root cause is fixed in offload
2206 // playback path.
Wei Jia7b8d4342016-02-16 17:56:37 -08002207 if (offloadInfo.is_streaming)
2208 {
2209 ALOGV("isOffloadSupported: is_streaming == true, returning false");
2210 return false;
2211 }
2212
Eric Laurente552edb2014-03-10 17:42:56 -07002213 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002214 const bool allowOffloadWithVideo =
2215 property_get_bool("audio.offload.video", false /* default_value */);
2216 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002217 ALOGV("isOffloadSupported: has_video == true, returning false");
2218 return false;
2219 }
2220
2221 //If duration is less than minimum value defined in property, return false
2222 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2223 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2224 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2225 return false;
2226 }
2227 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2228 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2229 return false;
2230 }
2231
2232 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2233 // creating an offloaded track and tearing it down immediately after start when audioflinger
2234 // detects there is an active non offloadable effect.
2235 // FIXME: We should check the audio session here but we do not have it in this context.
2236 // This may prevent offloading in rare situations where effects are left active by apps
2237 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002238 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002239 return false;
2240 }
2241
2242 // See if there is a profile to support this.
2243 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002244 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002245 offloadInfo.sample_rate,
2246 offloadInfo.format,
2247 offloadInfo.channel_mask,
2248 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002249 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2250 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002251}
2252
Eric Laurent6a94d692014-05-20 11:18:06 -07002253status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2254 audio_port_type_t type,
2255 unsigned int *num_ports,
2256 struct audio_port *ports,
2257 unsigned int *generation)
2258{
2259 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2260 generation == NULL) {
2261 return BAD_VALUE;
2262 }
2263 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2264 if (ports == NULL) {
2265 *num_ports = 0;
2266 }
2267
2268 size_t portsWritten = 0;
2269 size_t portsMax = *num_ports;
2270 *num_ports = 0;
2271 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2272 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2273 for (size_t i = 0;
2274 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2275 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2276 }
2277 *num_ports += mAvailableOutputDevices.size();
2278 }
2279 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2280 for (size_t i = 0;
2281 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2282 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2283 }
2284 *num_ports += mAvailableInputDevices.size();
2285 }
2286 }
2287 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2288 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2289 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2290 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2291 }
2292 *num_ports += mInputs.size();
2293 }
2294 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002295 size_t numOutputs = 0;
2296 for (size_t i = 0; i < mOutputs.size(); i++) {
2297 if (!mOutputs[i]->isDuplicated()) {
2298 numOutputs++;
2299 if (portsWritten < portsMax) {
2300 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2301 }
2302 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002303 }
Eric Laurent84c70242014-06-23 08:46:27 -07002304 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002305 }
2306 }
2307 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002308 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002309 return NO_ERROR;
2310}
2311
2312status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2313{
2314 return NO_ERROR;
2315}
2316
Eric Laurent6a94d692014-05-20 11:18:06 -07002317status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2318 audio_patch_handle_t *handle,
2319 uid_t uid)
2320{
2321 ALOGV("createAudioPatch()");
2322
2323 if (handle == NULL || patch == NULL) {
2324 return BAD_VALUE;
2325 }
2326 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2327
Eric Laurent874c42872014-08-08 15:13:39 -07002328 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2329 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2330 return BAD_VALUE;
2331 }
2332 // only one source per audio patch supported for now
2333 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002334 return INVALID_OPERATION;
2335 }
Eric Laurent874c42872014-08-08 15:13:39 -07002336
2337 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002338 return INVALID_OPERATION;
2339 }
Eric Laurent874c42872014-08-08 15:13:39 -07002340 for (size_t i = 0; i < patch->num_sinks; i++) {
2341 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2342 return INVALID_OPERATION;
2343 }
2344 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002345
2346 sp<AudioPatch> patchDesc;
2347 ssize_t index = mAudioPatches.indexOfKey(*handle);
2348
Eric Laurent6a94d692014-05-20 11:18:06 -07002349 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2350 patch->sources[0].role,
2351 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002352#if LOG_NDEBUG == 0
2353 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002354 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002355 patch->sinks[i].role,
2356 patch->sinks[i].type);
2357 }
2358#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002359
2360 if (index >= 0) {
2361 patchDesc = mAudioPatches.valueAt(index);
2362 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2363 mUidCached, patchDesc->mUid, uid);
2364 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2365 return INVALID_OPERATION;
2366 }
2367 } else {
2368 *handle = 0;
2369 }
2370
2371 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002372 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002373 if (outputDesc == NULL) {
2374 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2375 return BAD_VALUE;
2376 }
Eric Laurent84c70242014-06-23 08:46:27 -07002377 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2378 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002379 if (patchDesc != 0) {
2380 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2381 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2382 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2383 return BAD_VALUE;
2384 }
2385 }
Eric Laurent874c42872014-08-08 15:13:39 -07002386 DeviceVector devices;
2387 for (size_t i = 0; i < patch->num_sinks; i++) {
2388 // Only support mix to devices connection
2389 // TODO add support for mix to mix connection
2390 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2391 ALOGV("createAudioPatch() source mix but sink is not a device");
2392 return INVALID_OPERATION;
2393 }
2394 sp<DeviceDescriptor> devDesc =
2395 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2396 if (devDesc == 0) {
2397 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2398 return BAD_VALUE;
2399 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002400
François Gaffie53615e22015-03-19 09:24:12 +01002401 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002402 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002403 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002404 NULL, // updatedSamplingRate
2405 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002406 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002407 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002408 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002409 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002410 ALOGV("createAudioPatch() profile not supported for device %08x",
2411 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002412 return INVALID_OPERATION;
2413 }
2414 devices.add(devDesc);
2415 }
2416 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002417 return INVALID_OPERATION;
2418 }
Eric Laurent874c42872014-08-08 15:13:39 -07002419
Eric Laurent6a94d692014-05-20 11:18:06 -07002420 // TODO: reconfigure output format and channels here
2421 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002422 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002423 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002424 index = mAudioPatches.indexOfKey(*handle);
2425 if (index >= 0) {
2426 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2427 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2428 }
2429 patchDesc = mAudioPatches.valueAt(index);
2430 patchDesc->mUid = uid;
2431 ALOGV("createAudioPatch() success");
2432 } else {
2433 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2434 return INVALID_OPERATION;
2435 }
2436 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2437 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2438 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002439 // only one sink supported when connecting an input device to a mix
2440 if (patch->num_sinks > 1) {
2441 return INVALID_OPERATION;
2442 }
François Gaffie53615e22015-03-19 09:24:12 +01002443 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002444 if (inputDesc == NULL) {
2445 return BAD_VALUE;
2446 }
2447 if (patchDesc != 0) {
2448 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2449 return BAD_VALUE;
2450 }
2451 }
2452 sp<DeviceDescriptor> devDesc =
2453 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2454 if (devDesc == 0) {
2455 return BAD_VALUE;
2456 }
2457
François Gaffie53615e22015-03-19 09:24:12 +01002458 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002459 devDesc->mAddress,
2460 patch->sinks[0].sample_rate,
2461 NULL, /*updatedSampleRate*/
2462 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002463 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002464 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002465 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002466 // FIXME for the parameter type,
2467 // and the NONE
2468 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002469 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002470 return INVALID_OPERATION;
2471 }
2472 // TODO: reconfigure output format and channels here
2473 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002474 devDesc->type(), inputDesc->mIoHandle);
2475 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002476 index = mAudioPatches.indexOfKey(*handle);
2477 if (index >= 0) {
2478 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2479 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2480 }
2481 patchDesc = mAudioPatches.valueAt(index);
2482 patchDesc->mUid = uid;
2483 ALOGV("createAudioPatch() success");
2484 } else {
2485 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2486 return INVALID_OPERATION;
2487 }
2488 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2489 // device to device connection
2490 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002491 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002492 return BAD_VALUE;
2493 }
2494 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002495 sp<DeviceDescriptor> srcDeviceDesc =
2496 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002497 if (srcDeviceDesc == 0) {
2498 return BAD_VALUE;
2499 }
Eric Laurent874c42872014-08-08 15:13:39 -07002500
Eric Laurent6a94d692014-05-20 11:18:06 -07002501 //update source and sink with our own data as the data passed in the patch may
2502 // be incomplete.
2503 struct audio_patch newPatch = *patch;
2504 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002505
Eric Laurent874c42872014-08-08 15:13:39 -07002506 for (size_t i = 0; i < patch->num_sinks; i++) {
2507 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2508 ALOGV("createAudioPatch() source device but one sink is not a device");
2509 return INVALID_OPERATION;
2510 }
2511
2512 sp<DeviceDescriptor> sinkDeviceDesc =
2513 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2514 if (sinkDeviceDesc == 0) {
2515 return BAD_VALUE;
2516 }
2517 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2518
Eric Laurent3bcf8592015-04-03 12:13:24 -07002519 // create a software bridge in PatchPanel if:
2520 // - source and sink devices are on differnt HW modules OR
2521 // - audio HAL version is < 3.0
Eric Laurent232f26f2016-02-17 18:06:27 -08002522 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002523 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002524 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002525 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002526 return INVALID_OPERATION;
2527 }
Eric Laurent874c42872014-08-08 15:13:39 -07002528 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002529 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002530 // if the sink device is reachable via an opened output stream, request to go via
2531 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002532 audio_io_handle_t output = selectOutput(outputs,
2533 AUDIO_OUTPUT_FLAG_NONE,
2534 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002535 if (output != AUDIO_IO_HANDLE_NONE) {
2536 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2537 if (outputDesc->isDuplicated()) {
2538 return INVALID_OPERATION;
2539 }
2540 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002541 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002542 newPatch.num_sources = 2;
2543 }
Eric Laurent83b88082014-06-20 18:31:16 -07002544 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002545 }
2546 // TODO: check from routing capabilities in config file and other conflicting patches
2547
2548 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2549 if (index >= 0) {
2550 afPatchHandle = patchDesc->mAfPatchHandle;
2551 }
2552
2553 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2554 &afPatchHandle,
2555 0);
2556 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2557 status, afPatchHandle);
2558 if (status == NO_ERROR) {
2559 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002560 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002561 addAudioPatch(patchDesc->mHandle, patchDesc);
2562 } else {
2563 patchDesc->mPatch = newPatch;
2564 }
2565 patchDesc->mAfPatchHandle = afPatchHandle;
2566 *handle = patchDesc->mHandle;
2567 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002568 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002569 } else {
2570 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2571 status);
2572 return INVALID_OPERATION;
2573 }
2574 } else {
2575 return BAD_VALUE;
2576 }
2577 } else {
2578 return BAD_VALUE;
2579 }
2580 return NO_ERROR;
2581}
2582
2583status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2584 uid_t uid)
2585{
2586 ALOGV("releaseAudioPatch() patch %d", handle);
2587
2588 ssize_t index = mAudioPatches.indexOfKey(handle);
2589
2590 if (index < 0) {
2591 return BAD_VALUE;
2592 }
2593 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2594 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2595 mUidCached, patchDesc->mUid, uid);
2596 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2597 return INVALID_OPERATION;
2598 }
2599
2600 struct audio_patch *patch = &patchDesc->mPatch;
2601 patchDesc->mUid = mUidCached;
2602 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002603 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002604 if (outputDesc == NULL) {
2605 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2606 return BAD_VALUE;
2607 }
2608
Eric Laurentc75307b2015-03-17 15:29:32 -07002609 setOutputDevice(outputDesc,
2610 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002611 true,
2612 0,
2613 NULL);
2614 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2615 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002616 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002617 if (inputDesc == NULL) {
2618 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2619 return BAD_VALUE;
2620 }
2621 setInputDevice(inputDesc->mIoHandle,
Eric Laurent232f26f2016-02-17 18:06:27 -08002622 getNewInputDevice(inputDesc->mIoHandle),
Eric Laurent6a94d692014-05-20 11:18:06 -07002623 true,
2624 NULL);
2625 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2626 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2627 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2628 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2629 status, patchDesc->mAfPatchHandle);
2630 removeAudioPatch(patchDesc->mHandle);
2631 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002632 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002633 } else {
2634 return BAD_VALUE;
2635 }
2636 } else {
2637 return BAD_VALUE;
2638 }
2639 return NO_ERROR;
2640}
2641
2642status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2643 struct audio_patch *patches,
2644 unsigned int *generation)
2645{
François Gaffie53615e22015-03-19 09:24:12 +01002646 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002647 return BAD_VALUE;
2648 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002649 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002650 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002651}
2652
Eric Laurente1715a42014-05-20 11:30:42 -07002653status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002654{
Eric Laurente1715a42014-05-20 11:30:42 -07002655 ALOGV("setAudioPortConfig()");
2656
2657 if (config == NULL) {
2658 return BAD_VALUE;
2659 }
2660 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2661 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002662 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2663 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002664 }
2665
Eric Laurenta121f902014-06-03 13:32:54 -07002666 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002667 if (config->type == AUDIO_PORT_TYPE_MIX) {
2668 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002669 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002670 if (outputDesc == NULL) {
2671 return BAD_VALUE;
2672 }
Eric Laurent84c70242014-06-23 08:46:27 -07002673 ALOG_ASSERT(!outputDesc->isDuplicated(),
2674 "setAudioPortConfig() called on duplicated output %d",
2675 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002676 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002677 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002678 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002679 if (inputDesc == NULL) {
2680 return BAD_VALUE;
2681 }
Eric Laurenta121f902014-06-03 13:32:54 -07002682 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002683 } else {
2684 return BAD_VALUE;
2685 }
2686 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2687 sp<DeviceDescriptor> deviceDesc;
2688 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2689 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2690 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2691 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2692 } else {
2693 return BAD_VALUE;
2694 }
2695 if (deviceDesc == NULL) {
2696 return BAD_VALUE;
2697 }
Eric Laurenta121f902014-06-03 13:32:54 -07002698 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002699 } else {
2700 return BAD_VALUE;
2701 }
2702
Eric Laurenta121f902014-06-03 13:32:54 -07002703 struct audio_port_config backupConfig;
2704 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2705 if (status == NO_ERROR) {
2706 struct audio_port_config newConfig;
2707 audioPortConfig->toAudioPortConfig(&newConfig, config);
2708 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002709 }
Eric Laurenta121f902014-06-03 13:32:54 -07002710 if (status != NO_ERROR) {
2711 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002712 }
Eric Laurente1715a42014-05-20 11:30:42 -07002713
2714 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002715}
2716
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002717void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2718{
Eric Laurentd60560a2015-04-10 11:31:20 -07002719 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002720 clearAudioPatches(uid);
2721 clearSessionRoutes(uid);
2722}
2723
Eric Laurent6a94d692014-05-20 11:18:06 -07002724void AudioPolicyManager::clearAudioPatches(uid_t uid)
2725{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002726 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002727 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2728 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002729 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002730 }
2731 }
2732}
2733
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002734void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2735 audio_io_handle_t ouptutToSkip)
2736{
2737 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2738 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2739 for (size_t j = 0; j < mOutputs.size(); j++) {
2740 if (mOutputs.keyAt(j) == ouptutToSkip) {
2741 continue;
2742 }
2743 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2744 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2745 continue;
2746 }
2747 // If the default device for this strategy is on another output mix,
2748 // invalidate all tracks in this strategy to force re connection.
2749 // Otherwise select new device on the output mix.
2750 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
2751 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
2752 if (stream == AUDIO_STREAM_PATCH) {
2753 continue;
2754 }
2755 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2756 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2757 }
2758 }
2759 } else {
2760 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2761 setOutputDevice(outputDesc, newDevice, false);
2762 }
2763 }
2764}
2765
2766void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2767{
2768 // remove output routes associated with this uid
2769 SortedVector<routing_strategy> affectedStrategies;
2770 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2771 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2772 if (route->mUid == uid) {
2773 mOutputRoutes.removeItemsAt(i);
2774 if (route->mDeviceDescriptor != 0) {
2775 affectedStrategies.add(getStrategy(route->mStreamType));
2776 }
2777 }
2778 }
2779 // reroute outputs if necessary
2780 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2781 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2782 }
2783
2784 // remove input routes associated with this uid
2785 SortedVector<audio_source_t> affectedSources;
2786 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2787 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2788 if (route->mUid == uid) {
2789 mInputRoutes.removeItemsAt(i);
2790 if (route->mDeviceDescriptor != 0) {
2791 affectedSources.add(route->mSource);
2792 }
2793 }
2794 }
2795 // reroute inputs if necessary
2796 SortedVector<audio_io_handle_t> inputsToClose;
2797 for (size_t i = 0; i < mInputs.size(); i++) {
2798 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002799 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002800 inputsToClose.add(inputDesc->mIoHandle);
2801 }
2802 }
2803 for (size_t i = 0; i < inputsToClose.size(); i++) {
2804 closeInput(inputsToClose[i]);
2805 }
2806}
2807
Eric Laurentd60560a2015-04-10 11:31:20 -07002808void AudioPolicyManager::clearAudioSources(uid_t uid)
2809{
2810 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2811 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2812 if (sourceDesc->mUid == uid) {
2813 stopAudioSource(mAudioSources.keyAt(i));
2814 }
2815 }
2816}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002817
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002818status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2819 audio_io_handle_t *ioHandle,
2820 audio_devices_t *device)
2821{
Glenn Kasteneeecb982016-02-26 10:44:04 -08002822 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2823 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002824 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002825
François Gaffiedf372692015-03-19 10:43:27 +01002826 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002827}
2828
Eric Laurentd60560a2015-04-10 11:31:20 -07002829status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2830 const audio_attributes_t *attributes,
2831 audio_io_handle_t *handle,
2832 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002833{
Eric Laurentd60560a2015-04-10 11:31:20 -07002834 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2835 if (source == NULL || attributes == NULL || handle == NULL) {
2836 return BAD_VALUE;
2837 }
2838
2839 *handle = AUDIO_IO_HANDLE_NONE;
2840
2841 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2842 source->type != AUDIO_PORT_TYPE_DEVICE) {
2843 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2844 return INVALID_OPERATION;
2845 }
2846
2847 sp<DeviceDescriptor> srcDeviceDesc =
2848 mAvailableInputDevices.getDevice(source->ext.device.type,
2849 String8(source->ext.device.address));
2850 if (srcDeviceDesc == 0) {
2851 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2852 return BAD_VALUE;
2853 }
2854 sp<AudioSourceDescriptor> sourceDesc =
2855 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2856
2857 struct audio_patch dummyPatch;
2858 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2859 sourceDesc->mPatchDesc = patchDesc;
2860
2861 status_t status = connectAudioSource(sourceDesc);
2862 if (status == NO_ERROR) {
2863 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2864 *handle = sourceDesc->getHandle();
2865 }
2866 return status;
2867}
2868
2869status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2870{
2871 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2872
2873 // make sure we only have one patch per source.
2874 disconnectAudioSource(sourceDesc);
2875
2876 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2877 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2878 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2879
2880 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2881 sp<DeviceDescriptor> sinkDeviceDesc =
2882 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2883
2884 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2885 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2886
2887 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2888 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002889 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002890 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2891 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2892 // create patch between src device and output device
2893 // create Hwoutput and add to mHwOutputs
2894 } else {
2895 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2896 audio_io_handle_t output =
2897 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2898 if (output == AUDIO_IO_HANDLE_NONE) {
2899 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2900 return INVALID_OPERATION;
2901 }
2902 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2903 if (outputDesc->isDuplicated()) {
2904 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2905 return INVALID_OPERATION;
2906 }
2907 // create a special patch with no sink and two sources:
2908 // - the second source indicates to PatchPanel through which output mix this patch should
2909 // be connected as well as the stream type for volume control
2910 // - the sink is defined by whatever output device is currently selected for the output
2911 // though which this patch is routed.
2912 patch->num_sinks = 0;
2913 patch->num_sources = 2;
2914 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2915 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2916 patch->sources[1].ext.mix.usecase.stream = stream;
2917 status_t status = mpClientInterface->createAudioPatch(patch,
2918 &afPatchHandle,
2919 0);
2920 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
2921 status, afPatchHandle);
2922 if (status != NO_ERROR) {
2923 ALOGW("%s patch panel could not connect device patch, error %d",
2924 __FUNCTION__, status);
2925 return INVALID_OPERATION;
2926 }
2927 uint32_t delayMs = 0;
2928 status = startSource(outputDesc, stream, sinkDevice, &delayMs);
2929
2930 if (status != NO_ERROR) {
2931 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
2932 return status;
2933 }
2934 sourceDesc->mSwOutput = outputDesc;
2935 if (delayMs != 0) {
2936 usleep(delayMs * 1000);
2937 }
2938 }
2939
2940 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
2941 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
2942
2943 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07002944}
2945
Eric Laurent493404d2015-04-21 15:07:36 -07002946status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07002947{
Eric Laurentd60560a2015-04-10 11:31:20 -07002948 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
2949 ALOGV("%s handle %d", __FUNCTION__, handle);
2950 if (sourceDesc == 0) {
2951 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
2952 return BAD_VALUE;
2953 }
2954 status_t status = disconnectAudioSource(sourceDesc);
2955
2956 mAudioSources.removeItem(handle);
2957 return status;
2958}
2959
Andy Hung2ddee192015-12-18 17:34:44 -08002960status_t AudioPolicyManager::setMasterMono(bool mono)
2961{
2962 if (mMasterMono == mono) {
2963 return NO_ERROR;
2964 }
2965 mMasterMono = mono;
2966 // if enabling mono we close all offloaded devices, which will invalidate the
2967 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
2968 // for recreating the new AudioTrack as non-offloaded PCM.
2969 //
2970 // If disabling mono, we leave all tracks as is: we don't know which clients
2971 // and tracks are able to be recreated as offloaded. The next "song" should
2972 // play back offloaded.
2973 if (mMasterMono) {
2974 Vector<audio_io_handle_t> offloaded;
2975 for (size_t i = 0; i < mOutputs.size(); ++i) {
2976 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2977 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2978 offloaded.push(desc->mIoHandle);
2979 }
2980 }
2981 for (size_t i = 0; i < offloaded.size(); ++i) {
2982 closeOutput(offloaded[i]);
2983 }
2984 }
2985 // update master mono for all remaining outputs
2986 for (size_t i = 0; i < mOutputs.size(); ++i) {
2987 updateMono(mOutputs.keyAt(i));
2988 }
2989 return NO_ERROR;
2990}
2991
2992status_t AudioPolicyManager::getMasterMono(bool *mono)
2993{
2994 *mono = mMasterMono;
2995 return NO_ERROR;
2996}
2997
Eric Laurentd60560a2015-04-10 11:31:20 -07002998status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2999{
3000 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3001
3002 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3003 if (patchDesc == 0) {
3004 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3005 sourceDesc->mPatchDesc->mHandle);
3006 return BAD_VALUE;
3007 }
3008 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3009
3010 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
3011 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3012 if (swOutputDesc != 0) {
3013 stopSource(swOutputDesc, stream, false);
3014 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3015 } else {
3016 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3017 if (hwOutputDesc != 0) {
3018 // release patch between src device and output device
3019 // close Hwoutput and remove from mHwOutputs
3020 } else {
3021 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3022 }
3023 }
3024 return NO_ERROR;
3025}
3026
3027sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3028 audio_io_handle_t output, routing_strategy strategy)
3029{
3030 sp<AudioSourceDescriptor> source;
3031 for (size_t i = 0; i < mAudioSources.size(); i++) {
3032 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3033 routing_strategy sourceStrategy =
3034 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3035 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3036 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3037 source = sourceDesc;
3038 break;
3039 }
3040 }
3041 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003042}
3043
Eric Laurente552edb2014-03-10 17:42:56 -07003044// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003045// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003046// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003047uint32_t AudioPolicyManager::nextAudioPortGeneration()
3048{
3049 return android_atomic_inc(&mAudioPortGeneration);
3050}
3051
Eric Laurente0720872014-03-11 09:30:41 -07003052AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003053 :
3054#ifdef AUDIO_POLICY_TEST
3055 Thread(false),
3056#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003057 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003058 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003059 mAudioPortGeneration(1),
3060 mBeaconMuteRefCount(0),
3061 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003062 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003063 mTtsOutputAvailable(false),
3064 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003065{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003066 mUidCached = getuid();
3067 mpClientInterface = clientInterface;
3068
3069 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3070 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3071 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3072 bool speakerDrcEnabled = false;
3073
3074#ifdef USE_XML_AUDIO_POLICY_CONF
3075 mVolumeCurves = new VolumeCurvesCollection();
3076 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3077 mDefaultOutputDevice, speakerDrcEnabled,
3078 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3079 PolicySerializer serializer;
3080 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3081#else
3082 mVolumeCurves = new StreamDescriptorCollection();
3083 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3084 mDefaultOutputDevice, speakerDrcEnabled);
3085 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3086 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3087#endif
3088 ALOGE("could not load audio policy configuration file, setting defaults");
3089 config.setDefault();
3090 }
3091 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3092 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3093
3094 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003095 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3096 if (!engineInstance) {
3097 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3098 return;
3099 }
3100 // Retrieve the Policy Manager Interface
3101 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3102 if (mEngine == NULL) {
3103 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3104 return;
3105 }
3106 mEngine->setObserver(this);
3107 status_t status = mEngine->initCheck();
3108 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3109
Eric Laurent3a4311c2014-03-17 12:00:47 -07003110 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003111 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003112 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3113 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003114 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003115 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003116 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003117 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003118 continue;
3119 }
3120 // open all output streams needed to access attached devices
3121 // except for direct output streams that are only opened when they are actually
3122 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003123 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003124 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3125 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003126 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003127
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003128 if (!outProfile->hasSupportedDevices()) {
3129 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003130 continue;
3131 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003132 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003133 mTtsOutputAvailable = true;
3134 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003135
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003136 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003137 continue;
3138 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003139 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003140 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3141 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003142 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003143 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003144 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003145 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003146 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003147 if ((profileType & outputDeviceTypes) == 0) {
3148 continue;
3149 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003150 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3151 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003152
3153 outputDesc->mDevice = profileType;
3154 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3155 config.sample_rate = outputDesc->mSamplingRate;
3156 config.channel_mask = outputDesc->mChannelMask;
3157 config.format = outputDesc->mFormat;
3158 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003159 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003160 &output,
3161 &config,
3162 &outputDesc->mDevice,
3163 String8(""),
3164 &outputDesc->mLatency,
3165 outputDesc->mFlags);
3166
3167 if (status != NO_ERROR) {
3168 ALOGW("Cannot open output stream for device %08x on hw module %s",
3169 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003170 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003171 } else {
3172 outputDesc->mSamplingRate = config.sample_rate;
3173 outputDesc->mChannelMask = config.channel_mask;
3174 outputDesc->mFormat = config.format;
3175
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003176 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3177 for (size_t k = 0; k < supportedDevices.size(); k++) {
3178 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003179 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003180 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3181 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003182 }
3183 }
3184 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003185 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003186 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003187 }
3188 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003189 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003190 outputDesc->mDevice,
3191 true);
3192 }
Eric Laurente552edb2014-03-10 17:42:56 -07003193 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003194 // open input streams needed to access attached devices to validate
3195 // mAvailableInputDevices list
3196 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3197 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003198 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003199
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003200 if (!inProfile->hasSupportedDevices()) {
3201 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003202 continue;
3203 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003204 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003205 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003206 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3207
Eric Laurentd78f1532014-09-16 16:38:20 -07003208 if ((profileType & inputDeviceTypes) == 0) {
3209 continue;
3210 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003211 sp<AudioInputDescriptor> inputDesc =
3212 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003213
Eric Laurentd78f1532014-09-16 16:38:20 -07003214 inputDesc->mDevice = profileType;
3215
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003216 // find the address
3217 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3218 // the inputs vector must be of size 1, but we don't want to crash here
3219 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3220 : String8("");
3221 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3222 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3223
Eric Laurentd78f1532014-09-16 16:38:20 -07003224 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3225 config.sample_rate = inputDesc->mSamplingRate;
3226 config.channel_mask = inputDesc->mChannelMask;
3227 config.format = inputDesc->mFormat;
3228 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003229 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003230 &input,
3231 &config,
3232 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003233 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003234 AUDIO_SOURCE_MIC,
3235 AUDIO_INPUT_FLAG_NONE);
3236
3237 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003238 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3239 for (size_t k = 0; k < supportedDevices.size(); k++) {
3240 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003241 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003242 if (index >= 0) {
3243 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3244 if (!devDesc->isAttached()) {
3245 devDesc->attach(mHwModules[i]);
3246 devDesc->importAudioPort(inProfile);
3247 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003248 }
3249 }
3250 mpClientInterface->closeInput(input);
3251 } else {
3252 ALOGW("Cannot open input stream for device %08x on hw module %s",
3253 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003254 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003255 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003256 }
3257 }
3258 // make sure all attached devices have been allocated a unique ID
3259 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003260 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003261 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003262 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3263 continue;
3264 }
François Gaffie2110e042015-03-24 08:41:51 +01003265 // The device is now validated and can be appended to the available devices of the engine
3266 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3267 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003268 i++;
3269 }
3270 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003271 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003272 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003273 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3274 continue;
3275 }
François Gaffie2110e042015-03-24 08:41:51 +01003276 // The device is now validated and can be appended to the available devices of the engine
3277 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3278 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003279 i++;
3280 }
3281 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003282 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003283 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003284 }
Eric Laurente552edb2014-03-10 17:42:56 -07003285
3286 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3287
3288 updateDevicesAndOutputs();
3289
3290#ifdef AUDIO_POLICY_TEST
3291 if (mPrimaryOutput != 0) {
3292 AudioParameter outputCmd = AudioParameter();
3293 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003294 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003295
3296 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3297 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003298 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3299 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003300 mTestLatencyMs = 0;
3301 mCurOutput = 0;
3302 mDirectOutput = false;
3303 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3304 mTestOutputs[i] = 0;
3305 }
3306
3307 const size_t SIZE = 256;
3308 char buffer[SIZE];
3309 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3310 run(buffer, ANDROID_PRIORITY_AUDIO);
3311 }
3312#endif //AUDIO_POLICY_TEST
3313}
3314
Eric Laurente0720872014-03-11 09:30:41 -07003315AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003316{
3317#ifdef AUDIO_POLICY_TEST
3318 exit();
3319#endif //AUDIO_POLICY_TEST
3320 for (size_t i = 0; i < mOutputs.size(); i++) {
3321 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003322 }
3323 for (size_t i = 0; i < mInputs.size(); i++) {
3324 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003325 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003326 mAvailableOutputDevices.clear();
3327 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003328 mOutputs.clear();
3329 mInputs.clear();
3330 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003331}
3332
Eric Laurente0720872014-03-11 09:30:41 -07003333status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003334{
Eric Laurent87ffa392015-05-22 10:32:38 -07003335 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003336}
3337
3338#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003339bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003340{
3341 ALOGV("entering threadLoop()");
3342 while (!exitPending())
3343 {
3344 String8 command;
3345 int valueInt;
3346 String8 value;
3347
3348 Mutex::Autolock _l(mLock);
3349 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3350
3351 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3352 AudioParameter param = AudioParameter(command);
3353
3354 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3355 valueInt != 0) {
3356 ALOGV("Test command %s received", command.string());
3357 String8 target;
3358 if (param.get(String8("target"), target) != NO_ERROR) {
3359 target = "Manager";
3360 }
3361 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3362 param.remove(String8("test_cmd_policy_output"));
3363 mCurOutput = valueInt;
3364 }
3365 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3366 param.remove(String8("test_cmd_policy_direct"));
3367 if (value == "false") {
3368 mDirectOutput = false;
3369 } else if (value == "true") {
3370 mDirectOutput = true;
3371 }
3372 }
3373 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3374 param.remove(String8("test_cmd_policy_input"));
3375 mTestInput = valueInt;
3376 }
3377
3378 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3379 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003380 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003381 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003382 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003383 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003384 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003385 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003386 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003387 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003388 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003389 if (target == "Manager") {
3390 mTestFormat = format;
3391 } else if (mTestOutputs[mCurOutput] != 0) {
3392 AudioParameter outputParam = AudioParameter();
3393 outputParam.addInt(String8("format"), format);
3394 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3395 }
3396 }
3397 }
3398 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3399 param.remove(String8("test_cmd_policy_channels"));
3400 int channels = 0;
3401
3402 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003403 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003404 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003405 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003406 }
3407 if (channels != 0) {
3408 if (target == "Manager") {
3409 mTestChannels = channels;
3410 } else if (mTestOutputs[mCurOutput] != 0) {
3411 AudioParameter outputParam = AudioParameter();
3412 outputParam.addInt(String8("channels"), channels);
3413 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3414 }
3415 }
3416 }
3417 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3418 param.remove(String8("test_cmd_policy_sampleRate"));
3419 if (valueInt >= 0 && valueInt <= 96000) {
3420 int samplingRate = valueInt;
3421 if (target == "Manager") {
3422 mTestSamplingRate = samplingRate;
3423 } else if (mTestOutputs[mCurOutput] != 0) {
3424 AudioParameter outputParam = AudioParameter();
3425 outputParam.addInt(String8("sampling_rate"), samplingRate);
3426 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3427 }
3428 }
3429 }
3430
3431 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3432 param.remove(String8("test_cmd_policy_reopen"));
3433
Eric Laurentc75307b2015-03-17 15:29:32 -07003434 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003435
Eric Laurentc75307b2015-03-17 15:29:32 -07003436 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003437
Eric Laurentc75307b2015-03-17 15:29:32 -07003438 removeOutput(mPrimaryOutput->mIoHandle);
3439 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3440 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003441 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003442 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3443 config.sample_rate = outputDesc->mSamplingRate;
3444 config.channel_mask = outputDesc->mChannelMask;
3445 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003446 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003447 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003448 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003449 &config,
3450 &outputDesc->mDevice,
3451 String8(""),
3452 &outputDesc->mLatency,
3453 outputDesc->mFlags);
3454 if (status != NO_ERROR) {
3455 ALOGE("Failed to reopen hardware output stream, "
3456 "samplingRate: %d, format %d, channels %d",
3457 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003458 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003459 outputDesc->mSamplingRate = config.sample_rate;
3460 outputDesc->mChannelMask = config.channel_mask;
3461 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003462 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003463 AudioParameter outputCmd = AudioParameter();
3464 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003465 mpClientInterface->setParameters(handle, outputCmd.toString());
3466 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003467 }
3468 }
3469
3470
3471 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3472 }
3473 }
3474 return false;
3475}
3476
Eric Laurente0720872014-03-11 09:30:41 -07003477void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003478{
3479 {
3480 AutoMutex _l(mLock);
3481 requestExit();
3482 mWaitWorkCV.signal();
3483 }
3484 requestExitAndWait();
3485}
3486
Eric Laurente0720872014-03-11 09:30:41 -07003487int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003488{
3489 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3490 if (output == mTestOutputs[i]) return i;
3491 }
3492 return 0;
3493}
3494#endif //AUDIO_POLICY_TEST
3495
3496// ---
3497
Eric Laurentc75307b2015-03-17 15:29:32 -07003498void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003499{
François Gaffie98cc1912015-03-18 17:52:40 +01003500 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003501 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003502 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003503 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003504}
3505
François Gaffie53615e22015-03-19 09:24:12 +01003506void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3507{
3508 mOutputs.removeItem(output);
3509}
3510
Eric Laurent1f2f2232014-06-02 12:01:23 -07003511void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003512{
François Gaffie98cc1912015-03-18 17:52:40 +01003513 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003514 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003515 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003516}
Eric Laurente552edb2014-03-10 17:42:56 -07003517
Eric Laurentc75307b2015-03-17 15:29:32 -07003518void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003519 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003520 const String8 address /*in*/,
3521 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003522 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003523 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003524 if (devDesc != 0) {
3525 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3526 desc->mIoHandle, address.string());
3527 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003528 }
3529}
3530
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003531status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003532 audio_policy_dev_state_t state,
3533 SortedVector<audio_io_handle_t>& outputs,
3534 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003535{
François Gaffie53615e22015-03-19 09:24:12 +01003536 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003537 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003538
3539 if (audio_device_is_digital(device)) {
3540 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003541 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003542 }
Eric Laurente552edb2014-03-10 17:42:56 -07003543
Eric Laurent3b73df72014-03-11 09:06:29 -07003544 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003545 // first list already open outputs that can be routed to this device
3546 for (size_t i = 0; i < mOutputs.size(); i++) {
3547 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003548 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003549 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003550 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3551 outputs.add(mOutputs.keyAt(i));
3552 } else {
3553 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003554 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003555 }
Eric Laurente552edb2014-03-10 17:42:56 -07003556 }
3557 }
3558 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003559 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003560 for (size_t i = 0; i < mHwModules.size(); i++)
3561 {
3562 if (mHwModules[i]->mHandle == 0) {
3563 continue;
3564 }
3565 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3566 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003567 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003568 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003569 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003570 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003571 profiles.add(profile);
3572 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3573 }
Eric Laurente552edb2014-03-10 17:42:56 -07003574 }
3575 }
3576 }
3577
Eric Laurent7b279bb2015-12-14 10:18:23 -08003578 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003579
Eric Laurente552edb2014-03-10 17:42:56 -07003580 if (profiles.isEmpty() && outputs.isEmpty()) {
3581 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3582 return BAD_VALUE;
3583 }
3584
3585 // open outputs for matching profiles if needed. Direct outputs are also opened to
3586 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3587 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003588 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003589
3590 // nothing to do if one output is already opened for this profile
3591 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003592 for (j = 0; j < outputs.size(); j++) {
3593 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003594 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003595 // matching profile: save the sample rates, format and channel masks supported
3596 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003597 if (audio_device_is_digital(device)) {
3598 devDesc->importAudioPort(profile);
3599 }
Eric Laurente552edb2014-03-10 17:42:56 -07003600 break;
3601 }
3602 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003603 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003604 continue;
3605 }
3606
Eric Laurent83b88082014-06-20 18:31:16 -07003607 ALOGV("opening output for device %08x with params %s profile %p",
3608 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003609 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003610 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003611 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3612 config.sample_rate = desc->mSamplingRate;
3613 config.channel_mask = desc->mChannelMask;
3614 config.format = desc->mFormat;
3615 config.offload_info.sample_rate = desc->mSamplingRate;
3616 config.offload_info.channel_mask = desc->mChannelMask;
3617 config.offload_info.format = desc->mFormat;
3618 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003619 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003620 &output,
3621 &config,
3622 &desc->mDevice,
3623 address,
3624 &desc->mLatency,
3625 desc->mFlags);
3626 if (status == NO_ERROR) {
3627 desc->mSamplingRate = config.sample_rate;
3628 desc->mChannelMask = config.channel_mask;
3629 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003630
Eric Laurentd4692962014-05-05 18:13:44 -07003631 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003632 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003633 char *param = audio_device_address_to_parameter(device, address);
3634 mpClientInterface->setParameters(output, String8(param));
3635 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003636 }
François Gaffie112b0af2015-11-19 16:13:25 +01003637 updateAudioProfiles(output, profile->getAudioProfiles());
3638 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003639 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003640 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003641 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003642 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003643 mpClientInterface->closeOutput(output);
François Gaffie112b0af2015-11-19 16:13:25 +01003644 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003645 config.offload_info.sample_rate = config.sample_rate;
3646 config.offload_info.channel_mask = config.channel_mask;
3647 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003648 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003649 &output,
3650 &config,
3651 &desc->mDevice,
3652 address,
3653 &desc->mLatency,
3654 desc->mFlags);
3655 if (status == NO_ERROR) {
3656 desc->mSamplingRate = config.sample_rate;
3657 desc->mChannelMask = config.channel_mask;
3658 desc->mFormat = config.format;
3659 } else {
3660 output = AUDIO_IO_HANDLE_NONE;
3661 }
Eric Laurentd4692962014-05-05 18:13:44 -07003662 }
3663
Eric Laurentcf2c0212014-07-25 16:20:43 -07003664 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003665 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003666 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003667 sp<AudioPolicyMix> policyMix;
3668 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003669 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3670 address.string());
3671 }
François Gaffie036e1e92015-03-19 10:16:24 +01003672 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003673 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003674
Eric Laurent87ffa392015-05-22 10:32:38 -07003675 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3676 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003677 // no duplicated output for direct outputs and
3678 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003679 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003680
Eric Laurentd4692962014-05-05 18:13:44 -07003681 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003682 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003683
Eric Laurentd4692962014-05-05 18:13:44 -07003684 //TODO: configure audio effect output stage here
3685
3686 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003687 duplicatedOutput =
3688 mpClientInterface->openDuplicateOutput(output,
3689 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003690 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003691 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003692 sp<SwAudioOutputDescriptor> dupOutputDesc =
3693 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3694 dupOutputDesc->mOutput1 = mPrimaryOutput;
3695 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003696 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3697 dupOutputDesc->mFormat = desc->mFormat;
3698 dupOutputDesc->mChannelMask = desc->mChannelMask;
3699 dupOutputDesc->mLatency = desc->mLatency;
3700 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003701 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003702 } else {
3703 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003704 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003705 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003706 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003707 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003708 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003709 }
Eric Laurente552edb2014-03-10 17:42:56 -07003710 }
3711 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003712 } else {
3713 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003714 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003715 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003716 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003717 profiles.removeAt(profile_index);
3718 profile_index--;
3719 } else {
3720 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003721 // Load digital format info only for digital devices
3722 if (audio_device_is_digital(device)) {
3723 devDesc->importAudioPort(profile);
3724 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003725
François Gaffie53615e22015-03-19 09:24:12 +01003726 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003727 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3728 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003729 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003730 NULL/*patch handle*/, address.string());
3731 }
Eric Laurente552edb2014-03-10 17:42:56 -07003732 ALOGV("checkOutputsForDevice(): adding output %d", output);
3733 }
3734 }
3735
3736 if (profiles.isEmpty()) {
3737 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3738 return BAD_VALUE;
3739 }
Eric Laurentd4692962014-05-05 18:13:44 -07003740 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003741 // check if one opened output is not needed any more after disconnecting one device
3742 for (size_t i = 0; i < mOutputs.size(); i++) {
3743 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003744 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003745 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003746 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003747 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003748 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003749 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003750 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3751 mOutputs.keyAt(i));
3752 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003753 }
Eric Laurente552edb2014-03-10 17:42:56 -07003754 }
3755 }
Eric Laurentd4692962014-05-05 18:13:44 -07003756 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003757 for (size_t i = 0; i < mHwModules.size(); i++)
3758 {
3759 if (mHwModules[i]->mHandle == 0) {
3760 continue;
3761 }
3762 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3763 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003765 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003766 ALOGV("checkOutputsForDevice(): "
3767 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003768 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003769 }
3770 }
3771 }
3772 }
3773 return NO_ERROR;
3774}
3775
Paul McLean9080a4c2015-06-18 08:24:02 -07003776status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003777 audio_policy_dev_state_t state,
3778 SortedVector<audio_io_handle_t>& inputs,
3779 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003780{
Paul McLean9080a4c2015-06-18 08:24:02 -07003781 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003782 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003783
3784 if (audio_device_is_digital(device)) {
3785 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003786 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003787 }
3788
Eric Laurentd4692962014-05-05 18:13:44 -07003789 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3790 // first list already open inputs that can be routed to this device
3791 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3792 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003793 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003794 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3795 inputs.add(mInputs.keyAt(input_index));
3796 }
3797 }
3798
3799 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003800 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003801 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3802 {
3803 if (mHwModules[module_idx]->mHandle == 0) {
3804 continue;
3805 }
3806 for (size_t profile_index = 0;
3807 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3808 profile_index++)
3809 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003810 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3811
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003812 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003813 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003814 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003815 profiles.add(profile);
3816 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3817 profile_index, module_idx);
3818 }
Eric Laurentd4692962014-05-05 18:13:44 -07003819 }
3820 }
3821 }
3822
3823 if (profiles.isEmpty() && inputs.isEmpty()) {
3824 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3825 return BAD_VALUE;
3826 }
3827
3828 // open inputs for matching profiles if needed. Direct inputs are also opened to
3829 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3830 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3831
Eric Laurent1c333e22014-05-20 10:48:17 -07003832 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003833 // nothing to do if one input is already opened for this profile
3834 size_t input_index;
3835 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3836 desc = mInputs.valueAt(input_index);
3837 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003838 if (audio_device_is_digital(device)) {
3839 devDesc->importAudioPort(profile);
3840 }
Eric Laurentd4692962014-05-05 18:13:44 -07003841 break;
3842 }
3843 }
3844 if (input_index != mInputs.size()) {
3845 continue;
3846 }
3847
3848 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3849 desc = new AudioInputDescriptor(profile);
3850 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003851 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3852 config.sample_rate = desc->mSamplingRate;
3853 config.channel_mask = desc->mChannelMask;
3854 config.format = desc->mFormat;
3855 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003856 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003857 &input,
3858 &config,
3859 &desc->mDevice,
3860 address,
3861 AUDIO_SOURCE_MIC,
3862 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003863
Eric Laurentcf2c0212014-07-25 16:20:43 -07003864 if (status == NO_ERROR) {
3865 desc->mSamplingRate = config.sample_rate;
3866 desc->mChannelMask = config.channel_mask;
3867 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003868
Eric Laurentd4692962014-05-05 18:13:44 -07003869 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003870 char *param = audio_device_address_to_parameter(device, address);
3871 mpClientInterface->setParameters(input, String8(param));
3872 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003873 }
François Gaffie112b0af2015-11-19 16:13:25 +01003874 updateAudioProfiles(input, profile->getAudioProfiles());
3875 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003876 ALOGW("checkInputsForDevice() direct input missing param");
3877 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003878 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003879 }
3880
3881 if (input != 0) {
3882 addInput(input, desc);
3883 }
3884 } // endif input != 0
3885
Eric Laurentcf2c0212014-07-25 16:20:43 -07003886 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003887 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003888 profiles.removeAt(profile_index);
3889 profile_index--;
3890 } else {
3891 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003892 if (audio_device_is_digital(device)) {
3893 devDesc->importAudioPort(profile);
3894 }
Eric Laurentd4692962014-05-05 18:13:44 -07003895 ALOGV("checkInputsForDevice(): adding input %d", input);
3896 }
3897 } // end scan profiles
3898
3899 if (profiles.isEmpty()) {
3900 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3901 return BAD_VALUE;
3902 }
3903 } else {
3904 // Disconnect
3905 // check if one opened input is not needed any more after disconnecting one device
3906 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3907 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003908 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003909 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3910 mInputs.keyAt(input_index));
3911 inputs.add(mInputs.keyAt(input_index));
3912 }
3913 }
3914 // Clear any profiles associated with the disconnected device.
3915 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3916 if (mHwModules[module_index]->mHandle == 0) {
3917 continue;
3918 }
3919 for (size_t profile_index = 0;
3920 profile_index < mHwModules[module_index]->mInputProfiles.size();
3921 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003922 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003923 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003924 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003925 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01003926 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07003927 }
3928 }
3929 }
3930 } // end disconnect
3931
3932 return NO_ERROR;
3933}
3934
3935
Eric Laurente0720872014-03-11 09:30:41 -07003936void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003937{
3938 ALOGV("closeOutput(%d)", output);
3939
Eric Laurentc75307b2015-03-17 15:29:32 -07003940 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003941 if (outputDesc == NULL) {
3942 ALOGW("closeOutput() unknown output %d", output);
3943 return;
3944 }
François Gaffie036e1e92015-03-19 10:16:24 +01003945 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003946
Eric Laurente552edb2014-03-10 17:42:56 -07003947 // look for duplicated outputs connected to the output being removed.
3948 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003949 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003950 if (dupOutputDesc->isDuplicated() &&
3951 (dupOutputDesc->mOutput1 == outputDesc ||
3952 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003953 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003954 if (dupOutputDesc->mOutput1 == outputDesc) {
3955 outputDesc2 = dupOutputDesc->mOutput2;
3956 } else {
3957 outputDesc2 = dupOutputDesc->mOutput1;
3958 }
3959 // As all active tracks on duplicated output will be deleted,
3960 // and as they were also referenced on the other output, the reference
3961 // count for their stream type must be adjusted accordingly on
3962 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003963 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003964 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003965 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003966 }
3967 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3968 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3969
3970 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01003971 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003972 }
3973 }
3974
Eric Laurent05b90f82014-08-27 15:32:29 -07003975 nextAudioPortGeneration();
3976
Jean-Michel Triviff155c62016-02-26 12:07:16 -08003977 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07003978 if (index >= 0) {
3979 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3980 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3981 mAudioPatches.removeItemsAt(index);
3982 mpClientInterface->onAudioPatchListUpdate();
3983 }
3984
Eric Laurente552edb2014-03-10 17:42:56 -07003985 AudioParameter param;
3986 param.add(String8("closing"), String8("true"));
3987 mpClientInterface->setParameters(output, param.toString());
3988
3989 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003990 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003991 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003992}
3993
3994void AudioPolicyManager::closeInput(audio_io_handle_t input)
3995{
3996 ALOGV("closeInput(%d)", input);
3997
3998 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3999 if (inputDesc == NULL) {
4000 ALOGW("closeInput() unknown input %d", input);
4001 return;
4002 }
4003
Eric Laurent6a94d692014-05-20 11:18:06 -07004004 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004005
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004006 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004007 if (index >= 0) {
4008 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4009 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4010 mAudioPatches.removeItemsAt(index);
4011 mpClientInterface->onAudioPatchListUpdate();
4012 }
4013
4014 mpClientInterface->closeInput(input);
4015 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004016}
4017
Eric Laurentc75307b2015-03-17 15:29:32 -07004018SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4019 audio_devices_t device,
4020 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004021{
4022 SortedVector<audio_io_handle_t> outputs;
4023
4024 ALOGVV("getOutputsForDevice() device %04x", device);
4025 for (size_t i = 0; i < openOutputs.size(); i++) {
4026 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004027 i, openOutputs.valueAt(i)->isDuplicated(),
4028 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004029 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4030 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4031 outputs.add(openOutputs.keyAt(i));
4032 }
4033 }
4034 return outputs;
4035}
4036
Eric Laurente0720872014-03-11 09:30:41 -07004037bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004038 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004039{
4040 if (outputs1.size() != outputs2.size()) {
4041 return false;
4042 }
4043 for (size_t i = 0; i < outputs1.size(); i++) {
4044 if (outputs1[i] != outputs2[i]) {
4045 return false;
4046 }
4047 }
4048 return true;
4049}
4050
Eric Laurente0720872014-03-11 09:30:41 -07004051void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004052{
4053 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4054 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4055 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4056 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4057
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004058 // also take into account external policy-related changes: add all outputs which are
4059 // associated with policies in the "before" and "after" output vectors
4060 ALOGVV("checkOutputForStrategy(): policy related outputs");
4061 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004062 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004063 if (desc != 0 && desc->mPolicyMix != NULL) {
4064 srcOutputs.add(desc->mIoHandle);
4065 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4066 }
4067 }
4068 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004069 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004070 if (desc != 0 && desc->mPolicyMix != NULL) {
4071 dstOutputs.add(desc->mIoHandle);
4072 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4073 }
4074 }
4075
Eric Laurente552edb2014-03-10 17:42:56 -07004076 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4077 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4078 strategy, srcOutputs[0], dstOutputs[0]);
4079 // mute strategy while moving tracks from one output to another
4080 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004081 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004082 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004083 setStrategyMute(strategy, true, desc);
4084 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004085 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004086 sp<AudioSourceDescriptor> source =
4087 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4088 if (source != 0){
4089 connectAudioSource(source);
4090 }
Eric Laurente552edb2014-03-10 17:42:56 -07004091 }
4092
4093 // Move effects associated to this strategy from previous output to new output
4094 if (strategy == STRATEGY_MEDIA) {
4095 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4096 SortedVector<audio_io_handle_t> moved;
4097 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004098 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4099 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4100 effectDesc->mIo != fxOutput) {
4101 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004102 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4103 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004104 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004105 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004106 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004107 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004108 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004109 }
4110 }
4111 }
4112 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004113 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004114 if (i == AUDIO_STREAM_PATCH) {
4115 continue;
4116 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004117 if (getStrategy((audio_stream_type_t)i) == strategy) {
4118 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004119 }
4120 }
4121 }
4122}
4123
Eric Laurente0720872014-03-11 09:30:41 -07004124void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004125{
François Gaffie2110e042015-03-24 08:41:51 +01004126 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004127 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004128 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004129 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004130 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004131 checkOutputForStrategy(STRATEGY_SONIFICATION);
4132 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004133 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004134 checkOutputForStrategy(STRATEGY_MEDIA);
4135 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004136 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004137}
4138
Eric Laurente0720872014-03-11 09:30:41 -07004139void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004140{
François Gaffie53615e22015-03-19 09:24:12 +01004141 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004142 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004143 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004144 return;
4145 }
4146
Eric Laurent3a4311c2014-03-17 12:00:47 -07004147 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004148 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4149 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4150 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004151 // suspend A2DP output if:
4152 // (NOT already suspended) &&
4153 // ((SCO device is connected &&
4154 // (forced usage for communication || for record is SCO))) ||
4155 // (phone state is ringing || in call)
4156 //
4157 // restore A2DP output if:
4158 // (Already suspended) &&
4159 // ((SCO device is NOT connected ||
4160 // (forced usage NOT for communication && NOT for record is SCO))) &&
4161 // (phone state is NOT ringing && NOT in call)
4162 //
4163 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004164 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004165 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4166 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4167 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4168 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004169
4170 mpClientInterface->restoreOutput(a2dpOutput);
4171 mA2dpSuspended = false;
4172 }
4173 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004174 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004175 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4176 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4177 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4178 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004179
4180 mpClientInterface->suspendOutput(a2dpOutput);
4181 mA2dpSuspended = true;
4182 }
4183 }
4184}
4185
Eric Laurentc75307b2015-03-17 15:29:32 -07004186audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4187 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004188{
4189 audio_devices_t device = AUDIO_DEVICE_NONE;
4190
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004191 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004192 if (index >= 0) {
4193 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4194 if (patchDesc->mUid != mUidCached) {
4195 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004196 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004197 return outputDesc->device();
4198 }
4199 }
4200
Eric Laurente552edb2014-03-10 17:42:56 -07004201 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004202 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004203 // use device for strategy enforced audible
4204 // 2: we are in call or the strategy phone is active on the output:
4205 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004206 // 3: the strategy for enforced audible is active but not enforced on the output:
4207 // use the device for strategy enforced audible
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004208 // 4: the strategy accessibility is active on the output:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004209 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004210 // 5: the strategy sonification is active on the output:
4211 // use device for strategy sonification
4212 // 6: the strategy "respectful" sonification is active on the output:
4213 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004214 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004215 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004216 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004217 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004218 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004219 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004220 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004221 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004222 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4223 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004224 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004225 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004226 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004227 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004228 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4229 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004230 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004231 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004232 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004233 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004234 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004235 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004236 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004237 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004238 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004239 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004240 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004241 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004242 }
4243
Eric Laurent1c333e22014-05-20 10:48:17 -07004244 ALOGV("getNewOutputDevice() selected device %x", device);
4245 return device;
4246}
4247
Eric Laurent232f26f2016-02-17 18:06:27 -08004248audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
Eric Laurent1c333e22014-05-20 10:48:17 -07004249{
Eric Laurent232f26f2016-02-17 18:06:27 -08004250 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004251
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004252 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004253 if (index >= 0) {
4254 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4255 if (patchDesc->mUid != mUidCached) {
4256 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004257 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004258 return inputDesc->mDevice;
4259 }
4260 }
4261
Eric Laurent232f26f2016-02-17 18:06:27 -08004262 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004263
Eric Laurente552edb2014-03-10 17:42:56 -07004264 return device;
4265}
4266
Eric Laurente0720872014-03-11 09:30:41 -07004267uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004268 return (uint32_t)getStrategy(stream);
4269}
4270
Eric Laurente0720872014-03-11 09:30:41 -07004271audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004272 // By checking the range of stream before calling getStrategy, we avoid
4273 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4274 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004275 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004276 return AUDIO_DEVICE_NONE;
4277 }
4278 audio_devices_t devices;
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004279 routing_strategy strategy = getStrategy(stream);
Eric Laurent6a94d692014-05-20 11:18:06 -07004280 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4281 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4282 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004283 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004284 if (isStrategyActive(outputDesc, strategy)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004285 devices = outputDesc->device();
4286 break;
4287 }
Eric Laurente552edb2014-03-10 17:42:56 -07004288 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004289
4290 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4291 and doesn't really need to.*/
4292 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4293 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4294 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4295 }
Eric Laurente552edb2014-03-10 17:42:56 -07004296 return devices;
4297}
4298
François Gaffie2110e042015-03-24 08:41:51 +01004299routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4300{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004301 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004302 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004303}
4304
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004305uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4306 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004307 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4308 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4309 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004310 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4311 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4312 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004313 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004314 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004315}
4316
Eric Laurente0720872014-03-11 09:30:41 -07004317void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004318 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004319 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004320 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4321 updateDevicesAndOutputs();
4322 break;
4323 default:
4324 break;
4325 }
4326}
4327
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004328uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004329
4330 // skip beacon mute management if a dedicated TTS output is available
4331 if (mTtsOutputAvailable) {
4332 return 0;
4333 }
4334
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004335 switch(event) {
4336 case STARTING_OUTPUT:
4337 mBeaconMuteRefCount++;
4338 break;
4339 case STOPPING_OUTPUT:
4340 if (mBeaconMuteRefCount > 0) {
4341 mBeaconMuteRefCount--;
4342 }
4343 break;
4344 case STARTING_BEACON:
4345 mBeaconPlayingRefCount++;
4346 break;
4347 case STOPPING_BEACON:
4348 if (mBeaconPlayingRefCount > 0) {
4349 mBeaconPlayingRefCount--;
4350 }
4351 break;
4352 }
4353
4354 if (mBeaconMuteRefCount > 0) {
4355 // any playback causes beacon to be muted
4356 return setBeaconMute(true);
4357 } else {
4358 // no other playback: unmute when beacon starts playing, mute when it stops
4359 return setBeaconMute(mBeaconPlayingRefCount == 0);
4360 }
4361}
4362
4363uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4364 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4365 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4366 // keep track of muted state to avoid repeating mute/unmute operations
4367 if (mBeaconMuted != mute) {
4368 // mute/unmute AUDIO_STREAM_TTS on all outputs
4369 ALOGV("\t muting %d", mute);
4370 uint32_t maxLatency = 0;
4371 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004372 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004373 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004374 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004375 0 /*delay*/, AUDIO_DEVICE_NONE);
4376 const uint32_t latency = desc->latency() * 2;
4377 if (latency > maxLatency) {
4378 maxLatency = latency;
4379 }
4380 }
4381 mBeaconMuted = mute;
4382 return maxLatency;
4383 }
4384 return 0;
4385}
4386
Eric Laurente0720872014-03-11 09:30:41 -07004387audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004388 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004389{
Paul McLeanaa981192015-03-21 09:55:15 -07004390 // Routing
4391 // see if we have an explicit route
4392 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4393 // (getStrategy(stream)).
4394 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4395 // and activity count is non-zero
4396 // the device = the device from the descriptor in the RouteMap, and exit.
4397 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4398 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
4399 routing_strategy strat = getStrategy(route->mStreamType);
Eric Laurent093a20c2015-06-11 12:33:29 -07004400 // Special case for accessibility strategy which must follow any strategy it is
4401 // currently remapped to
4402 bool strategyMatch = (strat == strategy) ||
4403 ((strategy == STRATEGY_ACCESSIBILITY) &&
4404 ((mEngine->getStrategyForUsage(
4405 AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) == strat) ||
4406 (strat == STRATEGY_MEDIA)));
4407 if (strategyMatch && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004408 return route->mDeviceDescriptor->type();
4409 }
4410 }
4411
Eric Laurente552edb2014-03-10 17:42:56 -07004412 if (fromCache) {
4413 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4414 strategy, mDeviceForStrategy[strategy]);
4415 return mDeviceForStrategy[strategy];
4416 }
François Gaffie2110e042015-03-24 08:41:51 +01004417 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004418}
4419
Eric Laurente0720872014-03-11 09:30:41 -07004420void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004421{
4422 for (int i = 0; i < NUM_STRATEGIES; i++) {
4423 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4424 }
4425 mPreviousOutputs = mOutputs;
4426}
4427
Eric Laurent1f2f2232014-06-02 12:01:23 -07004428uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004429 audio_devices_t prevDevice,
4430 uint32_t delayMs)
4431{
4432 // mute/unmute strategies using an incompatible device combination
4433 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4434 // if unmuting, unmute only after the specified delay
4435 if (outputDesc->isDuplicated()) {
4436 return 0;
4437 }
4438
4439 uint32_t muteWaitMs = 0;
4440 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004441 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004442
4443 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4444 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004445 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004446 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4447 bool doMute = false;
4448
4449 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4450 doMute = true;
4451 outputDesc->mStrategyMutedByDevice[i] = true;
4452 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4453 doMute = true;
4454 outputDesc->mStrategyMutedByDevice[i] = false;
4455 }
Eric Laurent99401132014-05-07 19:48:15 -07004456 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004457 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004458 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004459 // skip output if it does not share any device with current output
4460 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4461 == AUDIO_DEVICE_NONE) {
4462 continue;
4463 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004464 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4465 mute ? "muting" : "unmuting", i, curDevice);
4466 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004467 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004468 if (mute) {
4469 // FIXME: should not need to double latency if volume could be applied
4470 // immediately by the audioflinger mixer. We must account for the delay
4471 // between now and the next time the audioflinger thread for this output
4472 // will process a buffer (which corresponds to one buffer size,
4473 // usually 1/2 or 1/4 of the latency).
4474 if (muteWaitMs < desc->latency() * 2) {
4475 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004476 }
4477 }
4478 }
4479 }
4480 }
4481 }
4482
Eric Laurent99401132014-05-07 19:48:15 -07004483 // temporary mute output if device selection changes to avoid volume bursts due to
4484 // different per device volumes
4485 if (outputDesc->isActive() && (device != prevDevice)) {
4486 if (muteWaitMs < outputDesc->latency() * 2) {
4487 muteWaitMs = outputDesc->latency() * 2;
4488 }
4489 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004490 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004491 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004492 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004493 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004494 muteWaitMs *2, device);
4495 }
4496 }
4497 }
4498
Eric Laurente552edb2014-03-10 17:42:56 -07004499 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4500 if (muteWaitMs > delayMs) {
4501 muteWaitMs -= delayMs;
4502 usleep(muteWaitMs * 1000);
4503 return muteWaitMs;
4504 }
4505 return 0;
4506}
4507
Eric Laurentc75307b2015-03-17 15:29:32 -07004508uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004509 audio_devices_t device,
4510 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004511 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004512 audio_patch_handle_t *patchHandle,
4513 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004514{
Eric Laurentc75307b2015-03-17 15:29:32 -07004515 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004516 AudioParameter param;
4517 uint32_t muteWaitMs;
4518
4519 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004520 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4521 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004522 return muteWaitMs;
4523 }
4524 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4525 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004526 if ((device != AUDIO_DEVICE_NONE) &&
4527 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004528 return 0;
4529 }
4530
4531 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004532 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004533
4534 audio_devices_t prevDevice = outputDesc->mDevice;
4535
Paul McLeanaa981192015-03-21 09:55:15 -07004536 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004537
4538 if (device != AUDIO_DEVICE_NONE) {
4539 outputDesc->mDevice = device;
4540 }
4541 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4542
4543 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004544 // the requested device is AUDIO_DEVICE_NONE
4545 // OR the requested device is the same as current device
4546 // AND force is not specified
4547 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004548 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004549 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4550 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004551 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004552 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004553 return muteWaitMs;
4554 }
4555
4556 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004557
Eric Laurente552edb2014-03-10 17:42:56 -07004558 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004559 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004560 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004561 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004562 DeviceVector deviceList = (address == NULL) ?
4563 mAvailableOutputDevices.getDevicesFromType(device)
4564 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004565 if (!deviceList.isEmpty()) {
4566 struct audio_patch patch;
4567 outputDesc->toAudioPortConfig(&patch.sources[0]);
4568 patch.num_sources = 1;
4569 patch.num_sinks = 0;
4570 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4571 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004572 patch.num_sinks++;
4573 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004574 ssize_t index;
4575 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4576 index = mAudioPatches.indexOfKey(*patchHandle);
4577 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004578 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004579 }
4580 sp< AudioPatch> patchDesc;
4581 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4582 if (index >= 0) {
4583 patchDesc = mAudioPatches.valueAt(index);
4584 afPatchHandle = patchDesc->mAfPatchHandle;
4585 }
4586
Eric Laurent1c333e22014-05-20 10:48:17 -07004587 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004588 &afPatchHandle,
4589 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004590 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4591 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004592 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004593 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004594 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004595 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 addAudioPatch(patchDesc->mHandle, patchDesc);
4597 } else {
4598 patchDesc->mPatch = patch;
4599 }
4600 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004601 if (patchHandle) {
4602 *patchHandle = patchDesc->mHandle;
4603 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004604 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004605 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004606 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004607 }
4608 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004609
4610 // inform all input as well
4611 for (size_t i = 0; i < mInputs.size(); i++) {
4612 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004613 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004614 AudioParameter inputCmd = AudioParameter();
4615 ALOGV("%s: inform input %d of device:%d", __func__,
4616 inputDescriptor->mIoHandle, device);
4617 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4618 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4619 inputCmd.toString(),
4620 delayMs);
4621 }
4622 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004623 }
Eric Laurente552edb2014-03-10 17:42:56 -07004624
4625 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004626 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004627
4628 return muteWaitMs;
4629}
4630
Eric Laurentc75307b2015-03-17 15:29:32 -07004631status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004632 int delayMs,
4633 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004634{
Eric Laurent6a94d692014-05-20 11:18:06 -07004635 ssize_t index;
4636 if (patchHandle) {
4637 index = mAudioPatches.indexOfKey(*patchHandle);
4638 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004639 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004640 }
4641 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004642 return INVALID_OPERATION;
4643 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004644 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4645 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004646 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004647 outputDesc->setPatchHandle(0);
Eric Laurent6a94d692014-05-20 11:18:06 -07004648 removeAudioPatch(patchDesc->mHandle);
4649 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004650 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004651 return status;
4652}
4653
4654status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4655 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004656 bool force,
4657 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004658{
4659 status_t status = NO_ERROR;
4660
Eric Laurent1f2f2232014-06-02 12:01:23 -07004661 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004662 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4663 inputDesc->mDevice = device;
4664
4665 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4666 if (!deviceList.isEmpty()) {
4667 struct audio_patch patch;
4668 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004669 // AUDIO_SOURCE_HOTWORD is for internal use only:
4670 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004671 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004672 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004673 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4674 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004675 patch.num_sinks = 1;
4676 //only one input device for now
4677 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004678 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004679 ssize_t index;
4680 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4681 index = mAudioPatches.indexOfKey(*patchHandle);
4682 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004683 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 }
4685 sp< AudioPatch> patchDesc;
4686 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4687 if (index >= 0) {
4688 patchDesc = mAudioPatches.valueAt(index);
4689 afPatchHandle = patchDesc->mAfPatchHandle;
4690 }
4691
Eric Laurent1c333e22014-05-20 10:48:17 -07004692 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004694 0);
4695 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004697 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004698 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004699 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 addAudioPatch(patchDesc->mHandle, patchDesc);
4701 } else {
4702 patchDesc->mPatch = patch;
4703 }
4704 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004705 if (patchHandle) {
4706 *patchHandle = patchDesc->mHandle;
4707 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004708 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004710 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004711 }
4712 }
4713 }
4714 return status;
4715}
4716
Eric Laurent6a94d692014-05-20 11:18:06 -07004717status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4718 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004719{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004720 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004721 ssize_t index;
4722 if (patchHandle) {
4723 index = mAudioPatches.indexOfKey(*patchHandle);
4724 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004725 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 }
4727 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004728 return INVALID_OPERATION;
4729 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4731 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004732 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004733 inputDesc->setPatchHandle(0);
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 removeAudioPatch(patchDesc->mHandle);
4735 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004736 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004737 return status;
4738}
4739
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004740sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004741 String8 address,
4742 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004743 audio_format_t& format,
4744 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004745 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004746{
4747 // Choose an input profile based on the requested capture parameters: select the first available
4748 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004749 //
4750 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4751 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004752
4753 for (size_t i = 0; i < mHwModules.size(); i++)
4754 {
4755 if (mHwModules[i]->mHandle == 0) {
4756 continue;
4757 }
4758 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4759 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004760 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004761 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004762 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004763 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004764 format,
4765 &format /*updatedFormat*/,
4766 channelMask,
4767 &channelMask /*updatedChannelMask*/,
4768 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004769
Eric Laurente552edb2014-03-10 17:42:56 -07004770 return profile;
4771 }
4772 }
4773 }
4774 return NULL;
4775}
4776
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004777
4778audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004779 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004780{
François Gaffie036e1e92015-03-19 10:16:24 +01004781 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4782 audio_devices_t selectedDeviceFromMix =
4783 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004784
François Gaffie036e1e92015-03-19 10:16:24 +01004785 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4786 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004787 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004788 return getDeviceForInputSource(inputSource);
4789}
4790
4791audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4792{
Paul McLean466dc8e2015-04-17 13:15:36 -06004793 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4794 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004795 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004796 return route->mDeviceDescriptor->type();
4797 }
4798 }
4799
4800 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004801}
4802
Eric Laurente0720872014-03-11 09:30:41 -07004803float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004804 int index,
4805 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004806{
François Gaffied1ab2bd2015-12-02 18:20:06 +01004807 float volumeDb = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Eric Laurente552edb2014-03-10 17:42:56 -07004808 // if a headset is connected, apply the following rules to ring tones and notifications
4809 // to avoid sound level bursts in user's ears:
4810 // - always attenuate ring tones and notifications volume by 6dB
4811 // - if music is playing, always limit the volume to current music volume,
4812 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004813 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004814 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4815 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4816 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4817 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4818 ((stream_strategy == STRATEGY_SONIFICATION)
4819 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004820 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004821 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004822 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01004823 mVolumeCurves->canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004824 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004825 // when the phone is ringing we must consider that music could have been paused just before
4826 // by the music application and behave as if music was active if the last music track was
4827 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004828 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004829 mLimitRingtoneVolume) {
4830 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004831 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004832 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
4833 musicDevice),
4834 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004835 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4836 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4837 if (volumeDb > minVolDB) {
4838 volumeDb = minVolDB;
4839 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004840 }
4841 }
4842 }
4843
Eric Laurentffbc80f2015-03-18 18:30:19 -07004844 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004845}
4846
Eric Laurente0720872014-03-11 09:30:41 -07004847status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004848 int index,
4849 const sp<AudioOutputDescriptor>& outputDesc,
4850 audio_devices_t device,
4851 int delayMs,
4852 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004853{
Eric Laurente552edb2014-03-10 17:42:56 -07004854 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004855 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004856 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004857 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004858 return NO_ERROR;
4859 }
François Gaffie2110e042015-03-24 08:41:51 +01004860 audio_policy_forced_cfg_t forceUseForComm =
4861 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004862 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004863 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4864 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004865 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004866 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004867 return INVALID_OPERATION;
4868 }
4869
Eric Laurentc75307b2015-03-17 15:29:32 -07004870 if (device == AUDIO_DEVICE_NONE) {
4871 device = outputDesc->device();
4872 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004873
Eric Laurentffbc80f2015-03-18 18:30:19 -07004874 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004875 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004876 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004877 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004878
Eric Laurentffbc80f2015-03-18 18:30:19 -07004879 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004880
Eric Laurent3b73df72014-03-11 09:06:29 -07004881 if (stream == AUDIO_STREAM_VOICE_CALL ||
4882 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004883 float voiceVolume;
4884 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004885 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004886 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004887 } else {
4888 voiceVolume = 1.0;
4889 }
4890
Eric Laurentc75307b2015-03-17 15:29:32 -07004891 if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
Eric Laurente552edb2014-03-10 17:42:56 -07004892 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4893 mLastVoiceVolume = voiceVolume;
4894 }
4895 }
4896
4897 return NO_ERROR;
4898}
4899
Eric Laurentc75307b2015-03-17 15:29:32 -07004900void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4901 audio_devices_t device,
4902 int delayMs,
4903 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004904{
Eric Laurentc75307b2015-03-17 15:29:32 -07004905 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004906
Eric Laurent3b73df72014-03-11 09:06:29 -07004907 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004908 if (stream == AUDIO_STREAM_PATCH) {
4909 continue;
4910 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004911 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004912 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004913 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004914 device,
4915 delayMs,
4916 force);
4917 }
4918}
4919
Eric Laurente0720872014-03-11 09:30:41 -07004920void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07004921 bool on,
4922 const sp<AudioOutputDescriptor>& outputDesc,
4923 int delayMs,
4924 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004925{
Eric Laurent72249d52015-06-08 11:12:15 -07004926 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
4927 strategy, on, outputDesc->getId());
Eric Laurent3b73df72014-03-11 09:06:29 -07004928 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004929 if (stream == AUDIO_STREAM_PATCH) {
4930 continue;
4931 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004932 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004933 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004934 }
4935 }
4936}
4937
Eric Laurente0720872014-03-11 09:30:41 -07004938void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004939 bool on,
4940 const sp<AudioOutputDescriptor>& outputDesc,
4941 int delayMs,
4942 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004943{
Eric Laurente552edb2014-03-10 17:42:56 -07004944 if (device == AUDIO_DEVICE_NONE) {
4945 device = outputDesc->device();
4946 }
4947
Eric Laurentc75307b2015-03-17 15:29:32 -07004948 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
4949 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07004950
4951 if (on) {
4952 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004953 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004954 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01004955 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004956 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004957 }
4958 }
4959 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4960 outputDesc->mMuteCount[stream]++;
4961 } else {
4962 if (outputDesc->mMuteCount[stream] == 0) {
4963 ALOGV("setStreamMute() unmuting non muted stream!");
4964 return;
4965 }
4966 if (--outputDesc->mMuteCount[stream] == 0) {
4967 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004968 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004969 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004970 device,
4971 delayMs);
4972 }
4973 }
4974}
4975
Eric Laurente0720872014-03-11 09:30:41 -07004976void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004977 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004978{
Eric Laurent87ffa392015-05-22 10:32:38 -07004979 if(!hasPrimaryOutput()) {
4980 return;
4981 }
4982
Eric Laurente552edb2014-03-10 17:42:56 -07004983 // if the stream pertains to sonification strategy and we are in call we must
4984 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4985 // in the device used for phone strategy and play the tone if the selected device does not
4986 // interfere with the device used for phone strategy
4987 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4988 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004989 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004990 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4991 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004992 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004993 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4994 stream, starting, outputDesc->mDevice, stateChange);
4995 if (outputDesc->mRefCount[stream]) {
4996 int muteCount = 1;
4997 if (stateChange) {
4998 muteCount = outputDesc->mRefCount[stream];
4999 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005000 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005001 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5002 for (int i = 0; i < muteCount; i++) {
5003 setStreamMute(stream, starting, mPrimaryOutput);
5004 }
5005 } else {
5006 ALOGV("handleIncallSonification() high visibility");
5007 if (outputDesc->device() &
5008 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5009 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5010 for (int i = 0; i < muteCount; i++) {
5011 setStreamMute(stream, starting, mPrimaryOutput);
5012 }
5013 }
5014 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005015 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5016 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005017 } else {
5018 mpClientInterface->stopTone();
5019 }
5020 }
5021 }
5022 }
5023}
5024
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005025audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5026{
5027 // flags to stream type mapping
5028 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5029 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5030 }
5031 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5032 return AUDIO_STREAM_BLUETOOTH_SCO;
5033 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005034 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5035 return AUDIO_STREAM_TTS;
5036 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005037
5038 // usage to stream type mapping
5039 switch (attr->usage) {
5040 case AUDIO_USAGE_MEDIA:
5041 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005042 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5043 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005044 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08005045 if (isStreamActive(AUDIO_STREAM_ALARM)) {
5046 return AUDIO_STREAM_ALARM;
5047 }
5048 if (isStreamActive(AUDIO_STREAM_RING)) {
5049 return AUDIO_STREAM_RING;
5050 }
5051 if (isInCall()) {
5052 return AUDIO_STREAM_VOICE_CALL;
5053 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08005054 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005055 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5056 return AUDIO_STREAM_SYSTEM;
5057 case AUDIO_USAGE_VOICE_COMMUNICATION:
5058 return AUDIO_STREAM_VOICE_CALL;
5059
5060 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5061 return AUDIO_STREAM_DTMF;
5062
5063 case AUDIO_USAGE_ALARM:
5064 return AUDIO_STREAM_ALARM;
5065 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5066 return AUDIO_STREAM_RING;
5067
5068 case AUDIO_USAGE_NOTIFICATION:
5069 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5070 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5071 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5072 case AUDIO_USAGE_NOTIFICATION_EVENT:
5073 return AUDIO_STREAM_NOTIFICATION;
5074
5075 case AUDIO_USAGE_UNKNOWN:
5076 default:
5077 return AUDIO_STREAM_MUSIC;
5078 }
5079}
Eric Laurente83b55d2014-11-14 10:06:21 -08005080
François Gaffie53615e22015-03-19 09:24:12 +01005081bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5082{
Eric Laurente83b55d2014-11-14 10:06:21 -08005083 // has flags that map to a strategy?
5084 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5085 return true;
5086 }
5087
5088 // has known usage?
5089 switch (paa->usage) {
5090 case AUDIO_USAGE_UNKNOWN:
5091 case AUDIO_USAGE_MEDIA:
5092 case AUDIO_USAGE_VOICE_COMMUNICATION:
5093 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5094 case AUDIO_USAGE_ALARM:
5095 case AUDIO_USAGE_NOTIFICATION:
5096 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5097 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5098 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5099 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5100 case AUDIO_USAGE_NOTIFICATION_EVENT:
5101 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5102 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5103 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5104 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005105 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005106 break;
5107 default:
5108 return false;
5109 }
5110 return true;
5111}
5112
François Gaffiead3183e2015-03-18 16:55:35 +01005113bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5114 routing_strategy strategy, uint32_t inPastMs,
5115 nsecs_t sysTime) const
5116{
5117 if ((sysTime == 0) && (inPastMs != 0)) {
5118 sysTime = systemTime();
5119 }
5120 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5121 if (i == AUDIO_STREAM_PATCH) {
5122 continue;
5123 }
5124 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5125 (NUM_STRATEGIES == strategy)) &&
5126 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5127 return true;
5128 }
5129 }
5130 return false;
5131}
5132
François Gaffie2110e042015-03-24 08:41:51 +01005133audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5134{
5135 return mEngine->getForceUse(usage);
5136}
5137
5138bool AudioPolicyManager::isInCall()
5139{
5140 return isStateInCall(mEngine->getPhoneState());
5141}
5142
5143bool AudioPolicyManager::isStateInCall(int state)
5144{
5145 return is_state_in_call(state);
5146}
5147
Eric Laurentd60560a2015-04-10 11:31:20 -07005148void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5149{
5150 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5151 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5152 if (sourceDesc->mDevice->equals(deviceDesc)) {
5153 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5154 stopAudioSource(sourceDesc->getHandle());
5155 }
5156 }
5157
5158 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5159 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5160 bool release = false;
5161 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5162 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5163 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5164 source->ext.device.type == deviceDesc->type()) {
5165 release = true;
5166 }
5167 }
5168 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5169 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5170 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5171 sink->ext.device.type == deviceDesc->type()) {
5172 release = true;
5173 }
5174 }
5175 if (release) {
5176 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5177 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5178 }
5179 }
5180}
5181
Phil Burk09bc4612016-02-24 15:58:15 -08005182// Modify the list of surround sound formats supported.
5183void AudioPolicyManager::filterSurroundFormats(FormatVector &formats) {
5184
5185 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5186 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5187 ALOGI("%s: forced use = %d", __FUNCTION__, forceUse);
5188
5189 // Analyze original support for various formats.
5190 bool supportsRawSurround = false;
5191 bool supportsIEC61937 = false;
5192 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5193 audio_format_t format = formats[formatIndex];
5194 ALOGI("%s: original formats: #%x", __FUNCTION__, format);
5195 switch (format) {
5196 case AUDIO_FORMAT_AC3:
5197 case AUDIO_FORMAT_E_AC3:
5198 case AUDIO_FORMAT_DTS:
5199 case AUDIO_FORMAT_DTS_HD:
5200 supportsRawSurround = true;
5201 break;
5202 case AUDIO_FORMAT_IEC61937:
5203 supportsIEC61937 = true;
5204 break;
5205 default:
5206 break;
5207 }
5208 }
5209 ALOGI("%s: supportsRawSurround = %d, supportsIEC61937 = %d",
5210 __FUNCTION__, supportsRawSurround, supportsIEC61937);
5211
5212 // Modify formats based on surround preferences.
5213 // If NEVER, remove support for surround formats.
5214 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER)
5215 && (supportsRawSurround || supportsIEC61937)) {
5216 // Remove surround sound related formats.
5217 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5218 audio_format_t format = formats[formatIndex];
5219 switch(format) {
5220 case AUDIO_FORMAT_AC3:
5221 case AUDIO_FORMAT_E_AC3:
5222 case AUDIO_FORMAT_DTS:
5223 case AUDIO_FORMAT_DTS_HD:
5224 case AUDIO_FORMAT_IEC61937:
5225 ALOGI("%s: remove #%x", __FUNCTION__, format);
5226 formats.removeAt(formatIndex);
5227 break;
5228 default:
5229 formatIndex++; // keep it
5230 break;
5231 }
5232 }
5233 supportsRawSurround = false;
5234 supportsIEC61937 = false;
5235 }
5236 // If ALWAYS, add support for raw surround formats if all are missing.
5237 // This assumes that if any of these formats are reported by the HAL
5238 // then the report is valid and should not be modified.
5239 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5240 && !supportsRawSurround) {
5241 formats.add(AUDIO_FORMAT_AC3);
5242 formats.add(AUDIO_FORMAT_E_AC3);
5243 formats.add(AUDIO_FORMAT_DTS);
5244 formats.add(AUDIO_FORMAT_DTS_HD);
5245 supportsRawSurround = true;
5246 }
5247 // Add support for IEC61937 if raw surround supported.
5248 // The HAL could do this but add it here, just in case.
5249 if (supportsRawSurround && !supportsIEC61937) {
5250 formats.add(AUDIO_FORMAT_IEC61937);
5251 // supportsIEC61937 = true;
5252 }
5253 // Just for debugging.
5254 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5255 audio_format_t format = formats[formatIndex];
5256 ALOGI("%s: final formats: #%x", __FUNCTION__, format);
5257 }
5258}
5259
François Gaffie112b0af2015-11-19 16:13:25 +01005260void AudioPolicyManager::updateAudioProfiles(audio_io_handle_t ioHandle,
5261 AudioProfileVector &profiles)
5262{
5263 String8 reply;
5264 char *value;
5265 // Format MUST be checked first to update the list of AudioProfile
5266 if (profiles.hasDynamicFormat()) {
5267 reply = mpClientInterface->getParameters(ioHandle,
5268 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk09bc4612016-02-24 15:58:15 -08005269 ALOGI("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005270 AudioParameter repliedParameters(reply);
5271 if (repliedParameters.get(
5272 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005273 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5274 return;
5275 }
Phil Burk09bc4612016-02-24 15:58:15 -08005276 FormatVector formats = formatsFromString(reply.string());
5277 filterSurroundFormats(formats);
5278 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005279 }
5280 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5281
Eric Laurent20eb3a42016-01-26 18:39:17 -08005282 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005283 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005284 ChannelsVector channelMasks;
5285 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005286 AudioParameter requestedParameters;
5287 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5288
5289 if (profiles.hasDynamicRateFor(format)) {
5290 reply = mpClientInterface->getParameters(ioHandle,
5291 requestedParameters.toString() + ";" +
5292 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5293 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005294 AudioParameter repliedParameters(reply);
5295 if (repliedParameters.get(
5296 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5297 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005298 }
5299 }
5300 if (profiles.hasDynamicChannelsFor(format)) {
5301 reply = mpClientInterface->getParameters(ioHandle,
5302 requestedParameters.toString() + ";" +
5303 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5304 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005305 AudioParameter repliedParameters(reply);
5306 if (repliedParameters.get(
5307 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5308 channelMasks = channelMasksFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005309 }
5310 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005311 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005312 }
5313}
Eric Laurentd60560a2015-04-10 11:31:20 -07005314
Eric Laurente552edb2014-03-10 17:42:56 -07005315}; // namespace android