blob: 7de72de655b6023d4549fe4cfeaa116b1da93f45 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -080017#define LOG_TAG "APM::AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Eric Laurentd4692962014-05-05 18:13:44 -070027#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070028#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070029
François Gaffie2110e042015-03-24 08:41:51 +010030#include <AudioPolicyManagerInterface.h>
31#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070032#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <utils/Log.h>
34#include <hardware/audio.h>
35#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070036#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080037#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070038#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070040#include "audio_policy_conf.h"
François Gaffie53615e22015-03-19 09:24:12 +010041#include <ConfigParsingUtils.h>
42#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043
Eric Laurent3b73df72014-03-11 09:06:29 -070044namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070045
46// ----------------------------------------------------------------------------
47// AudioPolicyInterface implementation
48// ----------------------------------------------------------------------------
49
Eric Laurente0720872014-03-11 09:30:41 -070050status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080051 audio_policy_dev_state_t state,
52 const char *device_address,
53 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070054{
Paul McLeane743a472015-01-28 11:07:31 -080055 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080056}
57
58status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080059 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080060 const char *device_address,
61 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080062{
Paul McLeane743a472015-01-28 11:07:31 -080063 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
64- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070065
66 // connect/disconnect only 1 device at a time
67 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
68
François Gaffie53615e22015-03-19 09:24:12 +010069 sp<DeviceDescriptor> devDesc =
70 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080071
Eric Laurente552edb2014-03-10 17:42:56 -070072 // handle output devices
73 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070074 SortedVector <audio_io_handle_t> outputs;
75
Eric Laurent3a4311c2014-03-17 12:00:47 -070076 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
77
Eric Laurente552edb2014-03-10 17:42:56 -070078 // save a copy of the opened output descriptors before any output is opened or closed
79 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
80 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -070081 switch (state)
82 {
83 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -080084 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -070086 ALOGW("setDeviceConnectionState() device already connected: %x", device);
87 return INVALID_OPERATION;
88 }
89 ALOGV("setDeviceConnectionState() connecting device %x", device);
90
Eric Laurente552edb2014-03-10 17:42:56 -070091 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -070092 index = mAvailableOutputDevices.add(devDesc);
93 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +010094 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -070095 if (module == 0) {
96 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
97 device);
98 mAvailableOutputDevices.remove(devDesc);
99 return INVALID_OPERATION;
100 }
Paul McLeane743a472015-01-28 11:07:31 -0800101 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 } else {
103 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700104 }
105
Eric Laurenta1d525f2015-01-29 13:36:45 -0800106 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700107 mAvailableOutputDevices.remove(devDesc);
108 return INVALID_OPERATION;
109 }
François Gaffie2110e042015-03-24 08:41:51 +0100110 // Propagate device availability to Engine
111 mEngine->setDeviceConnectionState(devDesc, state);
112
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700113 // outputs should never be empty here
114 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
115 "checkOutputsForDevice() returned no outputs but status OK");
116 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
117 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800118
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800119 // Send connect to HALs
Eric Laurent3ae5f312015-02-03 17:12:08 -0800120 AudioParameter param = AudioParameter(devDesc->mAddress);
121 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
122 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
123
124 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700126 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700128 ALOGW("setDeviceConnectionState() device not connected: %x", device);
129 return INVALID_OPERATION;
130 }
131
Paul McLean5c477aa2014-08-20 16:47:57 -0700132 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
133
Paul McLeane743a472015-01-28 11:07:31 -0800134 // Send Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800135 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700136 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
137 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
138
Eric Laurente552edb2014-03-10 17:42:56 -0700139 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700140 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700141
Eric Laurenta1d525f2015-01-29 13:36:45 -0800142 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100143
144 // Propagate device availability to Engine
145 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700146 } break;
147
148 default:
149 ALOGE("setDeviceConnectionState() invalid state: %x", state);
150 return BAD_VALUE;
151 }
152
Eric Laurent3a4311c2014-03-17 12:00:47 -0700153 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
154 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700155 checkA2dpSuspend();
156 checkOutputForAllStrategies();
157 // outputs must be closed after checkOutputForAllStrategies() is executed
158 if (!outputs.isEmpty()) {
159 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700160 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700161 // close unused outputs after device disconnection or direct outputs that have been
162 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700163 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700164 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
165 (desc->mDirectOpenCount == 0))) {
166 closeOutput(outputs[i]);
167 }
168 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700169 // check again after closing A2DP output to reset mA2dpSuspended if needed
170 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700171 }
172
173 updateDevicesAndOutputs();
François Gaffie2110e042015-03-24 08:41:51 +0100174 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700175 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
176 updateCallRouting(newDevice);
177 }
Eric Laurente552edb2014-03-10 17:42:56 -0700178 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700179 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
180 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
181 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700182 // do not force device change on duplicated output because if device is 0, it will
183 // also force a device 0 for the two outputs it is duplicated to which may override
184 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700185 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100186 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700187 // always force when disconnecting (a non-duplicated device)
188 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700189 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700190 }
Eric Laurente552edb2014-03-10 17:42:56 -0700191 }
192
Eric Laurent72aa32f2014-05-30 18:51:48 -0700193 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700194 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700195 } // end if is output device
196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 // handle input devices
198 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700199 SortedVector <audio_io_handle_t> inputs;
200
Eric Laurent3a4311c2014-03-17 12:00:47 -0700201 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700202 switch (state)
203 {
204 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700205 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700207 ALOGW("setDeviceConnectionState() device already connected: %d", device);
208 return INVALID_OPERATION;
209 }
François Gaffie53615e22015-03-19 09:24:12 +0100210 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700211 if (module == NULL) {
212 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
213 device);
214 return INVALID_OPERATION;
215 }
Eric Laurenta1d525f2015-01-29 13:36:45 -0800216 if (checkInputsForDevice(device, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700217 return INVALID_OPERATION;
218 }
219
Eric Laurent3a4311c2014-03-17 12:00:47 -0700220 index = mAvailableInputDevices.add(devDesc);
221 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800222 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700223 } else {
224 return NO_MEMORY;
225 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226
227 // Set connect to HALs
228 AudioParameter param = AudioParameter(devDesc->mAddress);
229 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
230 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
231
François Gaffie2110e042015-03-24 08:41:51 +0100232 // Propagate device availability to Engine
233 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700234 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700235
236 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700239 ALOGW("setDeviceConnectionState() device not connected: %d", device);
240 return INVALID_OPERATION;
241 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
243 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
244
245 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800246 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700247 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
248 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
249
Eric Laurenta1d525f2015-01-29 13:36:45 -0800250 checkInputsForDevice(device, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700252
François Gaffie2110e042015-03-24 08:41:51 +0100253 // Propagate device availability to Engine
254 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700255 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700256
257 default:
258 ALOGE("setDeviceConnectionState() invalid state: %x", state);
259 return BAD_VALUE;
260 }
261
Eric Laurentd4692962014-05-05 18:13:44 -0700262 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700263
François Gaffie2110e042015-03-24 08:41:51 +0100264 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700265 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
266 updateCallRouting(newDevice);
267 }
268
Eric Laurentb52c1522014-05-20 11:27:36 -0700269 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700270 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700271 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700272
273 ALOGW("setDeviceConnectionState() invalid device: %x", device);
274 return BAD_VALUE;
275}
276
Eric Laurente0720872014-03-11 09:30:41 -0700277audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100278 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700279{
François Gaffie53615e22015-03-19 09:24:12 +0100280 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(device, device_address, "");
281
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 DeviceVector *deviceVector;
283
Eric Laurente552edb2014-03-10 17:42:56 -0700284 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700285 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700286 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700287 deviceVector = &mAvailableInputDevices;
288 } else {
289 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
290 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700291 }
François Gaffie53615e22015-03-19 09:24:12 +0100292 return deviceVector->getDeviceConnectionState(devDesc);
Eric Laurenta1d525f2015-01-29 13:36:45 -0800293}
294
Eric Laurentc2730ba2014-07-20 15:47:07 -0700295void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
296{
297 bool createTxPatch = false;
298 struct audio_patch patch;
299 patch.num_sources = 1;
300 patch.num_sinks = 1;
301 status_t status;
302 audio_patch_handle_t afPatchHandle;
303 DeviceVector deviceList;
304
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800305 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700306 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
307
308 // release existing RX patch if any
309 if (mCallRxPatch != 0) {
310 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
311 mCallRxPatch.clear();
312 }
313 // release TX patch if any
314 if (mCallTxPatch != 0) {
315 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
316 mCallTxPatch.clear();
317 }
318
319 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
320 // via setOutputDevice() on primary output.
321 // Otherwise, create two audio patches for TX and RX path.
322 if (availablePrimaryOutputDevices() & rxDevice) {
323 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
324 // If the TX device is also on the primary HW module, setOutputDevice() will take care
325 // of it due to legacy implementation. If not, create a patch.
326 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
327 == AUDIO_DEVICE_NONE) {
328 createTxPatch = true;
329 }
330 } else {
331 // create RX path audio patch
332 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
333 ALOG_ASSERT(!deviceList.isEmpty(),
334 "updateCallRouting() selected device not in output device list");
335 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
336 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
337 ALOG_ASSERT(!deviceList.isEmpty(),
338 "updateCallRouting() no telephony RX device");
339 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
340
341 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
342 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
343
344 // request to reuse existing output stream if one is already opened to reach the RX device
345 SortedVector<audio_io_handle_t> outputs =
346 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700347 audio_io_handle_t output = selectOutput(outputs,
348 AUDIO_OUTPUT_FLAG_NONE,
349 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700350 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700351 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700352 ALOG_ASSERT(!outputDesc->isDuplicated(),
353 "updateCallRouting() RX device output is duplicated");
354 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700355 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700356 patch.num_sources = 2;
357 }
358
359 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
360 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
361 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
362 status);
363 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100364 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700365 mCallRxPatch->mAfPatchHandle = afPatchHandle;
366 mCallRxPatch->mUid = mUidCached;
367 }
368 createTxPatch = true;
369 }
370 if (createTxPatch) {
371
372 struct audio_patch patch;
373 patch.num_sources = 1;
374 patch.num_sinks = 1;
375 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
376 ALOG_ASSERT(!deviceList.isEmpty(),
377 "updateCallRouting() selected device not in input device list");
378 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
379 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
380 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
381 ALOG_ASSERT(!deviceList.isEmpty(),
382 "updateCallRouting() no telephony TX device");
383 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
384 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
385
386 SortedVector<audio_io_handle_t> outputs =
387 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700388 audio_io_handle_t output = selectOutput(outputs,
389 AUDIO_OUTPUT_FLAG_NONE,
390 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700391 // request to reuse existing output stream if one is already opened to reach the TX
392 // path output device
393 if (output != AUDIO_IO_HANDLE_NONE) {
394 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
395 ALOG_ASSERT(!outputDesc->isDuplicated(),
396 "updateCallRouting() RX device output is duplicated");
397 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700398 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700399 patch.num_sources = 2;
400 }
401
402 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
403 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
404 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
405 status);
406 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100407 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700408 mCallTxPatch->mAfPatchHandle = afPatchHandle;
409 mCallTxPatch->mUid = mUidCached;
410 }
411 }
412}
413
Eric Laurente0720872014-03-11 09:30:41 -0700414void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700415{
416 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100417 // store previous phone state for management of sonification strategy below
418 int oldState = mEngine->getPhoneState();
419
420 if (mEngine->setPhoneState(state) != NO_ERROR) {
421 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700422 return;
423 }
François Gaffie2110e042015-03-24 08:41:51 +0100424 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700425 // if leaving call state, handle special case of active streams
426 // pertaining to sonification strategy see handleIncallSonification()
427 if (isInCall()) {
428 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700429 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800430 if (stream == AUDIO_STREAM_PATCH) {
431 continue;
432 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700433 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700434 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800435
436 // force reevaluating accessibility routing when call starts
437 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700438 }
439
François Gaffie2110e042015-03-24 08:41:51 +0100440 /**
441 * Switching to or from incall state or switching between telephony and VoIP lead to force
442 * routing command.
443 */
444 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
445 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700446
447 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700448 checkA2dpSuspend();
449 checkOutputForAllStrategies();
450 updateDevicesAndOutputs();
451
Eric Laurentc75307b2015-03-17 15:29:32 -0700452 sp<SwAudioOutputDescriptor> hwOutputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -0700453
Eric Laurente552edb2014-03-10 17:42:56 -0700454 int delayMs = 0;
455 if (isStateInCall(state)) {
456 nsecs_t sysTime = systemTime();
457 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700458 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700459 // mute media and sonification strategies and delay device switch by the largest
460 // latency of any output where either strategy is active.
461 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100462 if ((isStrategyActive(desc, STRATEGY_MEDIA,
463 SONIFICATION_HEADSET_MUSIC_DELAY,
464 sysTime) ||
465 isStrategyActive(desc, STRATEGY_SONIFICATION,
466 SONIFICATION_HEADSET_MUSIC_DELAY,
467 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700468 (delayMs < (int)desc->latency()*2)) {
469 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700470 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700471 setStrategyMute(STRATEGY_MEDIA, true, desc);
472 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700473 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700474 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
475 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700476 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
477 }
478 }
479
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
481 // the device returned is not necessarily reachable via this output
482 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
483 // force routing command to audio hardware when ending call
484 // even if no device change is needed
485 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
486 rxDevice = hwOutputDesc->device();
487 }
Eric Laurente552edb2014-03-10 17:42:56 -0700488
Eric Laurentc2730ba2014-07-20 15:47:07 -0700489 if (state == AUDIO_MODE_IN_CALL) {
490 updateCallRouting(rxDevice, delayMs);
491 } else if (oldState == AUDIO_MODE_IN_CALL) {
492 if (mCallRxPatch != 0) {
493 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
494 mCallRxPatch.clear();
495 }
496 if (mCallTxPatch != 0) {
497 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
498 mCallTxPatch.clear();
499 }
500 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
501 } else {
502 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
503 }
Eric Laurente552edb2014-03-10 17:42:56 -0700504 // if entering in call state, handle special case of active streams
505 // pertaining to sonification strategy see handleIncallSonification()
506 if (isStateInCall(state)) {
507 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700508 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800509 if (stream == AUDIO_STREAM_PATCH) {
510 continue;
511 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700512 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700513 }
514 }
515
516 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700517 if (state == AUDIO_MODE_RINGTONE &&
518 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700519 mLimitRingtoneVolume = true;
520 } else {
521 mLimitRingtoneVolume = false;
522 }
523}
524
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700525audio_mode_t AudioPolicyManager::getPhoneState() {
526 return mEngine->getPhoneState();
527}
528
Eric Laurente0720872014-03-11 09:30:41 -0700529void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700530 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700531{
François Gaffie2110e042015-03-24 08:41:51 +0100532 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700533
François Gaffie2110e042015-03-24 08:41:51 +0100534 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
535 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
536 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700537 }
François Gaffie2110e042015-03-24 08:41:51 +0100538 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
539 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
540 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700541
542 // check for device and output changes triggered by new force usage
543 checkA2dpSuspend();
544 checkOutputForAllStrategies();
545 updateDevicesAndOutputs();
François Gaffie2110e042015-03-24 08:41:51 +0100546 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
548 updateCallRouting(newDevice);
549 }
Eric Laurente552edb2014-03-10 17:42:56 -0700550 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700551 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
552 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
553 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
554 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700555 }
Eric Laurente552edb2014-03-10 17:42:56 -0700556 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700557 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700558 }
559 }
560
François Gaffie53615e22015-03-19 09:24:12 +0100561 audio_io_handle_t activeInput = mInputs.getActiveInput();
Eric Laurente552edb2014-03-10 17:42:56 -0700562 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700563 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700564 }
565
566}
567
Eric Laurente0720872014-03-11 09:30:41 -0700568void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700569{
570 ALOGV("setSystemProperty() property %s, value %s", property, value);
571}
572
573// Find a direct output profile compatible with the parameters passed, even if the input flags do
574// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800575sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700576 audio_devices_t device,
577 uint32_t samplingRate,
578 audio_format_t format,
579 audio_channel_mask_t channelMask,
580 audio_output_flags_t flags)
581{
582 for (size_t i = 0; i < mHwModules.size(); i++) {
583 if (mHwModules[i]->mHandle == 0) {
584 continue;
585 }
586 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700587 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Andy Hungf129b032015-04-07 13:45:50 -0700588 bool found = profile->isCompatibleProfile(device, String8(""),
589 samplingRate, NULL /*updatedSamplingRate*/,
590 format, NULL /*updatedFormat*/,
591 channelMask, NULL /*updatedChannelMask*/,
Glenn Kastencbd48022014-07-24 13:46:44 -0700592 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
593 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700594 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
595 return profile;
596 }
Eric Laurente552edb2014-03-10 17:42:56 -0700597 }
598 }
599 return 0;
600}
601
Eric Laurente0720872014-03-11 09:30:41 -0700602audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100603 uint32_t samplingRate,
604 audio_format_t format,
605 audio_channel_mask_t channelMask,
606 audio_output_flags_t flags,
607 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700608{
Eric Laurent3b73df72014-03-11 09:06:29 -0700609 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700610 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
611 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
612 device, stream, samplingRate, format, channelMask, flags);
613
Eric Laurente83b55d2014-11-14 10:06:21 -0800614 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
615 stream, samplingRate,format, channelMask,
616 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700617}
618
Eric Laurente83b55d2014-11-14 10:06:21 -0800619status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
620 audio_io_handle_t *output,
621 audio_session_t session,
622 audio_stream_type_t *stream,
623 uint32_t samplingRate,
624 audio_format_t format,
625 audio_channel_mask_t channelMask,
626 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700627 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800628 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700629{
Eric Laurente83b55d2014-11-14 10:06:21 -0800630 audio_attributes_t attributes;
631 if (attr != NULL) {
632 if (!isValidAttributes(attr)) {
633 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
634 attr->usage, attr->content_type, attr->flags,
635 attr->tags);
636 return BAD_VALUE;
637 }
638 attributes = *attr;
639 } else {
640 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
641 ALOGE("getOutputForAttr(): invalid stream type");
642 return BAD_VALUE;
643 }
644 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700645 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700646 sp<SwAudioOutputDescriptor> desc;
François Gaffie036e1e92015-03-19 10:16:24 +0100647 if (mPolicyMixes.getOutputForAttr(attributes, desc) == NO_ERROR) {
648 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
649 if (!audio_is_linear_pcm(format)) {
650 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800651 }
François Gaffie036e1e92015-03-19 10:16:24 +0100652 *stream = streamTypefromAttributesInt(&attributes);
653 *output = desc->mIoHandle;
654 ALOGV("getOutputForAttr() returns output %d", *output);
655 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800656 }
657 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
658 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
659 return BAD_VALUE;
660 }
661
Eric Laurent93c3d412014-08-01 14:48:35 -0700662 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
François Gaffie53615e22015-03-19 09:24:12 +0100663 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700664
Eric Laurente83b55d2014-11-14 10:06:21 -0800665 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700666 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700667
Eric Laurente83b55d2014-11-14 10:06:21 -0800668 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700669 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
670 }
671
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700672 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700673 device, samplingRate, format, channelMask, flags);
674
Eric Laurente83b55d2014-11-14 10:06:21 -0800675 *stream = streamTypefromAttributesInt(&attributes);
676 *output = getOutputForDevice(device, session, *stream,
677 samplingRate, format, channelMask,
678 flags, offloadInfo);
679 if (*output == AUDIO_IO_HANDLE_NONE) {
680 return INVALID_OPERATION;
681 }
Paul McLeanaa981192015-03-21 09:55:15 -0700682
683 // Explicit routing?
684 sp<DeviceDescriptor> deviceDesc;
685
686 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent322b4d22015-04-03 15:57:54 -0700687 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
Paul McLeanaa981192015-03-21 09:55:15 -0700688 deviceDesc = mAvailableOutputDevices[i];
689 break;
690 }
691 }
Paul McLean466dc8e2015-04-17 13:15:36 -0600692 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc);
Eric Laurente83b55d2014-11-14 10:06:21 -0800693 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700694}
695
696audio_io_handle_t AudioPolicyManager::getOutputForDevice(
697 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800698 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700699 audio_stream_type_t stream,
700 uint32_t samplingRate,
701 audio_format_t format,
702 audio_channel_mask_t channelMask,
703 audio_output_flags_t flags,
704 const audio_offload_info_t *offloadInfo)
705{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700706 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700707 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700708 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700709
Eric Laurente552edb2014-03-10 17:42:56 -0700710#ifdef AUDIO_POLICY_TEST
711 if (mCurOutput != 0) {
712 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
713 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
714
715 if (mTestOutputs[mCurOutput] == 0) {
716 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700717 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
718 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700719 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700720 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700721 outputDesc->mFlags =
722 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700723 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700724 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
725 config.sample_rate = mTestSamplingRate;
726 config.channel_mask = mTestChannels;
727 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700728 if (offloadInfo != NULL) {
729 config.offload_info = *offloadInfo;
730 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700731 status = mpClientInterface->openOutput(0,
732 &mTestOutputs[mCurOutput],
733 &config,
734 &outputDesc->mDevice,
735 String8(""),
736 &outputDesc->mLatency,
737 outputDesc->mFlags);
738 if (status == NO_ERROR) {
739 outputDesc->mSamplingRate = config.sample_rate;
740 outputDesc->mFormat = config.format;
741 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700742 AudioParameter outputCmd = AudioParameter();
743 outputCmd.addInt(String8("set_id"),mCurOutput);
744 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
745 addOutput(mTestOutputs[mCurOutput], outputDesc);
746 }
747 }
748 return mTestOutputs[mCurOutput];
749 }
750#endif //AUDIO_POLICY_TEST
751
752 // open a direct output if required by specified parameters
753 //force direct flag if offload flag is set: offloading implies a direct output stream
754 // and all common behaviors are driven by checking only the direct flag
755 // this should normally be set appropriately in the policy configuration file
756 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700757 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700758 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700759 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
760 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
761 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800762 // only allow deep buffering for music stream type
763 if (stream != AUDIO_STREAM_MUSIC) {
764 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
765 }
Eric Laurente552edb2014-03-10 17:42:56 -0700766
Eric Laurentb732cf52014-09-24 19:08:21 -0700767 sp<IOProfile> profile;
768
769 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700770 // and not explicitly requested
771 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
772 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700773 audio_channel_count_from_out_mask(channelMask) <= 2) {
774 goto non_direct_output;
775 }
776
Eric Laurente552edb2014-03-10 17:42:56 -0700777 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
778 // creating an offloaded track and tearing it down immediately after start when audioflinger
779 // detects there is an active non offloadable effect.
780 // FIXME: We should check the audio session here but we do not have it in this context.
781 // This may prevent offloading in rare situations where effects are left active by apps
782 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700783
Eric Laurente552edb2014-03-10 17:42:56 -0700784 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
François Gaffie45ed3b02015-03-19 10:35:14 +0100785 !mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -0700786 profile = getProfileForDirectOutput(device,
787 samplingRate,
788 format,
789 channelMask,
790 (audio_output_flags_t)flags);
791 }
792
Eric Laurent1c333e22014-05-20 10:48:17 -0700793 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700794 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700795
796 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700797 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700798 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
799 outputDesc = desc;
800 // reuse direct output if currently open and configured with same parameters
801 if ((samplingRate == outputDesc->mSamplingRate) &&
802 (format == outputDesc->mFormat) &&
803 (channelMask == outputDesc->mChannelMask)) {
804 outputDesc->mDirectOpenCount++;
805 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
806 return mOutputs.keyAt(i);
807 }
808 }
809 }
810 // close direct output if currently open and configured with different parameters
811 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700814 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700815 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700816 outputDesc->mLatency = 0;
817 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700818 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
819 config.sample_rate = samplingRate;
820 config.channel_mask = channelMask;
821 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700822 if (offloadInfo != NULL) {
823 config.offload_info = *offloadInfo;
824 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700825 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700826 &output,
827 &config,
828 &outputDesc->mDevice,
829 String8(""),
830 &outputDesc->mLatency,
831 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700832
833 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700834 if (status != NO_ERROR ||
835 (samplingRate != 0 && samplingRate != config.sample_rate) ||
836 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
837 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700838 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
839 "format %d %d, channelMask %04x %04x", output, samplingRate,
840 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
841 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700842 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700843 mpClientInterface->closeOutput(output);
844 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800845 // fall back to mixer output if possible when the direct output could not be open
846 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
847 goto non_direct_output;
848 }
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800849 // fall back to mixer output if possible when the direct output could not be open
850 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
851 goto non_direct_output;
852 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700853 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700854 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700855 outputDesc->mSamplingRate = config.sample_rate;
856 outputDesc->mChannelMask = config.channel_mask;
857 outputDesc->mFormat = config.format;
858 outputDesc->mRefCount[stream] = 0;
859 outputDesc->mStopTime[stream] = 0;
860 outputDesc->mDirectOpenCount = 1;
861
Eric Laurente552edb2014-03-10 17:42:56 -0700862 audio_io_handle_t srcOutput = getOutputForEffect();
863 addOutput(output, outputDesc);
864 audio_io_handle_t dstOutput = getOutputForEffect();
865 if (dstOutput == output) {
866 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
867 }
868 mPreviousOutputs = mOutputs;
869 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700870 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700871 return output;
872 }
873
Eric Laurentb732cf52014-09-24 19:08:21 -0700874non_direct_output:
Eric Laurente552edb2014-03-10 17:42:56 -0700875 // ignoring channel mask due to downmix capability in mixer
876
877 // open a non direct output
878
879 // for non direct outputs, only PCM is supported
880 if (audio_is_linear_pcm(format)) {
881 // get which output is suitable for the specified stream. The actual
882 // routing change will happen when startOutput() will be called
883 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
884
Eric Laurent8838a382014-09-08 16:44:28 -0700885 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
886 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
887 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -0700888 }
889 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
890 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
891
Paul McLeanaa981192015-03-21 09:55:15 -0700892 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -0700893
894 return output;
895}
896
Eric Laurente0720872014-03-11 09:30:41 -0700897audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700898 audio_output_flags_t flags,
899 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700900{
901 // select one output among several that provide a path to a particular device or set of
902 // devices (the list was previously build by getOutputsForDevice()).
903 // The priority is as follows:
904 // 1: the output with the highest number of requested policy flags
905 // 2: the primary output
906 // 3: the first output in the list
907
908 if (outputs.size() == 0) {
909 return 0;
910 }
911 if (outputs.size() == 1) {
912 return outputs[0];
913 }
914
915 int maxCommonFlags = 0;
916 audio_io_handle_t outputFlags = 0;
917 audio_io_handle_t outputPrimary = 0;
918
919 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700920 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700921 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -0700922 // if a valid format is specified, skip output if not compatible
923 if (format != AUDIO_FORMAT_INVALID) {
924 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
925 if (format != outputDesc->mFormat) {
926 continue;
927 }
928 } else if (!audio_is_linear_pcm(format)) {
929 continue;
930 }
931 }
932
Eric Laurent3b73df72014-03-11 09:06:29 -0700933 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700934 if (commonFlags > maxCommonFlags) {
935 outputFlags = outputs[i];
936 maxCommonFlags = commonFlags;
937 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
938 }
939 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
940 outputPrimary = outputs[i];
941 }
942 }
943 }
944
945 if (outputFlags != 0) {
946 return outputFlags;
947 }
948 if (outputPrimary != 0) {
949 return outputPrimary;
950 }
951
952 return outputs[0];
953}
954
Eric Laurente0720872014-03-11 09:30:41 -0700955status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700956 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -0800957 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -0700958{
Paul McLeanaa981192015-03-21 09:55:15 -0700959 ALOGV("startOutput() output %d, stream %d, session %d",
960 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 ssize_t index = mOutputs.indexOfKey(output);
962 if (index < 0) {
963 ALOGW("startOutput() unknown output %d", output);
964 return BAD_VALUE;
965 }
966
Eric Laurentc75307b2015-03-17 15:29:32 -0700967 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
968
969 audio_devices_t newDevice;
970 if (outputDesc->mPolicyMix != NULL) {
971 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent493404d2015-04-21 15:07:36 -0700972 } else if (mOutputRoutes.hasRouteChanged(session)) {
973 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700974 } else {
975 newDevice = AUDIO_DEVICE_NONE;
976 }
977
978 uint32_t delayMs = 0;
979
980 // Routing?
981 mOutputRoutes.incRouteActivity(session);
982
983 status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
984
985 if (status != NO_ERROR) {
986 mOutputRoutes.decRouteActivity(session);
987 }
988 // Automatically enable the remote submix input when output is started on a re routing mix
989 // of type MIX_TYPE_RECORDERS
990 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
991 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
992 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
993 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
994 outputDesc->mPolicyMix->mRegistrationId,
995 "remote-submix");
996 }
997
998 if (delayMs != 0) {
999 usleep(delayMs * 1000);
1000 }
1001
1002 return status;
1003}
1004
1005status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1006 audio_stream_type_t stream,
1007 audio_devices_t device,
1008 uint32_t *delayMs)
1009{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001010 // cannot start playback of STREAM_TTS if any other output is being used
1011 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001012
1013 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001014 if (stream == AUDIO_STREAM_TTS) {
1015 ALOGV("\t found BEACON stream");
François Gaffie53615e22015-03-19 09:24:12 +01001016 if (mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001017 return INVALID_OPERATION;
1018 } else {
1019 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1020 }
1021 } else {
1022 // some playback other than beacon starts
1023 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1024 }
1025
Eric Laurente552edb2014-03-10 17:42:56 -07001026 // increment usage count for this stream on the requested output:
1027 // NOTE that the usage count is the same for duplicated output and hardware output which is
1028 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1029 outputDesc->changeRefCount(stream, 1);
1030
Eric Laurent493404d2015-04-21 15:07:36 -07001031 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001032 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001033 if (device == AUDIO_DEVICE_NONE) {
1034 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001035 }
Eric Laurente552edb2014-03-10 17:42:56 -07001036 routing_strategy strategy = getStrategy(stream);
1037 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001038 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1039 (beaconMuteLatency > 0);
1040 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001041 bool force = false;
1042 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001043 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001044 if (desc != outputDesc) {
1045 // force a device change if any other output is managed by the same hw
1046 // module and has a current device selection that differs from selected device.
1047 // In this case, the audio HAL must receive the new device selection so that it can
1048 // change the device currently selected by the other active output.
1049 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001050 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001051 force = true;
1052 }
1053 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001054 // a notification so that audio focus effect can propagate, or that a mute/unmute
1055 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001056 uint32_t latency = desc->latency();
1057 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1058 waitMs = latency;
1059 }
1060 }
1061 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001062 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
Eric Laurente552edb2014-03-10 17:42:56 -07001063
1064 // handle special case for sonification while in call
1065 if (isInCall()) {
1066 handleIncallSonification(stream, true, false);
1067 }
1068
1069 // apply volume rules for current stream and device if necessary
1070 checkAndSetVolume(stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07001071 mStreams.valueFor(stream).getVolumeIndex(device),
1072 outputDesc,
1073 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001074
1075 // update the outputs if starting an output with a stream that can affect notification
1076 // routing
1077 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001078
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001079 // force reevaluating accessibility routing when ringtone or alarm starts
1080 if (strategy == STRATEGY_SONIFICATION) {
1081 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1082 }
Eric Laurente552edb2014-03-10 17:42:56 -07001083 }
1084 return NO_ERROR;
1085}
1086
1087
Eric Laurente0720872014-03-11 09:30:41 -07001088status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001089 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001090 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001091{
1092 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1093 ssize_t index = mOutputs.indexOfKey(output);
1094 if (index < 0) {
1095 ALOGW("stopOutput() unknown output %d", output);
1096 return BAD_VALUE;
1097 }
1098
Eric Laurentc75307b2015-03-17 15:29:32 -07001099 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001100
Eric Laurentc75307b2015-03-17 15:29:32 -07001101 if (outputDesc->mRefCount[stream] == 1) {
1102 // Automatically disable the remote submix input when output is stopped on a
1103 // re routing mix of type MIX_TYPE_RECORDERS
1104 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1105 outputDesc->mPolicyMix != NULL &&
1106 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1107 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1108 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1109 outputDesc->mPolicyMix->mRegistrationId,
1110 "remote-submix");
1111 }
1112 }
1113
1114 // Routing?
1115 if (outputDesc->mRefCount[stream] > 0) {
1116 mOutputRoutes.decRouteActivity(session);
1117 }
1118
1119 return stopSource(outputDesc, stream);
1120}
1121
1122status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
1123 audio_stream_type_t stream)
1124{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001125 // always handle stream stop, check which stream type is stopping
1126 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1127
Eric Laurente552edb2014-03-10 17:42:56 -07001128 // handle special case for sonification while in call
1129 if (isInCall()) {
1130 handleIncallSonification(stream, false, false);
1131 }
1132
1133 if (outputDesc->mRefCount[stream] > 0) {
1134 // decrement usage count of this stream on the output
1135 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001136
Eric Laurente552edb2014-03-10 17:42:56 -07001137 // store time at which the stream was stopped - see isStreamActive()
1138 if (outputDesc->mRefCount[stream] == 0) {
1139 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001140 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001141 // delay the device switch by twice the latency because stopOutput() is executed when
1142 // the track stop() command is received and at that time the audio track buffer can
1143 // still contain data that needs to be drained. The latency only covers the audio HAL
1144 // and kernel buffers. Also the latency does not always include additional delay in the
1145 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001146 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001147
1148 // force restoring the device selection on other active outputs if it differs from the
1149 // one being selected for this output
1150 for (size_t i = 0; i < mOutputs.size(); i++) {
1151 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001152 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001153 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001154 desc->isActive() &&
1155 outputDesc->sharesHwModuleWith(desc) &&
1156 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001157 setOutputDevice(desc,
1158 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001159 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001160 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001161 }
1162 }
1163 // update the outputs if stopping one with a stream that can affect notification routing
1164 handleNotificationRoutingForStream(stream);
1165 }
1166 return NO_ERROR;
1167 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001168 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001169 return INVALID_OPERATION;
1170 }
1171}
1172
Eric Laurente83b55d2014-11-14 10:06:21 -08001173void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001174 audio_stream_type_t stream __unused,
1175 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001176{
1177 ALOGV("releaseOutput() %d", output);
1178 ssize_t index = mOutputs.indexOfKey(output);
1179 if (index < 0) {
1180 ALOGW("releaseOutput() releasing unknown output %d", output);
1181 return;
1182 }
1183
1184#ifdef AUDIO_POLICY_TEST
1185 int testIndex = testOutputIndex(output);
1186 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001187 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001188 if (outputDesc->isActive()) {
1189 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001190 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001191 mTestOutputs[testIndex] = 0;
1192 }
1193 return;
1194 }
1195#endif //AUDIO_POLICY_TEST
1196
Paul McLeanaa981192015-03-21 09:55:15 -07001197 // Routing
1198 mOutputRoutes.removeRoute(session);
1199
Eric Laurentc75307b2015-03-17 15:29:32 -07001200 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001201 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001202 if (desc->mDirectOpenCount <= 0) {
1203 ALOGW("releaseOutput() invalid open count %d for output %d",
1204 desc->mDirectOpenCount, output);
1205 return;
1206 }
1207 if (--desc->mDirectOpenCount == 0) {
1208 closeOutput(output);
1209 // If effects where present on the output, audioflinger moved them to the primary
1210 // output by default: move them back to the appropriate output.
1211 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurentc75307b2015-03-17 15:29:32 -07001212 if (dstOutput != mPrimaryOutput->mIoHandle) {
1213 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1214 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001215 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001216 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001217 }
1218 }
1219}
1220
1221
Eric Laurentcaf7f482014-11-25 17:50:47 -08001222status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1223 audio_io_handle_t *input,
1224 audio_session_t session,
1225 uint32_t samplingRate,
1226 audio_format_t format,
1227 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001228 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001229 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001230 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001231{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001232 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1233 "session %d, flags %#x",
1234 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001235
Eric Laurentcaf7f482014-11-25 17:50:47 -08001236 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001237 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001238 audio_devices_t device;
1239 // handle legacy remote submix case where the address was not always specified
1240 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001241 bool isSoundTrigger = false;
Eric Laurentc447ded2015-01-06 08:47:05 -08001242 audio_source_t inputSource = attr->source;
1243 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001244 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001245
Eric Laurentc447ded2015-01-06 08:47:05 -08001246 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1247 inputSource = AUDIO_SOURCE_MIC;
1248 }
1249 halInputSource = inputSource;
1250
Paul McLean466dc8e2015-04-17 13:15:36 -06001251 // Explicit routing?
1252 sp<DeviceDescriptor> deviceDesc;
1253 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1254 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1255 deviceDesc = mAvailableInputDevices[i];
1256 break;
1257 }
1258 }
1259 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc);
1260
Eric Laurentc447ded2015-01-06 08:47:05 -08001261 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001262 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001263 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001264 if (ret != NO_ERROR) {
1265 return ret;
1266 }
1267 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001268 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1269 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001270 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001271 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001272 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001273 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001274 return BAD_VALUE;
1275 }
Eric Laurentc722f302014-12-10 11:21:49 -08001276 if (policyMix != NULL) {
1277 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001278 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1279 // there is an external policy, but this input is attached to a mix of recorders,
1280 // meaning it receives audio injected into the framework, so the recorder doesn't
1281 // know about it and is therefore considered "legacy"
1282 *inputType = API_INPUT_LEGACY;
1283 } else {
1284 // recording a mix of players defined by an external policy, we're rerouting for
1285 // an external policy
1286 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1287 }
Eric Laurentc722f302014-12-10 11:21:49 -08001288 } else if (audio_is_remote_submix_device(device)) {
1289 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001290 *inputType = API_INPUT_MIX_CAPTURE;
1291 } else {
1292 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001293 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001294 // adapt channel selection to input source
Eric Laurentc447ded2015-01-06 08:47:05 -08001295 switch (inputSource) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001296 case AUDIO_SOURCE_VOICE_UPLINK:
1297 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1298 break;
1299 case AUDIO_SOURCE_VOICE_DOWNLINK:
1300 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1301 break;
1302 case AUDIO_SOURCE_VOICE_CALL:
1303 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1304 break;
1305 default:
1306 break;
1307 }
Eric Laurentc447ded2015-01-06 08:47:05 -08001308 if (inputSource == AUDIO_SOURCE_HOTWORD) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001309 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1310 if (index >= 0) {
1311 *input = mSoundTriggerSessions.valueFor(session);
1312 isSoundTrigger = true;
1313 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1314 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1315 } else {
1316 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1317 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001318 }
1319 }
1320
Andy Hungf129b032015-04-07 13:45:50 -07001321 // find a compatible input profile (not necessarily identical in parameters)
1322 sp<IOProfile> profile;
1323 // samplingRate and flags may be updated by getInputProfile
1324 uint32_t profileSamplingRate = samplingRate;
1325 audio_format_t profileFormat = format;
1326 audio_channel_mask_t profileChannelMask = channelMask;
1327 audio_input_flags_t profileFlags = flags;
1328 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001329 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001330 profileSamplingRate, profileFormat, profileChannelMask,
1331 profileFlags);
1332 if (profile != 0) {
1333 break; // success
1334 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1335 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1336 } else { // fail
Eric Laurentcaf7f482014-11-25 17:50:47 -08001337 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1338 "format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001339 device, samplingRate, format, channelMask, flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001340 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001341 }
Eric Laurente552edb2014-03-10 17:42:56 -07001342 }
1343
Eric Laurent322b4d22015-04-03 15:57:54 -07001344 if (profile->getModuleHandle() == 0) {
1345 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurentcaf7f482014-11-25 17:50:47 -08001346 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001347 }
1348
1349 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001350 config.sample_rate = profileSamplingRate;
1351 config.channel_mask = profileChannelMask;
1352 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001353
Eric Laurent322b4d22015-04-03 15:57:54 -07001354 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcaf7f482014-11-25 17:50:47 -08001355 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001356 &config,
1357 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001358 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001359 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001360 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001361
1362 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001363 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001364 (profileSamplingRate != config.sample_rate) ||
1365 (profileFormat != config.format) ||
1366 (profileChannelMask != config.channel_mask)) {
1367 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d,"
1368 " channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001369 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001370 if (*input != AUDIO_IO_HANDLE_NONE) {
1371 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001372 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001373 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001374 }
1375
Eric Laurent1f2f2232014-06-02 12:01:23 -07001376 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentc447ded2015-01-06 08:47:05 -08001377 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001378 inputDesc->mRefCount = 0;
1379 inputDesc->mOpenRefCount = 1;
Andy Hungf129b032015-04-07 13:45:50 -07001380 inputDesc->mSamplingRate = profileSamplingRate;
1381 inputDesc->mFormat = profileFormat;
1382 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001383 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001384 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001385 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001386 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001387
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001388 ALOGV("getInputForAttr() returns input type = %d", *inputType);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001389
Eric Laurentcaf7f482014-11-25 17:50:47 -08001390 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001391 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001392
Eric Laurentcaf7f482014-11-25 17:50:47 -08001393 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001394}
1395
Eric Laurent4dc68062014-07-28 17:26:49 -07001396status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1397 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001398{
1399 ALOGV("startInput() input %d", input);
1400 ssize_t index = mInputs.indexOfKey(input);
1401 if (index < 0) {
1402 ALOGW("startInput() unknown input %d", input);
1403 return BAD_VALUE;
1404 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001405 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001406
Eric Laurentc722f302014-12-10 11:21:49 -08001407 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001408 if (index < 0) {
1409 ALOGW("startInput() unknown session %d on input %d", session, input);
1410 return BAD_VALUE;
1411 }
1412
Glenn Kasten74a8e252014-07-24 14:09:55 -07001413 // virtual input devices are compatible with other input devices
François Gaffie53615e22015-03-19 09:24:12 +01001414 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001415
1416 // for a non-virtual input device, check if there is another (non-virtual) active input
François Gaffie53615e22015-03-19 09:24:12 +01001417 audio_io_handle_t activeInput = mInputs.getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001418 if (activeInput != 0 && activeInput != input) {
1419
1420 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1421 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001423 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001424 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001425 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1426 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001427 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001428 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001429 return INVALID_OPERATION;
1430 }
1431 }
1432 }
1433
Paul McLean466dc8e2015-04-17 13:15:36 -06001434 if (inputDesc->mRefCount == 0 || mInputRoutes.hasRouteChanged(session)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001435 // if input maps to a dynamic policy with an activity listener, notify of state change
1436 if ((inputDesc->mPolicyMix != NULL)
1437 && ((inputDesc->mPolicyMix->mFlags & MIX_FLAG_NOTIFY_ACTIVITY) != 0)) {
1438 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1439 MIX_STATE_MIXING);
1440 }
1441
Paul McLean466dc8e2015-04-17 13:15:36 -06001442 // Routing?
1443 mInputRoutes.incRouteActivity(session);
1444
François Gaffie53615e22015-03-19 09:24:12 +01001445 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001446 SoundTrigger::setCaptureState(true);
1447 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001448 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001449
Eric Laurentc722f302014-12-10 11:21:49 -08001450 // automatically enable the remote submix output when input is started if not
1451 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001452 // For remote submix (a virtual device), we open only one input per capture request.
1453 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001454 String8 address = String8("");
1455 if (inputDesc->mPolicyMix == NULL) {
1456 address = String8("0");
1457 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1458 address = inputDesc->mPolicyMix->mRegistrationId;
1459 }
1460 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001461 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001462 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001463 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001464 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001465 }
Eric Laurente552edb2014-03-10 17:42:56 -07001466 }
1467
Eric Laurente552edb2014-03-10 17:42:56 -07001468 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1469
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001470 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001471 return NO_ERROR;
1472}
1473
Eric Laurent4dc68062014-07-28 17:26:49 -07001474status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1475 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001476{
1477 ALOGV("stopInput() input %d", input);
1478 ssize_t index = mInputs.indexOfKey(input);
1479 if (index < 0) {
1480 ALOGW("stopInput() unknown input %d", input);
1481 return BAD_VALUE;
1482 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001483 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001484
Eric Laurentc722f302014-12-10 11:21:49 -08001485 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001486 if (index < 0) {
1487 ALOGW("stopInput() unknown session %d on input %d", session, input);
1488 return BAD_VALUE;
1489 }
1490
Eric Laurente552edb2014-03-10 17:42:56 -07001491 if (inputDesc->mRefCount == 0) {
1492 ALOGW("stopInput() input %d already stopped", input);
1493 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001494 }
1495
1496 inputDesc->mRefCount--;
Paul McLean466dc8e2015-04-17 13:15:36 -06001497
1498 // Routing?
1499 mInputRoutes.decRouteActivity(session);
1500
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001501 if (inputDesc->mRefCount == 0) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001502 // if input maps to a dynamic policy with an activity listener, notify of state change
1503 if ((inputDesc->mPolicyMix != NULL)
1504 && ((inputDesc->mPolicyMix->mFlags & MIX_FLAG_NOTIFY_ACTIVITY) != 0)) {
1505 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1506 MIX_STATE_IDLE);
1507 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001508
Eric Laurentc722f302014-12-10 11:21:49 -08001509 // automatically disable the remote submix output when input is stopped if not
1510 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001511 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001512 String8 address = String8("");
1513 if (inputDesc->mPolicyMix == NULL) {
1514 address = String8("0");
1515 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1516 address = inputDesc->mPolicyMix->mRegistrationId;
1517 }
1518 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001519 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001520 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001521 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001522 }
Eric Laurente552edb2014-03-10 17:42:56 -07001523 }
1524
Eric Laurent1c333e22014-05-20 10:48:17 -07001525 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001526
François Gaffie53615e22015-03-19 09:24:12 +01001527 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001528 SoundTrigger::setCaptureState(false);
1529 }
Eric Laurente552edb2014-03-10 17:42:56 -07001530 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001531 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001532}
1533
Eric Laurent4dc68062014-07-28 17:26:49 -07001534void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1535 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001536{
1537 ALOGV("releaseInput() %d", input);
1538 ssize_t index = mInputs.indexOfKey(input);
1539 if (index < 0) {
1540 ALOGW("releaseInput() releasing unknown input %d", input);
1541 return;
1542 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001543
1544 // Routing
1545 mInputRoutes.removeRoute(session);
1546
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001547 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1548 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001549
Eric Laurentc722f302014-12-10 11:21:49 -08001550 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001551 if (index < 0) {
1552 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1553 return;
1554 }
Eric Laurentc722f302014-12-10 11:21:49 -08001555 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001556 if (inputDesc->mOpenRefCount == 0) {
1557 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1558 return;
1559 }
1560 inputDesc->mOpenRefCount--;
1561 if (inputDesc->mOpenRefCount > 0) {
1562 ALOGV("releaseInput() exit > 0");
1563 return;
1564 }
1565
Eric Laurent05b90f82014-08-27 15:32:29 -07001566 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001567 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001568 ALOGV("releaseInput() exit");
1569}
1570
Eric Laurentd4692962014-05-05 18:13:44 -07001571void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001572 bool patchRemoved = false;
1573
Eric Laurentd4692962014-05-05 18:13:44 -07001574 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001575 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1576 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1577 if (patch_index >= 0) {
1578 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1579 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1580 mAudioPatches.removeItemsAt(patch_index);
1581 patchRemoved = true;
1582 }
Eric Laurentd4692962014-05-05 18:13:44 -07001583 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1584 }
1585 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001586 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001587
1588 if (patchRemoved) {
1589 mpClientInterface->onAudioPatchListUpdate();
1590 }
Eric Laurentd4692962014-05-05 18:13:44 -07001591}
1592
Eric Laurente0720872014-03-11 09:30:41 -07001593void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001594 int indexMin,
1595 int indexMax)
1596{
1597 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffie2110e042015-03-24 08:41:51 +01001598 mEngine->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001599 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1600 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffie2110e042015-03-24 08:41:51 +01001601 mEngine->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001602 }
Eric Laurente552edb2014-03-10 17:42:56 -07001603}
1604
Eric Laurente0720872014-03-11 09:30:41 -07001605status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001606 int index,
1607 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001608{
1609
Eric Laurentc75307b2015-03-17 15:29:32 -07001610 if ((index < mStreams.valueFor(stream).getVolumeIndexMin()) ||
1611 (index > mStreams.valueFor(stream).getVolumeIndexMax())) {
Eric Laurente552edb2014-03-10 17:42:56 -07001612 return BAD_VALUE;
1613 }
1614 if (!audio_is_output_device(device)) {
1615 return BAD_VALUE;
1616 }
1617
1618 // Force max volume if stream cannot be muted
Eric Laurentc75307b2015-03-17 15:29:32 -07001619 if (!mStreams.canBeMuted(stream)) index = mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07001620
1621 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1622 stream, device, index);
1623
1624 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1625 // clear all device specific values
1626 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
François Gaffiedfd74092015-03-19 12:10:59 +01001627 mStreams.clearCurrentVolumeIndex(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001628 }
François Gaffiedfd74092015-03-19 12:10:59 +01001629 mStreams.addCurrentVolumeIndex(stream, device, index);
Eric Laurente552edb2014-03-10 17:42:56 -07001630
Eric Laurent31551f82014-10-10 18:21:56 -07001631 // update volume on all outputs whose current device is also selected by the same
1632 // strategy as the device specified by the caller
1633 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001634
1635
1636 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1637 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1638 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffiedfd74092015-03-19 12:10:59 +01001639 mStreams.addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001640 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1641 }
1642 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1643 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001644 return NO_ERROR;
1645 }
Eric Laurente552edb2014-03-10 17:42:56 -07001646 status_t status = NO_ERROR;
1647 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001648 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1649 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001650 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001651 status_t volStatus = checkAndSetVolume(stream, index, desc, curDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07001652 if (volStatus != NO_ERROR) {
1653 status = volStatus;
1654 }
1655 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001656 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1657 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
Eric Laurentc75307b2015-03-17 15:29:32 -07001658 index, desc, curDevice);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001659 }
Eric Laurente552edb2014-03-10 17:42:56 -07001660 }
1661 return status;
1662}
1663
Eric Laurente0720872014-03-11 09:30:41 -07001664status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001665 int *index,
1666 audio_devices_t device)
1667{
1668 if (index == NULL) {
1669 return BAD_VALUE;
1670 }
1671 if (!audio_is_output_device(device)) {
1672 return BAD_VALUE;
1673 }
1674 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1675 // the strategy the stream belongs to.
1676 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1677 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1678 }
François Gaffiedfd74092015-03-19 12:10:59 +01001679 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001680
Eric Laurentc75307b2015-03-17 15:29:32 -07001681 *index = mStreams.valueFor(stream).getVolumeIndex(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001682 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1683 return NO_ERROR;
1684}
1685
Eric Laurente0720872014-03-11 09:30:41 -07001686audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001687 const SortedVector<audio_io_handle_t>& outputs)
1688{
1689 // select one output among several suitable for global effects.
1690 // The priority is as follows:
1691 // 1: An offloaded output. If the effect ends up not being offloadable,
1692 // AudioFlinger will invalidate the track and the offloaded output
1693 // will be closed causing the effect to be moved to a PCM output.
1694 // 2: A deep buffer output
1695 // 3: the first output in the list
1696
1697 if (outputs.size() == 0) {
1698 return 0;
1699 }
1700
1701 audio_io_handle_t outputOffloaded = 0;
1702 audio_io_handle_t outputDeepBuffer = 0;
1703
1704 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001705 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001706 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001707 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1708 outputOffloaded = outputs[i];
1709 }
1710 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1711 outputDeepBuffer = outputs[i];
1712 }
1713 }
1714
1715 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1716 outputOffloaded, outputDeepBuffer);
1717 if (outputOffloaded != 0) {
1718 return outputOffloaded;
1719 }
1720 if (outputDeepBuffer != 0) {
1721 return outputDeepBuffer;
1722 }
1723
1724 return outputs[0];
1725}
1726
Eric Laurente0720872014-03-11 09:30:41 -07001727audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001728{
1729 // apply simple rule where global effects are attached to the same output as MUSIC streams
1730
Eric Laurent3b73df72014-03-11 09:06:29 -07001731 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001732 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1733 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1734
1735 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1736 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1737 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1738
1739 return output;
1740}
1741
Eric Laurente0720872014-03-11 09:30:41 -07001742status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001743 audio_io_handle_t io,
1744 uint32_t strategy,
1745 int session,
1746 int id)
1747{
1748 ssize_t index = mOutputs.indexOfKey(io);
1749 if (index < 0) {
1750 index = mInputs.indexOfKey(io);
1751 if (index < 0) {
1752 ALOGW("registerEffect() unknown io %d", io);
1753 return INVALID_OPERATION;
1754 }
1755 }
François Gaffie45ed3b02015-03-19 10:35:14 +01001756 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07001757}
1758
Eric Laurentc75307b2015-03-17 15:29:32 -07001759bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1760{
1761 return mOutputs.isStreamActive(stream, inPastMs);
1762}
1763
1764bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
1765{
1766 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
1767}
1768
Eric Laurente0720872014-03-11 09:30:41 -07001769bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001770{
1771 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001772 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08001773 if (inputDescriptor->mRefCount == 0) {
1774 continue;
1775 }
1776 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07001777 return true;
1778 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08001779 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
1780 // corresponds to an active capture triggered by a hardware hotword recognition
1781 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
1782 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
1783 // FIXME: we should not assume that the first session is the active one and keep
1784 // activity count per session. Same in startInput().
1785 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
1786 if (index >= 0) {
1787 return true;
1788 }
1789 }
Eric Laurente552edb2014-03-10 17:42:56 -07001790 }
1791 return false;
1792}
1793
Eric Laurent275e8e92014-11-30 15:14:47 -08001794// Register a list of custom mixes with their attributes and format.
1795// When a mix is registered, corresponding input and output profiles are
1796// added to the remote submix hw module. The profile contains only the
1797// parameters (sampling rate, format...) specified by the mix.
1798// The corresponding input remote submix device is also connected.
1799//
1800// When a remote submix device is connected, the address is checked to select the
1801// appropriate profile and the corresponding input or output stream is opened.
1802//
1803// When capture starts, getInputForAttr() will:
1804// - 1 look for a mix matching the address passed in attribtutes tags if any
1805// - 2 if none found, getDeviceForInputSource() will:
1806// - 2.1 look for a mix matching the attributes source
1807// - 2.2 if none found, default to device selection by policy rules
1808// At this time, the corresponding output remote submix device is also connected
1809// and active playback use cases can be transferred to this mix if needed when reconnecting
1810// after AudioTracks are invalidated
1811//
1812// When playback starts, getOutputForAttr() will:
1813// - 1 look for a mix matching the address passed in attribtutes tags if any
1814// - 2 if none found, look for a mix matching the attributes usage
1815// - 3 if none found, default to device and output selection by policy rules.
1816
1817status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
1818{
1819 sp<HwModule> module;
1820 for (size_t i = 0; i < mHwModules.size(); i++) {
1821 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1822 mHwModules[i]->mHandle != 0) {
1823 module = mHwModules[i];
1824 break;
1825 }
1826 }
1827
1828 if (module == 0) {
1829 return INVALID_OPERATION;
1830 }
1831
1832 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
1833
1834 for (size_t i = 0; i < mixes.size(); i++) {
1835 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01001836
1837 if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001838 continue;
1839 }
1840 audio_config_t outputConfig = mixes[i].mFormat;
1841 audio_config_t inputConfig = mixes[i].mFormat;
1842 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
1843 // stereo and let audio flinger do the channel conversion if needed.
1844 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1845 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
1846 module->addOutputProfile(address, &outputConfig,
1847 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
1848 module->addInputProfile(address, &inputConfig,
1849 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01001850
Eric Laurentc722f302014-12-10 11:21:49 -08001851 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001852 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001853 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001854 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001855 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001856 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001857 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001858 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001859 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001860 }
1861 return NO_ERROR;
1862}
1863
1864status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
1865{
1866 sp<HwModule> module;
1867 for (size_t i = 0; i < mHwModules.size(); i++) {
1868 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1869 mHwModules[i]->mHandle != 0) {
1870 module = mHwModules[i];
1871 break;
1872 }
1873 }
1874
1875 if (module == 0) {
1876 return INVALID_OPERATION;
1877 }
1878
1879 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
1880
1881 for (size_t i = 0; i < mixes.size(); i++) {
1882 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01001883
1884 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001885 continue;
1886 }
1887
Eric Laurentc722f302014-12-10 11:21:49 -08001888 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
1889 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
1890 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001891 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001892 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001893 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001894 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001895
1896 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
1897 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
1898 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001899 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08001900 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001901 address.string(), "remote-submix");
Eric Laurent275e8e92014-11-30 15:14:47 -08001902 }
1903 module->removeOutputProfile(address);
1904 module->removeInputProfile(address);
1905 }
1906 return NO_ERROR;
1907}
1908
Eric Laurente552edb2014-03-10 17:42:56 -07001909
Eric Laurente0720872014-03-11 09:30:41 -07001910status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001911{
1912 const size_t SIZE = 256;
1913 char buffer[SIZE];
1914 String8 result;
1915
1916 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1917 result.append(buffer);
1918
Eric Laurentc75307b2015-03-17 15:29:32 -07001919 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001920 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01001921 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07001922 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001923 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01001924 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07001925 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01001926 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07001927 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01001928 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07001929 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01001930 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07001931 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01001932 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07001933 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001934 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01001935 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001936 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01001937 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07001938
François Gaffie53615e22015-03-19 09:24:12 +01001939 mAvailableOutputDevices.dump(fd, String8("output"));
1940 mAvailableInputDevices.dump(fd, String8("input"));
1941 mHwModules.dump(fd);
1942 mOutputs.dump(fd);
1943 mInputs.dump(fd);
François Gaffiedfd74092015-03-19 12:10:59 +01001944 mStreams.dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01001945 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01001946 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07001947
1948 return NO_ERROR;
1949}
1950
1951// This function checks for the parameters which can be offloaded.
1952// This can be enhanced depending on the capability of the DSP and policy
1953// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001954bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001955{
1956 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001957 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001958 offloadInfo.sample_rate, offloadInfo.channel_mask,
1959 offloadInfo.format,
1960 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1961 offloadInfo.has_video);
1962
1963 // Check if offload has been disabled
1964 char propValue[PROPERTY_VALUE_MAX];
1965 if (property_get("audio.offload.disable", propValue, "0")) {
1966 if (atoi(propValue) != 0) {
1967 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1968 return false;
1969 }
1970 }
1971
1972 // Check if stream type is music, then only allow offload as of now.
1973 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1974 {
1975 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1976 return false;
1977 }
1978
1979 //TODO: enable audio offloading with video when ready
1980 if (offloadInfo.has_video)
1981 {
1982 ALOGV("isOffloadSupported: has_video == true, returning false");
1983 return false;
1984 }
1985
1986 //If duration is less than minimum value defined in property, return false
1987 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1988 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1989 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1990 return false;
1991 }
1992 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1993 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1994 return false;
1995 }
1996
1997 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1998 // creating an offloaded track and tearing it down immediately after start when audioflinger
1999 // detects there is an active non offloadable effect.
2000 // FIXME: We should check the audio session here but we do not have it in this context.
2001 // This may prevent offloading in rare situations where effects are left active by apps
2002 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002003 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002004 return false;
2005 }
2006
2007 // See if there is a profile to support this.
2008 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002009 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002010 offloadInfo.sample_rate,
2011 offloadInfo.format,
2012 offloadInfo.channel_mask,
2013 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002014 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2015 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002016}
2017
Eric Laurent6a94d692014-05-20 11:18:06 -07002018status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2019 audio_port_type_t type,
2020 unsigned int *num_ports,
2021 struct audio_port *ports,
2022 unsigned int *generation)
2023{
2024 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2025 generation == NULL) {
2026 return BAD_VALUE;
2027 }
2028 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2029 if (ports == NULL) {
2030 *num_ports = 0;
2031 }
2032
2033 size_t portsWritten = 0;
2034 size_t portsMax = *num_ports;
2035 *num_ports = 0;
2036 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2037 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2038 for (size_t i = 0;
2039 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2040 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2041 }
2042 *num_ports += mAvailableOutputDevices.size();
2043 }
2044 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2045 for (size_t i = 0;
2046 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2047 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2048 }
2049 *num_ports += mAvailableInputDevices.size();
2050 }
2051 }
2052 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2053 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2054 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2055 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2056 }
2057 *num_ports += mInputs.size();
2058 }
2059 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002060 size_t numOutputs = 0;
2061 for (size_t i = 0; i < mOutputs.size(); i++) {
2062 if (!mOutputs[i]->isDuplicated()) {
2063 numOutputs++;
2064 if (portsWritten < portsMax) {
2065 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2066 }
2067 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002068 }
Eric Laurent84c70242014-06-23 08:46:27 -07002069 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002070 }
2071 }
2072 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002073 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002074 return NO_ERROR;
2075}
2076
2077status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2078{
2079 return NO_ERROR;
2080}
2081
Eric Laurent6a94d692014-05-20 11:18:06 -07002082status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2083 audio_patch_handle_t *handle,
2084 uid_t uid)
2085{
2086 ALOGV("createAudioPatch()");
2087
2088 if (handle == NULL || patch == NULL) {
2089 return BAD_VALUE;
2090 }
2091 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2092
Eric Laurent874c42872014-08-08 15:13:39 -07002093 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2094 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2095 return BAD_VALUE;
2096 }
2097 // only one source per audio patch supported for now
2098 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002099 return INVALID_OPERATION;
2100 }
Eric Laurent874c42872014-08-08 15:13:39 -07002101
2102 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002103 return INVALID_OPERATION;
2104 }
Eric Laurent874c42872014-08-08 15:13:39 -07002105 for (size_t i = 0; i < patch->num_sinks; i++) {
2106 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2107 return INVALID_OPERATION;
2108 }
2109 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002110
2111 sp<AudioPatch> patchDesc;
2112 ssize_t index = mAudioPatches.indexOfKey(*handle);
2113
Eric Laurent6a94d692014-05-20 11:18:06 -07002114 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2115 patch->sources[0].role,
2116 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002117#if LOG_NDEBUG == 0
2118 for (size_t i = 0; i < patch->num_sinks; i++) {
2119 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2120 patch->sinks[i].role,
2121 patch->sinks[i].type);
2122 }
2123#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002124
2125 if (index >= 0) {
2126 patchDesc = mAudioPatches.valueAt(index);
2127 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2128 mUidCached, patchDesc->mUid, uid);
2129 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2130 return INVALID_OPERATION;
2131 }
2132 } else {
2133 *handle = 0;
2134 }
2135
2136 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002137 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002138 if (outputDesc == NULL) {
2139 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2140 return BAD_VALUE;
2141 }
Eric Laurent84c70242014-06-23 08:46:27 -07002142 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2143 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002144 if (patchDesc != 0) {
2145 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2146 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2147 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2148 return BAD_VALUE;
2149 }
2150 }
Eric Laurent874c42872014-08-08 15:13:39 -07002151 DeviceVector devices;
2152 for (size_t i = 0; i < patch->num_sinks; i++) {
2153 // Only support mix to devices connection
2154 // TODO add support for mix to mix connection
2155 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2156 ALOGV("createAudioPatch() source mix but sink is not a device");
2157 return INVALID_OPERATION;
2158 }
2159 sp<DeviceDescriptor> devDesc =
2160 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2161 if (devDesc == 0) {
2162 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2163 return BAD_VALUE;
2164 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002165
François Gaffie53615e22015-03-19 09:24:12 +01002166 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002167 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002168 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002169 NULL, // updatedSamplingRate
2170 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002171 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002172 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002173 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002174 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002175 ALOGV("createAudioPatch() profile not supported for device %08x",
2176 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002177 return INVALID_OPERATION;
2178 }
2179 devices.add(devDesc);
2180 }
2181 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002182 return INVALID_OPERATION;
2183 }
Eric Laurent874c42872014-08-08 15:13:39 -07002184
Eric Laurent6a94d692014-05-20 11:18:06 -07002185 // TODO: reconfigure output format and channels here
2186 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002187 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002188 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002189 index = mAudioPatches.indexOfKey(*handle);
2190 if (index >= 0) {
2191 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2192 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2193 }
2194 patchDesc = mAudioPatches.valueAt(index);
2195 patchDesc->mUid = uid;
2196 ALOGV("createAudioPatch() success");
2197 } else {
2198 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2199 return INVALID_OPERATION;
2200 }
2201 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2202 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2203 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002204 // only one sink supported when connecting an input device to a mix
2205 if (patch->num_sinks > 1) {
2206 return INVALID_OPERATION;
2207 }
François Gaffie53615e22015-03-19 09:24:12 +01002208 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002209 if (inputDesc == NULL) {
2210 return BAD_VALUE;
2211 }
2212 if (patchDesc != 0) {
2213 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2214 return BAD_VALUE;
2215 }
2216 }
2217 sp<DeviceDescriptor> devDesc =
2218 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2219 if (devDesc == 0) {
2220 return BAD_VALUE;
2221 }
2222
François Gaffie53615e22015-03-19 09:24:12 +01002223 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002224 devDesc->mAddress,
2225 patch->sinks[0].sample_rate,
2226 NULL, /*updatedSampleRate*/
2227 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002228 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002229 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002230 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002231 // FIXME for the parameter type,
2232 // and the NONE
2233 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002234 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002235 return INVALID_OPERATION;
2236 }
2237 // TODO: reconfigure output format and channels here
2238 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002239 devDesc->type(), inputDesc->mIoHandle);
2240 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002241 index = mAudioPatches.indexOfKey(*handle);
2242 if (index >= 0) {
2243 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2244 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2245 }
2246 patchDesc = mAudioPatches.valueAt(index);
2247 patchDesc->mUid = uid;
2248 ALOGV("createAudioPatch() success");
2249 } else {
2250 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2251 return INVALID_OPERATION;
2252 }
2253 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2254 // device to device connection
2255 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002256 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002257 return BAD_VALUE;
2258 }
2259 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002260 sp<DeviceDescriptor> srcDeviceDesc =
2261 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002262 if (srcDeviceDesc == 0) {
2263 return BAD_VALUE;
2264 }
Eric Laurent874c42872014-08-08 15:13:39 -07002265
Eric Laurent6a94d692014-05-20 11:18:06 -07002266 //update source and sink with our own data as the data passed in the patch may
2267 // be incomplete.
2268 struct audio_patch newPatch = *patch;
2269 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002270
Eric Laurent874c42872014-08-08 15:13:39 -07002271 for (size_t i = 0; i < patch->num_sinks; i++) {
2272 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2273 ALOGV("createAudioPatch() source device but one sink is not a device");
2274 return INVALID_OPERATION;
2275 }
2276
2277 sp<DeviceDescriptor> sinkDeviceDesc =
2278 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2279 if (sinkDeviceDesc == 0) {
2280 return BAD_VALUE;
2281 }
2282 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2283
Eric Laurent3bcf8592015-04-03 12:13:24 -07002284 // create a software bridge in PatchPanel if:
2285 // - source and sink devices are on differnt HW modules OR
2286 // - audio HAL version is < 3.0
2287 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
2288 (srcDeviceDesc->mModule->mHalVersion < AUDIO_DEVICE_API_VERSION_3_0)) {
2289 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002290 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002291 return INVALID_OPERATION;
2292 }
Eric Laurent874c42872014-08-08 15:13:39 -07002293 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002294 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002295 // if the sink device is reachable via an opened output stream, request to go via
2296 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002297 audio_io_handle_t output = selectOutput(outputs,
2298 AUDIO_OUTPUT_FLAG_NONE,
2299 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002300 if (output != AUDIO_IO_HANDLE_NONE) {
2301 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2302 if (outputDesc->isDuplicated()) {
2303 return INVALID_OPERATION;
2304 }
2305 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002306 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002307 newPatch.num_sources = 2;
2308 }
Eric Laurent83b88082014-06-20 18:31:16 -07002309 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002310 }
2311 // TODO: check from routing capabilities in config file and other conflicting patches
2312
2313 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2314 if (index >= 0) {
2315 afPatchHandle = patchDesc->mAfPatchHandle;
2316 }
2317
2318 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2319 &afPatchHandle,
2320 0);
2321 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2322 status, afPatchHandle);
2323 if (status == NO_ERROR) {
2324 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002325 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002326 addAudioPatch(patchDesc->mHandle, patchDesc);
2327 } else {
2328 patchDesc->mPatch = newPatch;
2329 }
2330 patchDesc->mAfPatchHandle = afPatchHandle;
2331 *handle = patchDesc->mHandle;
2332 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002333 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002334 } else {
2335 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2336 status);
2337 return INVALID_OPERATION;
2338 }
2339 } else {
2340 return BAD_VALUE;
2341 }
2342 } else {
2343 return BAD_VALUE;
2344 }
2345 return NO_ERROR;
2346}
2347
2348status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2349 uid_t uid)
2350{
2351 ALOGV("releaseAudioPatch() patch %d", handle);
2352
2353 ssize_t index = mAudioPatches.indexOfKey(handle);
2354
2355 if (index < 0) {
2356 return BAD_VALUE;
2357 }
2358 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2359 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2360 mUidCached, patchDesc->mUid, uid);
2361 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2362 return INVALID_OPERATION;
2363 }
2364
2365 struct audio_patch *patch = &patchDesc->mPatch;
2366 patchDesc->mUid = mUidCached;
2367 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002368 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002369 if (outputDesc == NULL) {
2370 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2371 return BAD_VALUE;
2372 }
2373
Eric Laurentc75307b2015-03-17 15:29:32 -07002374 setOutputDevice(outputDesc,
2375 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002376 true,
2377 0,
2378 NULL);
2379 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2380 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002381 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002382 if (inputDesc == NULL) {
2383 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2384 return BAD_VALUE;
2385 }
2386 setInputDevice(inputDesc->mIoHandle,
2387 getNewInputDevice(inputDesc->mIoHandle),
2388 true,
2389 NULL);
2390 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2391 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2392 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2393 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2394 status, patchDesc->mAfPatchHandle);
2395 removeAudioPatch(patchDesc->mHandle);
2396 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002397 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002398 } else {
2399 return BAD_VALUE;
2400 }
2401 } else {
2402 return BAD_VALUE;
2403 }
2404 return NO_ERROR;
2405}
2406
2407status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2408 struct audio_patch *patches,
2409 unsigned int *generation)
2410{
François Gaffie53615e22015-03-19 09:24:12 +01002411 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002412 return BAD_VALUE;
2413 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002414 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002415 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002416}
2417
Eric Laurente1715a42014-05-20 11:30:42 -07002418status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002419{
Eric Laurente1715a42014-05-20 11:30:42 -07002420 ALOGV("setAudioPortConfig()");
2421
2422 if (config == NULL) {
2423 return BAD_VALUE;
2424 }
2425 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2426 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002427 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2428 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002429 }
2430
Eric Laurenta121f902014-06-03 13:32:54 -07002431 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002432 if (config->type == AUDIO_PORT_TYPE_MIX) {
2433 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002434 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002435 if (outputDesc == NULL) {
2436 return BAD_VALUE;
2437 }
Eric Laurent84c70242014-06-23 08:46:27 -07002438 ALOG_ASSERT(!outputDesc->isDuplicated(),
2439 "setAudioPortConfig() called on duplicated output %d",
2440 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002441 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002442 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002443 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002444 if (inputDesc == NULL) {
2445 return BAD_VALUE;
2446 }
Eric Laurenta121f902014-06-03 13:32:54 -07002447 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002448 } else {
2449 return BAD_VALUE;
2450 }
2451 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2452 sp<DeviceDescriptor> deviceDesc;
2453 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2454 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2455 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2456 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2457 } else {
2458 return BAD_VALUE;
2459 }
2460 if (deviceDesc == NULL) {
2461 return BAD_VALUE;
2462 }
Eric Laurenta121f902014-06-03 13:32:54 -07002463 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002464 } else {
2465 return BAD_VALUE;
2466 }
2467
Eric Laurenta121f902014-06-03 13:32:54 -07002468 struct audio_port_config backupConfig;
2469 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2470 if (status == NO_ERROR) {
2471 struct audio_port_config newConfig;
2472 audioPortConfig->toAudioPortConfig(&newConfig, config);
2473 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002474 }
Eric Laurenta121f902014-06-03 13:32:54 -07002475 if (status != NO_ERROR) {
2476 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002477 }
Eric Laurente1715a42014-05-20 11:30:42 -07002478
2479 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002480}
2481
2482void AudioPolicyManager::clearAudioPatches(uid_t uid)
2483{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002484 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002485 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2486 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002487 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002488 }
2489 }
2490}
2491
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002492status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2493 audio_io_handle_t *ioHandle,
2494 audio_devices_t *device)
2495{
2496 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2497 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002498 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002499
François Gaffiedf372692015-03-19 10:43:27 +01002500 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002501}
2502
Eric Laurent493404d2015-04-21 15:07:36 -07002503status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source __unused,
2504 const audio_attributes_t *attributes __unused,
2505 audio_io_handle_t *handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07002506{
2507 return INVALID_OPERATION;
2508}
2509
Eric Laurent493404d2015-04-21 15:07:36 -07002510status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07002511{
2512 return INVALID_OPERATION;
2513}
2514
Eric Laurente552edb2014-03-10 17:42:56 -07002515// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002516// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002517// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07002518uint32_t AudioPolicyManager::nextAudioPortGeneration()
2519{
2520 return android_atomic_inc(&mAudioPortGeneration);
2521}
2522
Eric Laurente0720872014-03-11 09:30:41 -07002523AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002524 :
2525#ifdef AUDIO_POLICY_TEST
2526 Thread(false),
2527#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07002528 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002529 mA2dpSuspended(false),
Paul McLeane743a472015-01-28 11:07:31 -08002530 mSpeakerDrcEnabled(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002531 mAudioPortGeneration(1),
2532 mBeaconMuteRefCount(0),
2533 mBeaconPlayingRefCount(0),
2534 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002535{
François Gaffie2110e042015-03-24 08:41:51 +01002536 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
2537 if (!engineInstance) {
2538 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
2539 return;
2540 }
2541 // Retrieve the Policy Manager Interface
2542 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
2543 if (mEngine == NULL) {
2544 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
2545 return;
2546 }
2547 mEngine->setObserver(this);
2548 status_t status = mEngine->initCheck();
2549 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
2550
Eric Laurent6a94d692014-05-20 11:18:06 -07002551 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002552 mpClientInterface = clientInterface;
2553
Paul McLeane743a472015-01-28 11:07:31 -08002554 mDefaultOutputDevice = new DeviceDescriptor(String8("Speaker"), AUDIO_DEVICE_OUT_SPEAKER);
François Gaffie53615e22015-03-19 09:24:12 +01002555 if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE,
2556 mHwModules, mAvailableInputDevices, mAvailableOutputDevices,
2557 mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) {
2558 if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE,
2559 mHwModules, mAvailableInputDevices, mAvailableOutputDevices,
2560 mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07002561 ALOGE("could not load audio policy configuration file, setting defaults");
2562 defaultAudioPolicyConfig();
2563 }
2564 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002565 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002566
François Gaffie2110e042015-03-24 08:41:51 +01002567 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
2568 mEngine->initializeVolumeCurves(mSpeakerDrcEnabled);
Eric Laurente552edb2014-03-10 17:42:56 -07002569
2570 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002571 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2572 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002573 for (size_t i = 0; i < mHwModules.size(); i++) {
2574 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2575 if (mHwModules[i]->mHandle == 0) {
2576 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2577 continue;
2578 }
2579 // open all output streams needed to access attached devices
2580 // except for direct output streams that are only opened when they are actually
2581 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002582 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002583 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2584 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002585 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002586
Eric Laurent3a4311c2014-03-17 12:00:47 -07002587 if (outProfile->mSupportedDevices.isEmpty()) {
2588 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2589 continue;
2590 }
2591
Eric Laurentd78f1532014-09-16 16:38:20 -07002592 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2593 continue;
2594 }
Eric Laurent83b88082014-06-20 18:31:16 -07002595 audio_devices_t profileType = outProfile->mSupportedDevices.types();
François Gaffie53615e22015-03-19 09:24:12 +01002596 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
2597 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07002598 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002599 // chose first device present in mSupportedDevices also part of
2600 // outputDeviceTypes
2601 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
François Gaffie53615e22015-03-19 09:24:12 +01002602 profileType = outProfile->mSupportedDevices[k]->type();
Eric Laurentd78f1532014-09-16 16:38:20 -07002603 if ((profileType & outputDeviceTypes) != 0) {
2604 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002605 }
Eric Laurente552edb2014-03-10 17:42:56 -07002606 }
2607 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002608 if ((profileType & outputDeviceTypes) == 0) {
2609 continue;
2610 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002611 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
2612 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07002613
2614 outputDesc->mDevice = profileType;
2615 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2616 config.sample_rate = outputDesc->mSamplingRate;
2617 config.channel_mask = outputDesc->mChannelMask;
2618 config.format = outputDesc->mFormat;
2619 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07002620 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07002621 &output,
2622 &config,
2623 &outputDesc->mDevice,
2624 String8(""),
2625 &outputDesc->mLatency,
2626 outputDesc->mFlags);
2627
2628 if (status != NO_ERROR) {
2629 ALOGW("Cannot open output stream for device %08x on hw module %s",
2630 outputDesc->mDevice,
2631 mHwModules[i]->mName);
2632 } else {
2633 outputDesc->mSamplingRate = config.sample_rate;
2634 outputDesc->mChannelMask = config.channel_mask;
2635 outputDesc->mFormat = config.format;
2636
2637 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
François Gaffie53615e22015-03-19 09:24:12 +01002638 audio_devices_t type = outProfile->mSupportedDevices[k]->type();
Eric Laurentd78f1532014-09-16 16:38:20 -07002639 ssize_t index =
2640 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2641 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08002642 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
2643 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07002644 }
2645 }
2646 if (mPrimaryOutput == 0 &&
2647 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002648 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07002649 }
2650 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07002651 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07002652 outputDesc->mDevice,
2653 true);
2654 }
Eric Laurente552edb2014-03-10 17:42:56 -07002655 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002656 // open input streams needed to access attached devices to validate
2657 // mAvailableInputDevices list
2658 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2659 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002660 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002661
Eric Laurent3a4311c2014-03-17 12:00:47 -07002662 if (inProfile->mSupportedDevices.isEmpty()) {
2663 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2664 continue;
2665 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002666 // chose first device present in mSupportedDevices also part of
2667 // inputDeviceTypes
2668 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2669 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
François Gaffie53615e22015-03-19 09:24:12 +01002670 profileType = inProfile->mSupportedDevices[k]->type();
Eric Laurentd78f1532014-09-16 16:38:20 -07002671 if (profileType & inputDeviceTypes) {
2672 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002673 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002674 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002675 if ((profileType & inputDeviceTypes) == 0) {
2676 continue;
2677 }
2678 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2679
2680 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2681 inputDesc->mDevice = profileType;
2682
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002683 // find the address
2684 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2685 // the inputs vector must be of size 1, but we don't want to crash here
2686 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2687 : String8("");
2688 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
2689 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2690
Eric Laurentd78f1532014-09-16 16:38:20 -07002691 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2692 config.sample_rate = inputDesc->mSamplingRate;
2693 config.channel_mask = inputDesc->mChannelMask;
2694 config.format = inputDesc->mFormat;
2695 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07002696 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07002697 &input,
2698 &config,
2699 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002700 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07002701 AUDIO_SOURCE_MIC,
2702 AUDIO_INPUT_FLAG_NONE);
2703
2704 if (status == NO_ERROR) {
2705 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
François Gaffie53615e22015-03-19 09:24:12 +01002706 audio_devices_t type = inProfile->mSupportedDevices[k]->type();
Eric Laurentd78f1532014-09-16 16:38:20 -07002707 ssize_t index =
2708 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2709 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08002710 if (index >= 0 && !mAvailableInputDevices[index]->isAttached()) {
2711 mAvailableInputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07002712 }
2713 }
2714 mpClientInterface->closeInput(input);
2715 } else {
2716 ALOGW("Cannot open input stream for device %08x on hw module %s",
2717 inputDesc->mDevice,
2718 mHwModules[i]->mName);
2719 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002720 }
2721 }
2722 // make sure all attached devices have been allocated a unique ID
2723 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08002724 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01002725 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002726 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2727 continue;
2728 }
François Gaffie2110e042015-03-24 08:41:51 +01002729 // The device is now validated and can be appended to the available devices of the engine
2730 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
2731 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002732 i++;
2733 }
2734 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08002735 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01002736 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002737 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2738 continue;
2739 }
François Gaffie2110e042015-03-24 08:41:51 +01002740 // The device is now validated and can be appended to the available devices of the engine
2741 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
2742 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002743 i++;
2744 }
2745 // make sure default device is reachable
2746 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01002747 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002748 }
Eric Laurente552edb2014-03-10 17:42:56 -07002749
2750 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2751
2752 updateDevicesAndOutputs();
2753
2754#ifdef AUDIO_POLICY_TEST
2755 if (mPrimaryOutput != 0) {
2756 AudioParameter outputCmd = AudioParameter();
2757 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07002758 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07002759
2760 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2761 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002762 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2763 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002764 mTestLatencyMs = 0;
2765 mCurOutput = 0;
2766 mDirectOutput = false;
2767 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2768 mTestOutputs[i] = 0;
2769 }
2770
2771 const size_t SIZE = 256;
2772 char buffer[SIZE];
2773 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2774 run(buffer, ANDROID_PRIORITY_AUDIO);
2775 }
2776#endif //AUDIO_POLICY_TEST
2777}
2778
Eric Laurente0720872014-03-11 09:30:41 -07002779AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002780{
2781#ifdef AUDIO_POLICY_TEST
2782 exit();
2783#endif //AUDIO_POLICY_TEST
2784 for (size_t i = 0; i < mOutputs.size(); i++) {
2785 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002786 }
2787 for (size_t i = 0; i < mInputs.size(); i++) {
2788 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002789 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002790 mAvailableOutputDevices.clear();
2791 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002792 mOutputs.clear();
2793 mInputs.clear();
2794 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002795}
2796
Eric Laurente0720872014-03-11 09:30:41 -07002797status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002798{
2799 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2800}
2801
2802#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002803bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002804{
2805 ALOGV("entering threadLoop()");
2806 while (!exitPending())
2807 {
2808 String8 command;
2809 int valueInt;
2810 String8 value;
2811
2812 Mutex::Autolock _l(mLock);
2813 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2814
2815 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2816 AudioParameter param = AudioParameter(command);
2817
2818 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2819 valueInt != 0) {
2820 ALOGV("Test command %s received", command.string());
2821 String8 target;
2822 if (param.get(String8("target"), target) != NO_ERROR) {
2823 target = "Manager";
2824 }
2825 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2826 param.remove(String8("test_cmd_policy_output"));
2827 mCurOutput = valueInt;
2828 }
2829 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2830 param.remove(String8("test_cmd_policy_direct"));
2831 if (value == "false") {
2832 mDirectOutput = false;
2833 } else if (value == "true") {
2834 mDirectOutput = true;
2835 }
2836 }
2837 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2838 param.remove(String8("test_cmd_policy_input"));
2839 mTestInput = valueInt;
2840 }
2841
2842 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2843 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002844 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002845 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002846 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002847 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002848 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002849 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002850 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002851 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002852 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002853 if (target == "Manager") {
2854 mTestFormat = format;
2855 } else if (mTestOutputs[mCurOutput] != 0) {
2856 AudioParameter outputParam = AudioParameter();
2857 outputParam.addInt(String8("format"), format);
2858 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2859 }
2860 }
2861 }
2862 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2863 param.remove(String8("test_cmd_policy_channels"));
2864 int channels = 0;
2865
2866 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002867 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002868 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002869 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002870 }
2871 if (channels != 0) {
2872 if (target == "Manager") {
2873 mTestChannels = channels;
2874 } else if (mTestOutputs[mCurOutput] != 0) {
2875 AudioParameter outputParam = AudioParameter();
2876 outputParam.addInt(String8("channels"), channels);
2877 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2878 }
2879 }
2880 }
2881 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2882 param.remove(String8("test_cmd_policy_sampleRate"));
2883 if (valueInt >= 0 && valueInt <= 96000) {
2884 int samplingRate = valueInt;
2885 if (target == "Manager") {
2886 mTestSamplingRate = samplingRate;
2887 } else if (mTestOutputs[mCurOutput] != 0) {
2888 AudioParameter outputParam = AudioParameter();
2889 outputParam.addInt(String8("sampling_rate"), samplingRate);
2890 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2891 }
2892 }
2893 }
2894
2895 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2896 param.remove(String8("test_cmd_policy_reopen"));
2897
Eric Laurentc75307b2015-03-17 15:29:32 -07002898 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07002899
Eric Laurentc75307b2015-03-17 15:29:32 -07002900 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07002901
Eric Laurentc75307b2015-03-17 15:29:32 -07002902 removeOutput(mPrimaryOutput->mIoHandle);
2903 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
2904 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07002905 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002906 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2907 config.sample_rate = outputDesc->mSamplingRate;
2908 config.channel_mask = outputDesc->mChannelMask;
2909 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07002910 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002911 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07002912 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002913 &config,
2914 &outputDesc->mDevice,
2915 String8(""),
2916 &outputDesc->mLatency,
2917 outputDesc->mFlags);
2918 if (status != NO_ERROR) {
2919 ALOGE("Failed to reopen hardware output stream, "
2920 "samplingRate: %d, format %d, channels %d",
2921 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002922 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002923 outputDesc->mSamplingRate = config.sample_rate;
2924 outputDesc->mChannelMask = config.channel_mask;
2925 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07002926 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07002927 AudioParameter outputCmd = AudioParameter();
2928 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07002929 mpClientInterface->setParameters(handle, outputCmd.toString());
2930 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07002931 }
2932 }
2933
2934
2935 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2936 }
2937 }
2938 return false;
2939}
2940
Eric Laurente0720872014-03-11 09:30:41 -07002941void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002942{
2943 {
2944 AutoMutex _l(mLock);
2945 requestExit();
2946 mWaitWorkCV.signal();
2947 }
2948 requestExitAndWait();
2949}
2950
Eric Laurente0720872014-03-11 09:30:41 -07002951int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002952{
2953 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2954 if (output == mTestOutputs[i]) return i;
2955 }
2956 return 0;
2957}
2958#endif //AUDIO_POLICY_TEST
2959
2960// ---
2961
Eric Laurentc75307b2015-03-17 15:29:32 -07002962void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002963{
François Gaffie98cc1912015-03-18 17:52:40 +01002964 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07002965 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002966 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002967}
2968
François Gaffie53615e22015-03-19 09:24:12 +01002969void AudioPolicyManager::removeOutput(audio_io_handle_t output)
2970{
2971 mOutputs.removeItem(output);
2972}
2973
Eric Laurent1f2f2232014-06-02 12:01:23 -07002974void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002975{
François Gaffie98cc1912015-03-18 17:52:40 +01002976 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07002977 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002978 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002979}
Eric Laurente552edb2014-03-10 17:42:56 -07002980
Eric Laurentc75307b2015-03-17 15:29:32 -07002981void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08002982 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002983 const String8 address /*in*/,
2984 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08002985 sp<DeviceDescriptor> devDesc =
2986 desc->mProfile->mSupportedDevices.getDevice(device, address);
2987 if (devDesc != 0) {
2988 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
2989 desc->mIoHandle, address.string());
2990 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002991 }
2992}
2993
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07002994status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01002995 audio_policy_dev_state_t state,
2996 SortedVector<audio_io_handle_t>& outputs,
2997 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002998{
François Gaffie53615e22015-03-19 09:24:12 +01002999 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003000 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003001 // erase all current sample rates, formats and channel masks
3002 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003003
Eric Laurent3b73df72014-03-11 09:06:29 -07003004 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003005 // first list already open outputs that can be routed to this device
3006 for (size_t i = 0; i < mOutputs.size(); i++) {
3007 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003008 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003009 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003010 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3011 outputs.add(mOutputs.keyAt(i));
3012 } else {
3013 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003014 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003015 }
Eric Laurente552edb2014-03-10 17:42:56 -07003016 }
3017 }
3018 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003019 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003020 for (size_t i = 0; i < mHwModules.size(); i++)
3021 {
3022 if (mHwModules[i]->mHandle == 0) {
3023 continue;
3024 }
3025 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3026 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003027 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3028 if (profile->mSupportedDevices.types() & device) {
François Gaffie53615e22015-03-19 09:24:12 +01003029 if (!device_distinguishes_on_address(device) ||
Eric Laurent275e8e92014-11-30 15:14:47 -08003030 address == profile->mSupportedDevices[0]->mAddress) {
3031 profiles.add(profile);
3032 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3033 }
Eric Laurente552edb2014-03-10 17:42:56 -07003034 }
3035 }
3036 }
3037
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003038 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3039
Eric Laurente552edb2014-03-10 17:42:56 -07003040 if (profiles.isEmpty() && outputs.isEmpty()) {
3041 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3042 return BAD_VALUE;
3043 }
3044
3045 // open outputs for matching profiles if needed. Direct outputs are also opened to
3046 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3047 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003048 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003049
3050 // nothing to do if one output is already opened for this profile
3051 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003052 for (j = 0; j < outputs.size(); j++) {
3053 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003054 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003055 // matching profile: save the sample rates, format and channel masks supported
3056 // by the profile in our device descriptor
3057 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003058 break;
3059 }
3060 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003061 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003062 continue;
3063 }
3064
Eric Laurent83b88082014-06-20 18:31:16 -07003065 ALOGV("opening output for device %08x with params %s profile %p",
3066 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003067 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003068 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003069 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3070 config.sample_rate = desc->mSamplingRate;
3071 config.channel_mask = desc->mChannelMask;
3072 config.format = desc->mFormat;
3073 config.offload_info.sample_rate = desc->mSamplingRate;
3074 config.offload_info.channel_mask = desc->mChannelMask;
3075 config.offload_info.format = desc->mFormat;
3076 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003077 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003078 &output,
3079 &config,
3080 &desc->mDevice,
3081 address,
3082 &desc->mLatency,
3083 desc->mFlags);
3084 if (status == NO_ERROR) {
3085 desc->mSamplingRate = config.sample_rate;
3086 desc->mChannelMask = config.channel_mask;
3087 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003088
Eric Laurentd4692962014-05-05 18:13:44 -07003089 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003090 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003091 char *param = audio_device_address_to_parameter(device, address);
3092 mpClientInterface->setParameters(output, String8(param));
3093 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003094 }
3095
Eric Laurentd4692962014-05-05 18:13:44 -07003096 // Here is where we step through and resolve any "dynamic" fields
3097 String8 reply;
3098 char *value;
3099 if (profile->mSamplingRates[0] == 0) {
3100 reply = mpClientInterface->getParameters(output,
3101 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003102 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003103 reply.string());
3104 value = strpbrk((char *)reply.string(), "=");
3105 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003106 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003107 }
Eric Laurentd4692962014-05-05 18:13:44 -07003108 }
3109 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3110 reply = mpClientInterface->getParameters(output,
3111 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003112 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003113 reply.string());
3114 value = strpbrk((char *)reply.string(), "=");
3115 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003116 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003117 }
Eric Laurentd4692962014-05-05 18:13:44 -07003118 }
3119 if (profile->mChannelMasks[0] == 0) {
3120 reply = mpClientInterface->getParameters(output,
3121 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003122 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003123 reply.string());
3124 value = strpbrk((char *)reply.string(), "=");
3125 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003126 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003127 }
Eric Laurentd4692962014-05-05 18:13:44 -07003128 }
3129 if (((profile->mSamplingRates[0] == 0) &&
3130 (profile->mSamplingRates.size() < 2)) ||
3131 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3132 (profile->mFormats.size() < 2)) ||
3133 ((profile->mChannelMasks[0] == 0) &&
3134 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003135 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003136 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003137 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003138 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3139 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003140 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003141 config.sample_rate = profile->pickSamplingRate();
3142 config.channel_mask = profile->pickChannelMask();
3143 config.format = profile->pickFormat();
3144 config.offload_info.sample_rate = config.sample_rate;
3145 config.offload_info.channel_mask = config.channel_mask;
3146 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003147 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003148 &output,
3149 &config,
3150 &desc->mDevice,
3151 address,
3152 &desc->mLatency,
3153 desc->mFlags);
3154 if (status == NO_ERROR) {
3155 desc->mSamplingRate = config.sample_rate;
3156 desc->mChannelMask = config.channel_mask;
3157 desc->mFormat = config.format;
3158 } else {
3159 output = AUDIO_IO_HANDLE_NONE;
3160 }
Eric Laurentd4692962014-05-05 18:13:44 -07003161 }
3162
Eric Laurentcf2c0212014-07-25 16:20:43 -07003163 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003164 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003165 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003166 sp<AudioPolicyMix> policyMix;
3167 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003168 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3169 address.string());
3170 }
François Gaffie036e1e92015-03-19 10:16:24 +01003171 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003172 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003173
Eric Laurentc722f302014-12-10 11:21:49 -08003174 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3175 // no duplicated output for direct outputs and
3176 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003177 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003178
Eric Laurentd4692962014-05-05 18:13:44 -07003179 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003180 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003181
Eric Laurentd4692962014-05-05 18:13:44 -07003182 //TODO: configure audio effect output stage here
3183
3184 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003185 duplicatedOutput =
3186 mpClientInterface->openDuplicateOutput(output,
3187 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003188 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003189 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003190 sp<SwAudioOutputDescriptor> dupOutputDesc =
3191 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3192 dupOutputDesc->mOutput1 = mPrimaryOutput;
3193 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003194 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3195 dupOutputDesc->mFormat = desc->mFormat;
3196 dupOutputDesc->mChannelMask = desc->mChannelMask;
3197 dupOutputDesc->mLatency = desc->mLatency;
3198 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003199 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003200 } else {
3201 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003202 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003203 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003204 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003205 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003206 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003207 }
Eric Laurente552edb2014-03-10 17:42:56 -07003208 }
3209 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003210 } else {
3211 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003212 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003213 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003214 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003215 profiles.removeAt(profile_index);
3216 profile_index--;
3217 } else {
3218 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003219 devDesc->importAudioPort(profile);
3220
François Gaffie53615e22015-03-19 09:24:12 +01003221 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003222 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3223 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003224 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003225 NULL/*patch handle*/, address.string());
3226 }
Eric Laurente552edb2014-03-10 17:42:56 -07003227 ALOGV("checkOutputsForDevice(): adding output %d", output);
3228 }
3229 }
3230
3231 if (profiles.isEmpty()) {
3232 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3233 return BAD_VALUE;
3234 }
Eric Laurentd4692962014-05-05 18:13:44 -07003235 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003236 // check if one opened output is not needed any more after disconnecting one device
3237 for (size_t i = 0; i < mOutputs.size(); i++) {
3238 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003239 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003240 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003241 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003242 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003243 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003244 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003245 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3246 mOutputs.keyAt(i));
3247 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003248 }
Eric Laurente552edb2014-03-10 17:42:56 -07003249 }
3250 }
Eric Laurentd4692962014-05-05 18:13:44 -07003251 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003252 for (size_t i = 0; i < mHwModules.size(); i++)
3253 {
3254 if (mHwModules[i]->mHandle == 0) {
3255 continue;
3256 }
3257 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3258 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003259 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003260 if (profile->mSupportedDevices.types() & device) {
3261 ALOGV("checkOutputsForDevice(): "
3262 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003263 if (profile->mSamplingRates[0] == 0) {
3264 profile->mSamplingRates.clear();
3265 profile->mSamplingRates.add(0);
3266 }
3267 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3268 profile->mFormats.clear();
3269 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3270 }
3271 if (profile->mChannelMasks[0] == 0) {
3272 profile->mChannelMasks.clear();
3273 profile->mChannelMasks.add(0);
3274 }
3275 }
3276 }
3277 }
3278 }
3279 return NO_ERROR;
3280}
3281
Eric Laurentd4692962014-05-05 18:13:44 -07003282status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01003283 audio_policy_dev_state_t state,
3284 SortedVector<audio_io_handle_t>& inputs,
3285 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003286{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003287 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003288 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3289 // first list already open inputs that can be routed to this device
3290 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3291 desc = mInputs.valueAt(input_index);
3292 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3293 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3294 inputs.add(mInputs.keyAt(input_index));
3295 }
3296 }
3297
3298 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003299 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003300 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3301 {
3302 if (mHwModules[module_idx]->mHandle == 0) {
3303 continue;
3304 }
3305 for (size_t profile_index = 0;
3306 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3307 profile_index++)
3308 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003309 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3310
3311 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
François Gaffie53615e22015-03-19 09:24:12 +01003312 if (!device_distinguishes_on_address(device) ||
Eric Laurent275e8e92014-11-30 15:14:47 -08003313 address == profile->mSupportedDevices[0]->mAddress) {
3314 profiles.add(profile);
3315 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3316 profile_index, module_idx);
3317 }
Eric Laurentd4692962014-05-05 18:13:44 -07003318 }
3319 }
3320 }
3321
3322 if (profiles.isEmpty() && inputs.isEmpty()) {
3323 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3324 return BAD_VALUE;
3325 }
3326
3327 // open inputs for matching profiles if needed. Direct inputs are also opened to
3328 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3329 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3330
Eric Laurent1c333e22014-05-20 10:48:17 -07003331 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003332 // nothing to do if one input is already opened for this profile
3333 size_t input_index;
3334 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3335 desc = mInputs.valueAt(input_index);
3336 if (desc->mProfile == profile) {
3337 break;
3338 }
3339 }
3340 if (input_index != mInputs.size()) {
3341 continue;
3342 }
3343
3344 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3345 desc = new AudioInputDescriptor(profile);
3346 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003347 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3348 config.sample_rate = desc->mSamplingRate;
3349 config.channel_mask = desc->mChannelMask;
3350 config.format = desc->mFormat;
3351 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003352 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003353 &input,
3354 &config,
3355 &desc->mDevice,
3356 address,
3357 AUDIO_SOURCE_MIC,
3358 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003359
Eric Laurentcf2c0212014-07-25 16:20:43 -07003360 if (status == NO_ERROR) {
3361 desc->mSamplingRate = config.sample_rate;
3362 desc->mChannelMask = config.channel_mask;
3363 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003364
Eric Laurentd4692962014-05-05 18:13:44 -07003365 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003366 char *param = audio_device_address_to_parameter(device, address);
3367 mpClientInterface->setParameters(input, String8(param));
3368 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003369 }
3370
3371 // Here is where we step through and resolve any "dynamic" fields
3372 String8 reply;
3373 char *value;
3374 if (profile->mSamplingRates[0] == 0) {
3375 reply = mpClientInterface->getParameters(input,
3376 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3377 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3378 reply.string());
3379 value = strpbrk((char *)reply.string(), "=");
3380 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003381 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003382 }
3383 }
3384 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3385 reply = mpClientInterface->getParameters(input,
3386 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3387 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3388 value = strpbrk((char *)reply.string(), "=");
3389 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003390 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003391 }
3392 }
3393 if (profile->mChannelMasks[0] == 0) {
3394 reply = mpClientInterface->getParameters(input,
3395 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3396 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3397 reply.string());
3398 value = strpbrk((char *)reply.string(), "=");
3399 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003400 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003401 }
3402 }
3403 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3404 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3405 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3406 ALOGW("checkInputsForDevice() direct input missing param");
3407 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003408 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003409 }
3410
3411 if (input != 0) {
3412 addInput(input, desc);
3413 }
3414 } // endif input != 0
3415
Eric Laurentcf2c0212014-07-25 16:20:43 -07003416 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003417 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003418 profiles.removeAt(profile_index);
3419 profile_index--;
3420 } else {
3421 inputs.add(input);
3422 ALOGV("checkInputsForDevice(): adding input %d", input);
3423 }
3424 } // end scan profiles
3425
3426 if (profiles.isEmpty()) {
3427 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3428 return BAD_VALUE;
3429 }
3430 } else {
3431 // Disconnect
3432 // check if one opened input is not needed any more after disconnecting one device
3433 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3434 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003435 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3436 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003437 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3438 mInputs.keyAt(input_index));
3439 inputs.add(mInputs.keyAt(input_index));
3440 }
3441 }
3442 // Clear any profiles associated with the disconnected device.
3443 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3444 if (mHwModules[module_index]->mHandle == 0) {
3445 continue;
3446 }
3447 for (size_t profile_index = 0;
3448 profile_index < mHwModules[module_index]->mInputProfiles.size();
3449 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003450 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003451 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003452 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003453 profile_index, module_index);
3454 if (profile->mSamplingRates[0] == 0) {
3455 profile->mSamplingRates.clear();
3456 profile->mSamplingRates.add(0);
3457 }
3458 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3459 profile->mFormats.clear();
3460 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3461 }
3462 if (profile->mChannelMasks[0] == 0) {
3463 profile->mChannelMasks.clear();
3464 profile->mChannelMasks.add(0);
3465 }
3466 }
3467 }
3468 }
3469 } // end disconnect
3470
3471 return NO_ERROR;
3472}
3473
3474
Eric Laurente0720872014-03-11 09:30:41 -07003475void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003476{
3477 ALOGV("closeOutput(%d)", output);
3478
Eric Laurentc75307b2015-03-17 15:29:32 -07003479 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003480 if (outputDesc == NULL) {
3481 ALOGW("closeOutput() unknown output %d", output);
3482 return;
3483 }
François Gaffie036e1e92015-03-19 10:16:24 +01003484 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003485
Eric Laurente552edb2014-03-10 17:42:56 -07003486 // look for duplicated outputs connected to the output being removed.
3487 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003488 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003489 if (dupOutputDesc->isDuplicated() &&
3490 (dupOutputDesc->mOutput1 == outputDesc ||
3491 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003492 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003493 if (dupOutputDesc->mOutput1 == outputDesc) {
3494 outputDesc2 = dupOutputDesc->mOutput2;
3495 } else {
3496 outputDesc2 = dupOutputDesc->mOutput1;
3497 }
3498 // As all active tracks on duplicated output will be deleted,
3499 // and as they were also referenced on the other output, the reference
3500 // count for their stream type must be adjusted accordingly on
3501 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003502 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003503 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003504 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003505 }
3506 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3507 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3508
3509 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01003510 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003511 }
3512 }
3513
Eric Laurent05b90f82014-08-27 15:32:29 -07003514 nextAudioPortGeneration();
3515
3516 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3517 if (index >= 0) {
3518 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3519 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3520 mAudioPatches.removeItemsAt(index);
3521 mpClientInterface->onAudioPatchListUpdate();
3522 }
3523
Eric Laurente552edb2014-03-10 17:42:56 -07003524 AudioParameter param;
3525 param.add(String8("closing"), String8("true"));
3526 mpClientInterface->setParameters(output, param.toString());
3527
3528 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003529 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003530 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003531}
3532
3533void AudioPolicyManager::closeInput(audio_io_handle_t input)
3534{
3535 ALOGV("closeInput(%d)", input);
3536
3537 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3538 if (inputDesc == NULL) {
3539 ALOGW("closeInput() unknown input %d", input);
3540 return;
3541 }
3542
Eric Laurent6a94d692014-05-20 11:18:06 -07003543 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003544
3545 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3546 if (index >= 0) {
3547 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3548 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3549 mAudioPatches.removeItemsAt(index);
3550 mpClientInterface->onAudioPatchListUpdate();
3551 }
3552
3553 mpClientInterface->closeInput(input);
3554 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003555}
3556
Eric Laurentc75307b2015-03-17 15:29:32 -07003557SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
3558 audio_devices_t device,
3559 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003560{
3561 SortedVector<audio_io_handle_t> outputs;
3562
3563 ALOGVV("getOutputsForDevice() device %04x", device);
3564 for (size_t i = 0; i < openOutputs.size(); i++) {
3565 ALOGVV("output %d isDuplicated=%d device=%04x",
3566 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3567 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3568 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3569 outputs.add(openOutputs.keyAt(i));
3570 }
3571 }
3572 return outputs;
3573}
3574
Eric Laurente0720872014-03-11 09:30:41 -07003575bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01003576 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07003577{
3578 if (outputs1.size() != outputs2.size()) {
3579 return false;
3580 }
3581 for (size_t i = 0; i < outputs1.size(); i++) {
3582 if (outputs1[i] != outputs2[i]) {
3583 return false;
3584 }
3585 }
3586 return true;
3587}
3588
Eric Laurente0720872014-03-11 09:30:41 -07003589void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003590{
3591 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3592 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3593 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3594 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3595
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003596 // also take into account external policy-related changes: add all outputs which are
3597 // associated with policies in the "before" and "after" output vectors
3598 ALOGVV("checkOutputForStrategy(): policy related outputs");
3599 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003600 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003601 if (desc != 0 && desc->mPolicyMix != NULL) {
3602 srcOutputs.add(desc->mIoHandle);
3603 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
3604 }
3605 }
3606 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003607 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003608 if (desc != 0 && desc->mPolicyMix != NULL) {
3609 dstOutputs.add(desc->mIoHandle);
3610 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
3611 }
3612 }
3613
Eric Laurente552edb2014-03-10 17:42:56 -07003614 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3615 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3616 strategy, srcOutputs[0], dstOutputs[0]);
3617 // mute strategy while moving tracks from one output to another
3618 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003619 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01003620 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003621 setStrategyMute(strategy, true, desc);
3622 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07003623 }
3624 }
3625
3626 // Move effects associated to this strategy from previous output to new output
3627 if (strategy == STRATEGY_MEDIA) {
3628 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3629 SortedVector<audio_io_handle_t> moved;
3630 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003631 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3632 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3633 effectDesc->mIo != fxOutput) {
3634 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003635 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3636 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003637 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003638 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003639 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003640 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003641 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003642 }
3643 }
3644 }
3645 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003646 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08003647 if (i == AUDIO_STREAM_PATCH) {
3648 continue;
3649 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003650 if (getStrategy((audio_stream_type_t)i) == strategy) {
3651 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003652 }
3653 }
3654 }
3655}
3656
Eric Laurente0720872014-03-11 09:30:41 -07003657void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003658{
François Gaffie2110e042015-03-24 08:41:51 +01003659 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05003660 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003661 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01003662 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05003663 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003664 checkOutputForStrategy(STRATEGY_SONIFICATION);
3665 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003666 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07003667 checkOutputForStrategy(STRATEGY_MEDIA);
3668 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003669 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07003670}
3671
Eric Laurente0720872014-03-11 09:30:41 -07003672void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003673{
François Gaffie53615e22015-03-19 09:24:12 +01003674 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07003675 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003676 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003677 return;
3678 }
3679
Eric Laurent3a4311c2014-03-17 12:00:47 -07003680 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08003681 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
3682 ~AUDIO_DEVICE_BIT_IN) != 0) ||
3683 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003684 // suspend A2DP output if:
3685 // (NOT already suspended) &&
3686 // ((SCO device is connected &&
3687 // (forced usage for communication || for record is SCO))) ||
3688 // (phone state is ringing || in call)
3689 //
3690 // restore A2DP output if:
3691 // (Already suspended) &&
3692 // ((SCO device is NOT connected ||
3693 // (forced usage NOT for communication && NOT for record is SCO))) &&
3694 // (phone state is NOT ringing && NOT in call)
3695 //
3696 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003697 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01003698 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
3699 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
3700 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
3701 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003702
3703 mpClientInterface->restoreOutput(a2dpOutput);
3704 mA2dpSuspended = false;
3705 }
3706 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003707 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01003708 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
3709 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
3710 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
3711 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003712
3713 mpClientInterface->suspendOutput(a2dpOutput);
3714 mA2dpSuspended = true;
3715 }
3716 }
3717}
3718
Eric Laurentc75307b2015-03-17 15:29:32 -07003719audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
3720 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003721{
3722 audio_devices_t device = AUDIO_DEVICE_NONE;
3723
Eric Laurent6a94d692014-05-20 11:18:06 -07003724 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3725 if (index >= 0) {
3726 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3727 if (patchDesc->mUid != mUidCached) {
3728 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3729 outputDesc->device(), outputDesc->mPatchHandle);
3730 return outputDesc->device();
3731 }
3732 }
3733
Eric Laurente552edb2014-03-10 17:42:56 -07003734 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003735 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003736 // use device for strategy enforced audible
3737 // 2: we are in call or the strategy phone is active on the output:
3738 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003739 // 3: the strategy for enforced audible is active but not enforced on the output:
3740 // use the device for strategy enforced audible
3741 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003742 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003743 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003744 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08003745 // 6: the strategy accessibility is active on the output:
3746 // use device for strategy accessibility
3747 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003748 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08003749 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003750 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08003751 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003752 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01003753 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01003754 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003755 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3756 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01003757 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003758 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003759 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05003760 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003761 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003762 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003763 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003764 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003765 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08003766 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003767 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003768 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003769 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003770 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003771 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003772 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01003773 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08003774 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003775 }
3776
Eric Laurent1c333e22014-05-20 10:48:17 -07003777 ALOGV("getNewOutputDevice() selected device %x", device);
3778 return device;
3779}
3780
3781audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3782{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003783 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003784
3785 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3786 if (index >= 0) {
3787 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3788 if (patchDesc->mUid != mUidCached) {
3789 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3790 inputDesc->mDevice, inputDesc->mPatchHandle);
3791 return inputDesc->mDevice;
3792 }
3793 }
3794
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003795 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07003796
Eric Laurente552edb2014-03-10 17:42:56 -07003797 return device;
3798}
3799
Eric Laurente0720872014-03-11 09:30:41 -07003800uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003801 return (uint32_t)getStrategy(stream);
3802}
3803
Eric Laurente0720872014-03-11 09:30:41 -07003804audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003805 // By checking the range of stream before calling getStrategy, we avoid
3806 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3807 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08003808 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003809 return AUDIO_DEVICE_NONE;
3810 }
3811 audio_devices_t devices;
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08003812 routing_strategy strategy = getStrategy(stream);
Eric Laurent6a94d692014-05-20 11:18:06 -07003813 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3814 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3815 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003816 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01003817 if (isStrategyActive(outputDesc, strategy)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003818 devices = outputDesc->device();
3819 break;
3820 }
Eric Laurente552edb2014-03-10 17:42:56 -07003821 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003822
3823 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3824 and doesn't really need to.*/
3825 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3826 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3827 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3828 }
3829
Eric Laurente552edb2014-03-10 17:42:56 -07003830 return devices;
3831}
3832
François Gaffie2110e042015-03-24 08:41:51 +01003833routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
3834{
Eric Laurent223fd5c2014-11-11 13:43:36 -08003835 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01003836 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07003837}
3838
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003839uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3840 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003841 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
3842 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
3843 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003844 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3845 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3846 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003847 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01003848 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003849}
3850
Eric Laurente0720872014-03-11 09:30:41 -07003851void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003852 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003853 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003854 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3855 updateDevicesAndOutputs();
3856 break;
3857 default:
3858 break;
3859 }
3860}
3861
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003862uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
3863 switch(event) {
3864 case STARTING_OUTPUT:
3865 mBeaconMuteRefCount++;
3866 break;
3867 case STOPPING_OUTPUT:
3868 if (mBeaconMuteRefCount > 0) {
3869 mBeaconMuteRefCount--;
3870 }
3871 break;
3872 case STARTING_BEACON:
3873 mBeaconPlayingRefCount++;
3874 break;
3875 case STOPPING_BEACON:
3876 if (mBeaconPlayingRefCount > 0) {
3877 mBeaconPlayingRefCount--;
3878 }
3879 break;
3880 }
3881
3882 if (mBeaconMuteRefCount > 0) {
3883 // any playback causes beacon to be muted
3884 return setBeaconMute(true);
3885 } else {
3886 // no other playback: unmute when beacon starts playing, mute when it stops
3887 return setBeaconMute(mBeaconPlayingRefCount == 0);
3888 }
3889}
3890
3891uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
3892 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
3893 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
3894 // keep track of muted state to avoid repeating mute/unmute operations
3895 if (mBeaconMuted != mute) {
3896 // mute/unmute AUDIO_STREAM_TTS on all outputs
3897 ALOGV("\t muting %d", mute);
3898 uint32_t maxLatency = 0;
3899 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003900 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003901 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07003902 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003903 0 /*delay*/, AUDIO_DEVICE_NONE);
3904 const uint32_t latency = desc->latency() * 2;
3905 if (latency > maxLatency) {
3906 maxLatency = latency;
3907 }
3908 }
3909 mBeaconMuted = mute;
3910 return maxLatency;
3911 }
3912 return 0;
3913}
3914
Eric Laurente0720872014-03-11 09:30:41 -07003915audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01003916 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003917{
Paul McLeanaa981192015-03-21 09:55:15 -07003918 // Routing
3919 // see if we have an explicit route
3920 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
3921 // (getStrategy(stream)).
3922 // if the strategy from the stream type in the RouteMap is the same as the argument above,
3923 // and activity count is non-zero
3924 // the device = the device from the descriptor in the RouteMap, and exit.
3925 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
3926 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
3927 routing_strategy strat = getStrategy(route->mStreamType);
3928 if (strat == strategy && route->mDeviceDescriptor != 0 /*&& route->mActivityCount != 0*/) {
3929 return route->mDeviceDescriptor->type();
3930 }
3931 }
3932
Eric Laurente552edb2014-03-10 17:42:56 -07003933 if (fromCache) {
3934 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3935 strategy, mDeviceForStrategy[strategy]);
3936 return mDeviceForStrategy[strategy];
3937 }
François Gaffie2110e042015-03-24 08:41:51 +01003938 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07003939}
3940
Eric Laurente0720872014-03-11 09:30:41 -07003941void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003942{
3943 for (int i = 0; i < NUM_STRATEGIES; i++) {
3944 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3945 }
3946 mPreviousOutputs = mOutputs;
3947}
3948
Eric Laurent1f2f2232014-06-02 12:01:23 -07003949uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003950 audio_devices_t prevDevice,
3951 uint32_t delayMs)
3952{
3953 // mute/unmute strategies using an incompatible device combination
3954 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3955 // if unmuting, unmute only after the specified delay
3956 if (outputDesc->isDuplicated()) {
3957 return 0;
3958 }
3959
3960 uint32_t muteWaitMs = 0;
3961 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003962 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003963
3964 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3965 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07003966 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07003967 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3968 bool doMute = false;
3969
3970 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3971 doMute = true;
3972 outputDesc->mStrategyMutedByDevice[i] = true;
3973 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3974 doMute = true;
3975 outputDesc->mStrategyMutedByDevice[i] = false;
3976 }
Eric Laurent99401132014-05-07 19:48:15 -07003977 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003978 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003979 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003980 // skip output if it does not share any device with current output
3981 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3982 == AUDIO_DEVICE_NONE) {
3983 continue;
3984 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003985 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
3986 mute ? "muting" : "unmuting", i, curDevice);
3987 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01003988 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003989 if (mute) {
3990 // FIXME: should not need to double latency if volume could be applied
3991 // immediately by the audioflinger mixer. We must account for the delay
3992 // between now and the next time the audioflinger thread for this output
3993 // will process a buffer (which corresponds to one buffer size,
3994 // usually 1/2 or 1/4 of the latency).
3995 if (muteWaitMs < desc->latency() * 2) {
3996 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003997 }
3998 }
3999 }
4000 }
4001 }
4002 }
4003
Eric Laurent99401132014-05-07 19:48:15 -07004004 // temporary mute output if device selection changes to avoid volume bursts due to
4005 // different per device volumes
4006 if (outputDesc->isActive() && (device != prevDevice)) {
4007 if (muteWaitMs < outputDesc->latency() * 2) {
4008 muteWaitMs = outputDesc->latency() * 2;
4009 }
4010 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004011 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004012 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004013 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004014 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004015 muteWaitMs *2, device);
4016 }
4017 }
4018 }
4019
Eric Laurente552edb2014-03-10 17:42:56 -07004020 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4021 if (muteWaitMs > delayMs) {
4022 muteWaitMs -= delayMs;
4023 usleep(muteWaitMs * 1000);
4024 return muteWaitMs;
4025 }
4026 return 0;
4027}
4028
Eric Laurentc75307b2015-03-17 15:29:32 -07004029uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004030 audio_devices_t device,
4031 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004032 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004033 audio_patch_handle_t *patchHandle,
4034 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004035{
Eric Laurentc75307b2015-03-17 15:29:32 -07004036 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004037 AudioParameter param;
4038 uint32_t muteWaitMs;
4039
4040 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004041 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4042 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004043 return muteWaitMs;
4044 }
4045 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4046 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004047 if ((device != AUDIO_DEVICE_NONE) &&
4048 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004049 return 0;
4050 }
4051
4052 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004053 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004054
4055 audio_devices_t prevDevice = outputDesc->mDevice;
4056
Paul McLeanaa981192015-03-21 09:55:15 -07004057 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004058
4059 if (device != AUDIO_DEVICE_NONE) {
4060 outputDesc->mDevice = device;
4061 }
4062 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4063
4064 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004065 // the requested device is AUDIO_DEVICE_NONE
4066 // OR the requested device is the same as current device
4067 // AND force is not specified
4068 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004069 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004070 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4071 !force &&
4072 outputDesc->mPatchHandle != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004073 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004074 return muteWaitMs;
4075 }
4076
4077 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004078
Eric Laurente552edb2014-03-10 17:42:56 -07004079 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004080 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004081 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004082 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004083 DeviceVector deviceList = (address == NULL) ?
4084 mAvailableOutputDevices.getDevicesFromType(device)
4085 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004086 if (!deviceList.isEmpty()) {
4087 struct audio_patch patch;
4088 outputDesc->toAudioPortConfig(&patch.sources[0]);
4089 patch.num_sources = 1;
4090 patch.num_sinks = 0;
4091 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4092 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004093 patch.num_sinks++;
4094 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004095 ssize_t index;
4096 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4097 index = mAudioPatches.indexOfKey(*patchHandle);
4098 } else {
4099 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4100 }
4101 sp< AudioPatch> patchDesc;
4102 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4103 if (index >= 0) {
4104 patchDesc = mAudioPatches.valueAt(index);
4105 afPatchHandle = patchDesc->mAfPatchHandle;
4106 }
4107
Eric Laurent1c333e22014-05-20 10:48:17 -07004108 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004109 &afPatchHandle,
4110 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004111 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4112 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004113 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004114 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004115 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004116 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004117 addAudioPatch(patchDesc->mHandle, patchDesc);
4118 } else {
4119 patchDesc->mPatch = patch;
4120 }
4121 patchDesc->mAfPatchHandle = afPatchHandle;
4122 patchDesc->mUid = mUidCached;
4123 if (patchHandle) {
4124 *patchHandle = patchDesc->mHandle;
4125 }
4126 outputDesc->mPatchHandle = patchDesc->mHandle;
4127 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004128 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004129 }
4130 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004131
4132 // inform all input as well
4133 for (size_t i = 0; i < mInputs.size(); i++) {
4134 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004135 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004136 AudioParameter inputCmd = AudioParameter();
4137 ALOGV("%s: inform input %d of device:%d", __func__,
4138 inputDescriptor->mIoHandle, device);
4139 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4140 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4141 inputCmd.toString(),
4142 delayMs);
4143 }
4144 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004145 }
Eric Laurente552edb2014-03-10 17:42:56 -07004146
4147 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004148 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004149
4150 return muteWaitMs;
4151}
4152
Eric Laurentc75307b2015-03-17 15:29:32 -07004153status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 int delayMs,
4155 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004156{
Eric Laurent6a94d692014-05-20 11:18:06 -07004157 ssize_t index;
4158 if (patchHandle) {
4159 index = mAudioPatches.indexOfKey(*patchHandle);
4160 } else {
4161 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4162 }
4163 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004164 return INVALID_OPERATION;
4165 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004166 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4167 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004168 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4169 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004170 removeAudioPatch(patchDesc->mHandle);
4171 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004172 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004173 return status;
4174}
4175
4176status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4177 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004178 bool force,
4179 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004180{
4181 status_t status = NO_ERROR;
4182
Eric Laurent1f2f2232014-06-02 12:01:23 -07004183 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004184 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4185 inputDesc->mDevice = device;
4186
4187 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4188 if (!deviceList.isEmpty()) {
4189 struct audio_patch patch;
4190 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004191 // AUDIO_SOURCE_HOTWORD is for internal use only:
4192 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004193 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4194 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004195 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4196 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004197 patch.num_sinks = 1;
4198 //only one input device for now
4199 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004200 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004201 ssize_t index;
4202 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4203 index = mAudioPatches.indexOfKey(*patchHandle);
4204 } else {
4205 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4206 }
4207 sp< AudioPatch> patchDesc;
4208 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4209 if (index >= 0) {
4210 patchDesc = mAudioPatches.valueAt(index);
4211 afPatchHandle = patchDesc->mAfPatchHandle;
4212 }
4213
Eric Laurent1c333e22014-05-20 10:48:17 -07004214 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004216 0);
4217 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004218 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004219 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004221 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004222 addAudioPatch(patchDesc->mHandle, patchDesc);
4223 } else {
4224 patchDesc->mPatch = patch;
4225 }
4226 patchDesc->mAfPatchHandle = afPatchHandle;
4227 patchDesc->mUid = mUidCached;
4228 if (patchHandle) {
4229 *patchHandle = patchDesc->mHandle;
4230 }
4231 inputDesc->mPatchHandle = patchDesc->mHandle;
4232 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004233 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004234 }
4235 }
4236 }
4237 return status;
4238}
4239
Eric Laurent6a94d692014-05-20 11:18:06 -07004240status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4241 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004242{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004243 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004244 ssize_t index;
4245 if (patchHandle) {
4246 index = mAudioPatches.indexOfKey(*patchHandle);
4247 } else {
4248 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4249 }
4250 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004251 return INVALID_OPERATION;
4252 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004253 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4254 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004255 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4256 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004257 removeAudioPatch(patchDesc->mHandle);
4258 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004259 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004260 return status;
4261}
4262
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004263sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004264 String8 address,
4265 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004266 audio_format_t& format,
4267 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004268 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004269{
4270 // Choose an input profile based on the requested capture parameters: select the first available
4271 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004272 //
4273 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4274 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004275
4276 for (size_t i = 0; i < mHwModules.size(); i++)
4277 {
4278 if (mHwModules[i]->mHandle == 0) {
4279 continue;
4280 }
4281 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4282 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004283 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004284 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004285 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004286 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004287 format,
4288 &format /*updatedFormat*/,
4289 channelMask,
4290 &channelMask /*updatedChannelMask*/,
4291 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004292
Eric Laurente552edb2014-03-10 17:42:56 -07004293 return profile;
4294 }
4295 }
4296 }
4297 return NULL;
4298}
4299
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004300
4301audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004302 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004303{
François Gaffie036e1e92015-03-19 10:16:24 +01004304 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4305 audio_devices_t selectedDeviceFromMix =
4306 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004307
François Gaffie036e1e92015-03-19 10:16:24 +01004308 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4309 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004310 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004311 return getDeviceForInputSource(inputSource);
4312}
4313
4314audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4315{
Paul McLean466dc8e2015-04-17 13:15:36 -06004316 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4317 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
4318 if (inputSource == route->mSource && route->mDeviceDescriptor != 0
4319 /*&& route->mActivityCount != 0*/) {
4320 return route->mDeviceDescriptor->type();
4321 }
4322 }
4323
4324 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004325}
4326
Eric Laurente0720872014-03-11 09:30:41 -07004327float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004328 int index,
4329 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004330{
Eric Laurentffbc80f2015-03-18 18:30:19 -07004331 float volumeDb = mEngine->volIndexToDb(Volume::getDeviceCategory(device), stream, index);
Eric Laurente552edb2014-03-10 17:42:56 -07004332
4333 // if a headset is connected, apply the following rules to ring tones and notifications
4334 // to avoid sound level bursts in user's ears:
4335 // - always attenuate ring tones and notifications volume by 6dB
4336 // - if music is playing, always limit the volume to current music volume,
4337 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004338 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004339 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4340 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4341 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4342 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4343 ((stream_strategy == STRATEGY_SONIFICATION)
4344 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004345 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004346 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004347 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
4348 mStreams.canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004349 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004350 // when the phone is ringing we must consider that music could have been paused just before
4351 // by the music application and behave as if music was active if the last music track was
4352 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004353 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004354 mLimitRingtoneVolume) {
4355 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004356 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
4357 mStreams.valueFor(AUDIO_STREAM_MUSIC).getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004358 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004359 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4360 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4361 if (volumeDb > minVolDB) {
4362 volumeDb = minVolDB;
4363 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004364 }
4365 }
4366 }
4367
Eric Laurentffbc80f2015-03-18 18:30:19 -07004368 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004369}
4370
Eric Laurente0720872014-03-11 09:30:41 -07004371status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004372 int index,
4373 const sp<AudioOutputDescriptor>& outputDesc,
4374 audio_devices_t device,
4375 int delayMs,
4376 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004377{
Eric Laurente552edb2014-03-10 17:42:56 -07004378 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004379 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004380 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004381 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004382 return NO_ERROR;
4383 }
François Gaffie2110e042015-03-24 08:41:51 +01004384 audio_policy_forced_cfg_t forceUseForComm =
4385 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004386 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004387 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4388 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004389 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004390 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004391 return INVALID_OPERATION;
4392 }
4393
Eric Laurentc75307b2015-03-17 15:29:32 -07004394 if (device == AUDIO_DEVICE_NONE) {
4395 device = outputDesc->device();
4396 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004397
Eric Laurentffbc80f2015-03-18 18:30:19 -07004398 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004399 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004400 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004401 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004402
Eric Laurentffbc80f2015-03-18 18:30:19 -07004403 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004404
Eric Laurent3b73df72014-03-11 09:06:29 -07004405 if (stream == AUDIO_STREAM_VOICE_CALL ||
4406 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004407 float voiceVolume;
4408 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004409 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004410 voiceVolume = (float)index/(float)mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07004411 } else {
4412 voiceVolume = 1.0;
4413 }
4414
Eric Laurentc75307b2015-03-17 15:29:32 -07004415 if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
Eric Laurente552edb2014-03-10 17:42:56 -07004416 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4417 mLastVoiceVolume = voiceVolume;
4418 }
4419 }
4420
4421 return NO_ERROR;
4422}
4423
Eric Laurentc75307b2015-03-17 15:29:32 -07004424void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4425 audio_devices_t device,
4426 int delayMs,
4427 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004428{
Eric Laurentc75307b2015-03-17 15:29:32 -07004429 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004430
Eric Laurent3b73df72014-03-11 09:06:29 -07004431 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004432 if (stream == AUDIO_STREAM_PATCH) {
4433 continue;
4434 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004435 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004436 mStreams.valueFor((audio_stream_type_t)stream).getVolumeIndex(device),
4437 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004438 device,
4439 delayMs,
4440 force);
4441 }
4442}
4443
Eric Laurente0720872014-03-11 09:30:41 -07004444void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07004445 bool on,
4446 const sp<AudioOutputDescriptor>& outputDesc,
4447 int delayMs,
4448 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004449{
4450 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004451 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004452 if (stream == AUDIO_STREAM_PATCH) {
4453 continue;
4454 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004455 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004456 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004457 }
4458 }
4459}
4460
Eric Laurente0720872014-03-11 09:30:41 -07004461void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004462 bool on,
4463 const sp<AudioOutputDescriptor>& outputDesc,
4464 int delayMs,
4465 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004466{
Eric Laurentc75307b2015-03-17 15:29:32 -07004467 const StreamDescriptor& streamDesc = mStreams.valueFor(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004468 if (device == AUDIO_DEVICE_NONE) {
4469 device = outputDesc->device();
4470 }
4471
Eric Laurentc75307b2015-03-17 15:29:32 -07004472 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
4473 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07004474
4475 if (on) {
4476 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffiedfd74092015-03-19 12:10:59 +01004477 if (streamDesc.canBeMuted() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004478 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01004479 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004480 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004481 }
4482 }
4483 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4484 outputDesc->mMuteCount[stream]++;
4485 } else {
4486 if (outputDesc->mMuteCount[stream] == 0) {
4487 ALOGV("setStreamMute() unmuting non muted stream!");
4488 return;
4489 }
4490 if (--outputDesc->mMuteCount[stream] == 0) {
4491 checkAndSetVolume(stream,
4492 streamDesc.getVolumeIndex(device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004493 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004494 device,
4495 delayMs);
4496 }
4497 }
4498}
4499
Eric Laurente0720872014-03-11 09:30:41 -07004500void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004501 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004502{
4503 // if the stream pertains to sonification strategy and we are in call we must
4504 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4505 // in the device used for phone strategy and play the tone if the selected device does not
4506 // interfere with the device used for phone strategy
4507 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4508 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004509 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004510 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4511 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004512 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004513 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4514 stream, starting, outputDesc->mDevice, stateChange);
4515 if (outputDesc->mRefCount[stream]) {
4516 int muteCount = 1;
4517 if (stateChange) {
4518 muteCount = outputDesc->mRefCount[stream];
4519 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004520 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004521 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4522 for (int i = 0; i < muteCount; i++) {
4523 setStreamMute(stream, starting, mPrimaryOutput);
4524 }
4525 } else {
4526 ALOGV("handleIncallSonification() high visibility");
4527 if (outputDesc->device() &
4528 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4529 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4530 for (int i = 0; i < muteCount; i++) {
4531 setStreamMute(stream, starting, mPrimaryOutput);
4532 }
4533 }
4534 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004535 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4536 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004537 } else {
4538 mpClientInterface->stopTone();
4539 }
4540 }
4541 }
4542 }
4543}
4544
Paul McLeanaa981192015-03-21 09:55:15 -07004545// --- SessionRoute class implementation
4546void AudioPolicyManager::SessionRoute::log(const char* prefix) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004547 ALOGI("%s[SessionRoute strm:0x%X, src:%d, sess:0x%X, dev:0x%X refs:%d act:%d",
4548 prefix, mStreamType, mSource, mSession,
Paul McLeanaa981192015-03-21 09:55:15 -07004549 mDeviceDescriptor != 0 ? mDeviceDescriptor->type() : AUDIO_DEVICE_NONE,
4550 mRefCount, mActivityCount);
4551}
4552
4553// --- SessionRouteMap class implementation
4554bool AudioPolicyManager::SessionRouteMap::hasRoute(audio_session_t session)
4555{
4556 return indexOfKey(session) >= 0 && valueFor(session)->mDeviceDescriptor != 0;
4557}
4558
Eric Laurent493404d2015-04-21 15:07:36 -07004559bool AudioPolicyManager::SessionRouteMap::hasRouteChanged(audio_session_t session)
4560{
4561 if (indexOfKey(session) >= 0) {
4562 if (valueFor(session)->mChanged) {
4563 valueFor(session)->mChanged = false;
4564 return true;
4565 }
4566 }
4567 return false;
4568}
4569
Paul McLeanaa981192015-03-21 09:55:15 -07004570void AudioPolicyManager::SessionRouteMap::removeRoute(audio_session_t session)
4571{
4572 sp<SessionRoute> route = indexOfKey(session) >= 0 ? valueFor(session) : 0;
4573 if (route != 0) {
4574 ALOG_ASSERT(route->mRefCount > 0);
4575 --route->mRefCount;
4576 if (route->mRefCount <= 0) {
4577 removeItem(session);
4578 }
4579 }
4580}
4581
4582int AudioPolicyManager::SessionRouteMap::incRouteActivity(audio_session_t session)
4583{
4584 sp<SessionRoute> route = indexOfKey(session) >= 0 ? valueFor(session) : 0;
4585 return route != 0 ? ++(route->mActivityCount) : -1;
4586}
4587
4588int AudioPolicyManager::SessionRouteMap::decRouteActivity(audio_session_t session)
4589{
4590 sp<SessionRoute> route = indexOfKey(session) >= 0 ? valueFor(session) : 0;
4591 if (route != 0 && route->mActivityCount > 0) {
4592 return --(route->mActivityCount);
4593 } else {
4594 return -1;
4595 }
4596}
4597
4598void AudioPolicyManager::SessionRouteMap::log(const char* caption) {
4599 ALOGI("%s ----", caption);
4600 for(size_t index = 0; index < size(); index++) {
4601 valueAt(index)->log(" ");
4602 }
4603}
4604
Paul McLean466dc8e2015-04-17 13:15:36 -06004605void AudioPolicyManager::SessionRouteMap::addRoute(audio_session_t session,
4606 audio_stream_type_t streamType,
4607 audio_source_t source,
4608 sp<DeviceDescriptor> descriptor)
4609{
4610 if (mMapType == MAPTYPE_INPUT && streamType != SessionRoute::STREAM_TYPE_NA) {
4611 ALOGE("Adding Output Route to InputRouteMap");
4612 return;
4613 } else if (mMapType == MAPTYPE_OUTPUT && source != SessionRoute::SOURCE_TYPE_NA) {
4614 ALOGE("Adding Input Route to OutputRouteMap");
4615 return;
4616 }
4617
4618 sp<SessionRoute> route = indexOfKey(session) >= 0 ? valueFor(session) : 0;
4619
4620 if (route != 0) {
4621 if ((route->mDeviceDescriptor == 0 && descriptor != 0) ||
4622 (!route->mDeviceDescriptor->equals(descriptor))) {
4623 route->mChanged = true;
4624 }
4625 route->mRefCount++;
4626 route->mDeviceDescriptor = descriptor;
4627 } else {
4628 route = new AudioPolicyManager::SessionRoute(session, streamType, source, descriptor);
4629 route->mRefCount++;
4630 add(session, route);
4631 if (descriptor != 0) {
4632 route->mChanged = true;
4633 }
4634 }
4635}
4636
Eric Laurente0720872014-03-11 09:30:41 -07004637void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07004638{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004639 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07004640 sp<IOProfile> profile;
Paul McLeane743a472015-01-28 11:07:31 -08004641 sp<DeviceDescriptor> defaultInputDevice =
4642 new DeviceDescriptor(String8("builtin-mic"), AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004643 mAvailableOutputDevices.add(mDefaultOutputDevice);
4644 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004645
4646 module = new HwModule("primary");
4647
Eric Laurent322b4d22015-04-03 15:57:54 -07004648 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE);
4649 profile->attach(module);
Eric Laurente552edb2014-03-10 17:42:56 -07004650 profile->mSamplingRates.add(44100);
4651 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4652 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004654 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4655 module->mOutputProfiles.add(profile);
4656
Eric Laurent322b4d22015-04-03 15:57:54 -07004657 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK);
4658 profile->attach(module);
Eric Laurente552edb2014-03-10 17:42:56 -07004659 profile->mSamplingRates.add(8000);
4660 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4661 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004662 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004663 module->mInputProfiles.add(profile);
4664
4665 mHwModules.add(module);
4666}
4667
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004668audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
4669{
4670 // flags to stream type mapping
4671 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4672 return AUDIO_STREAM_ENFORCED_AUDIBLE;
4673 }
4674 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
4675 return AUDIO_STREAM_BLUETOOTH_SCO;
4676 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08004677 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4678 return AUDIO_STREAM_TTS;
4679 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004680
4681 // usage to stream type mapping
4682 switch (attr->usage) {
4683 case AUDIO_USAGE_MEDIA:
4684 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004685 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4686 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004687 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08004688 if (isStreamActive(AUDIO_STREAM_ALARM)) {
4689 return AUDIO_STREAM_ALARM;
4690 }
4691 if (isStreamActive(AUDIO_STREAM_RING)) {
4692 return AUDIO_STREAM_RING;
4693 }
4694 if (isInCall()) {
4695 return AUDIO_STREAM_VOICE_CALL;
4696 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08004697 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004698 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4699 return AUDIO_STREAM_SYSTEM;
4700 case AUDIO_USAGE_VOICE_COMMUNICATION:
4701 return AUDIO_STREAM_VOICE_CALL;
4702
4703 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4704 return AUDIO_STREAM_DTMF;
4705
4706 case AUDIO_USAGE_ALARM:
4707 return AUDIO_STREAM_ALARM;
4708 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4709 return AUDIO_STREAM_RING;
4710
4711 case AUDIO_USAGE_NOTIFICATION:
4712 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4713 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4714 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4715 case AUDIO_USAGE_NOTIFICATION_EVENT:
4716 return AUDIO_STREAM_NOTIFICATION;
4717
4718 case AUDIO_USAGE_UNKNOWN:
4719 default:
4720 return AUDIO_STREAM_MUSIC;
4721 }
4722}
Eric Laurente83b55d2014-11-14 10:06:21 -08004723
François Gaffie53615e22015-03-19 09:24:12 +01004724bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
4725{
Eric Laurente83b55d2014-11-14 10:06:21 -08004726 // has flags that map to a strategy?
4727 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
4728 return true;
4729 }
4730
4731 // has known usage?
4732 switch (paa->usage) {
4733 case AUDIO_USAGE_UNKNOWN:
4734 case AUDIO_USAGE_MEDIA:
4735 case AUDIO_USAGE_VOICE_COMMUNICATION:
4736 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4737 case AUDIO_USAGE_ALARM:
4738 case AUDIO_USAGE_NOTIFICATION:
4739 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4740 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4741 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4742 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4743 case AUDIO_USAGE_NOTIFICATION_EVENT:
4744 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4745 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4746 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4747 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08004748 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08004749 break;
4750 default:
4751 return false;
4752 }
4753 return true;
4754}
4755
François Gaffiead3183e2015-03-18 16:55:35 +01004756bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
4757 routing_strategy strategy, uint32_t inPastMs,
4758 nsecs_t sysTime) const
4759{
4760 if ((sysTime == 0) && (inPastMs != 0)) {
4761 sysTime = systemTime();
4762 }
4763 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4764 if (i == AUDIO_STREAM_PATCH) {
4765 continue;
4766 }
4767 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
4768 (NUM_STRATEGIES == strategy)) &&
4769 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
4770 return true;
4771 }
4772 }
4773 return false;
4774}
4775
François Gaffie2110e042015-03-24 08:41:51 +01004776audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
4777{
4778 return mEngine->getForceUse(usage);
4779}
4780
4781bool AudioPolicyManager::isInCall()
4782{
4783 return isStateInCall(mEngine->getPhoneState());
4784}
4785
4786bool AudioPolicyManager::isStateInCall(int state)
4787{
4788 return is_state_in_call(state);
4789}
4790
Eric Laurente552edb2014-03-10 17:42:56 -07004791}; // namespace android